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 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 const std::string strMessageMagic;
76 extern double dHashesPerSec;
77 extern int64 nHPSTimerStart;
78 extern int64 nTimeBestReceived;
79 extern CCriticalSection cs_setpwalletRegistered;
80 extern std::set<CWallet*> setpwalletRegistered;
81 extern std::map<uint256, CBlock*> mapOrphanBlocks;
84 extern int64 nTransactionFee;
94 void RegisterWallet(CWallet* pwalletIn);
95 void UnregisterWallet(CWallet* pwalletIn);
96 bool ProcessBlock(CNode* pfrom, CBlock* pblock);
97 bool CheckDiskSpace(uint64 nAdditionalBytes=0);
98 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
99 FILE* AppendBlockFile(unsigned int& nFileRet);
100 bool LoadBlockIndex(bool fAllowNew=true);
101 void PrintBlockTree();
102 bool ProcessMessages(CNode* pfrom);
103 bool SendMessages(CNode* pto, bool fSendTrickle);
104 void GenerateBitcoins(bool fGenerate, CWallet* pwallet);
105 CBlock* CreateNewBlock(CWallet* pwallet, bool fProofOfStake=false);
106 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce);
107 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
108 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey);
109 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
110 int64 GetProofOfWorkReward(unsigned int nBits);
111 int64 GetProofOfStakeReward(int64 nCoinAge);
112 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime);
113 int GetNumBlocksOfPeers();
114 bool IsInitialBlockDownload();
115 std::string GetWarnings(std::string strFor);
116 uint256 WantedByOrphan(const CBlock* pblockOrphan);
117 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake);
118 void BitcoinMiner(CWallet *pwallet, bool fProofOfStake);
130 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
132 /** Position on disk for a particular transaction. */
137 unsigned int nBlockPos;
145 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
148 nBlockPos = nBlockPosIn;
152 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
153 void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
154 bool IsNull() const { return (nFile == -1); }
156 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
158 return (a.nFile == b.nFile &&
159 a.nBlockPos == b.nBlockPos &&
160 a.nTxPos == b.nTxPos);
163 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
168 std::string ToString() const
173 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
178 printf("%s", ToString().c_str());
184 /** An inpoint - a combination of a transaction and an index n into its vin */
191 CInPoint() { SetNull(); }
192 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
193 void SetNull() { ptx = NULL; n = -1; }
194 bool IsNull() const { return (ptx == NULL && n == -1); }
199 /** An outpoint - a combination of a transaction hash and an index n into its vout */
206 COutPoint() { SetNull(); }
207 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
208 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
209 void SetNull() { hash = 0; n = -1; }
210 bool IsNull() const { return (hash == 0 && n == -1); }
212 friend bool operator<(const COutPoint& a, const COutPoint& b)
214 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
217 friend bool operator==(const COutPoint& a, const COutPoint& b)
219 return (a.hash == b.hash && a.n == b.n);
222 friend bool operator!=(const COutPoint& a, const COutPoint& b)
227 std::string ToString() const
229 return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,10).c_str(), n);
234 printf("%s\n", ToString().c_str());
241 /** An input of a transaction. It contains the location of the previous
242 * transaction's output that it claims and a signature that matches the
243 * output's public key.
250 unsigned int nSequence;
254 nSequence = std::numeric_limits<unsigned int>::max();
257 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
260 scriptSig = scriptSigIn;
261 nSequence = nSequenceIn;
264 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
266 prevout = COutPoint(hashPrevTx, nOut);
267 scriptSig = scriptSigIn;
268 nSequence = nSequenceIn;
274 READWRITE(scriptSig);
275 READWRITE(nSequence);
280 return (nSequence == std::numeric_limits<unsigned int>::max());
283 friend bool operator==(const CTxIn& a, const CTxIn& b)
285 return (a.prevout == b.prevout &&
286 a.scriptSig == b.scriptSig &&
287 a.nSequence == b.nSequence);
290 friend bool operator!=(const CTxIn& a, const CTxIn& b)
295 std::string ToStringShort() const
297 return strprintf(" %s %d", prevout.hash.ToString().c_str(), prevout.n);
300 std::string ToString() const
304 str += prevout.ToString();
305 if (prevout.IsNull())
306 str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
308 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
309 if (nSequence != std::numeric_limits<unsigned int>::max())
310 str += strprintf(", nSequence=%u", nSequence);
317 printf("%s\n", ToString().c_str());
324 /** An output of a transaction. It contains the public key that the next input
325 * must be able to sign with to claim it.
331 CScript scriptPubKey;
338 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
341 scriptPubKey = scriptPubKeyIn;
347 READWRITE(scriptPubKey);
353 scriptPubKey.clear();
358 return (nValue == -1);
364 scriptPubKey.clear();
369 return (nValue == 0 && scriptPubKey.empty());
372 uint256 GetHash() const
374 return SerializeHash(*this);
377 friend bool operator==(const CTxOut& a, const CTxOut& b)
379 return (a.nValue == b.nValue &&
380 a.scriptPubKey == b.scriptPubKey);
383 friend bool operator!=(const CTxOut& a, const CTxOut& b)
388 std::string ToStringShort() const
390 return strprintf(" out amount %s", FormatMoney(nValue).c_str());
393 std::string ToString() const
395 if (IsEmpty()) return "CTxOut(empty)";
396 if (scriptPubKey.size() < 6)
397 return "CTxOut(error)";
398 return strprintf("CTxOut(nValue=%s, scriptPubKey=%s)", FormatMoney(nValue).c_str(), scriptPubKey.ToString().substr(0,30).c_str());
403 printf("%s\n", ToString().c_str());
417 typedef std::map<uint256, std::pair<CTxIndex, CTransaction> > MapPrevTx;
419 /** The basic transaction that is broadcasted on the network and contained in
420 * blocks. A transaction can contain multiple inputs and outputs.
427 std::vector<CTxIn> vin;
428 std::vector<CTxOut> vout;
429 unsigned int nLockTime;
431 // Denial-of-service detection:
433 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
442 READWRITE(this->nVersion);
443 nVersion = this->nVersion;
447 READWRITE(nLockTime);
453 nTime = GetAdjustedTime();
457 nDoS = 0; // Denial-of-service prevention
462 return (vin.empty() && vout.empty());
465 uint256 GetHash() const
467 return SerializeHash(*this);
470 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
472 // Time based nLockTime implemented in 0.1.6
475 if (nBlockHeight == 0)
476 nBlockHeight = nBestHeight;
478 nBlockTime = GetAdjustedTime();
479 if ((int64)nLockTime < ((int64)nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
481 BOOST_FOREACH(const CTxIn& txin, vin)
487 bool IsNewerThan(const CTransaction& old) const
489 if (vin.size() != old.vin.size())
491 for (unsigned int i = 0; i < vin.size(); i++)
492 if (vin[i].prevout != old.vin[i].prevout)
496 unsigned int nLowest = std::numeric_limits<unsigned int>::max();
497 for (unsigned int i = 0; i < vin.size(); i++)
499 if (vin[i].nSequence != old.vin[i].nSequence)
501 if (vin[i].nSequence <= nLowest)
504 nLowest = vin[i].nSequence;
506 if (old.vin[i].nSequence < nLowest)
509 nLowest = old.vin[i].nSequence;
516 bool IsCoinBase() const
518 return (vin.size() == 1 && vin[0].prevout.IsNull() && vout.size() >= 1);
521 bool IsCoinStake() const
523 // ppcoin: the coin stake transaction is marked with the first output empty
524 return (vin.size() > 0 && (!vin[0].prevout.IsNull()) && vout.size() >= 2 && vout[0].IsEmpty());
527 /** Check for standard transaction types
528 @return True if all outputs (scriptPubKeys) use only standard transaction forms
530 bool IsStandard() const;
532 /** Check for standard transaction types
533 @param[in] mapInputs Map of previous transactions that have outputs we're spending
534 @return True if all inputs (scriptSigs) use only standard transaction forms
535 @see CTransaction::FetchInputs
537 bool AreInputsStandard(const MapPrevTx& mapInputs) const;
539 /** Count ECDSA signature operations the old-fashioned (pre-0.6) way
540 @return number of sigops this transaction's outputs will produce when spent
541 @see CTransaction::FetchInputs
543 unsigned int GetLegacySigOpCount() const;
545 /** Count ECDSA signature operations in pay-to-script-hash inputs.
547 @param[in] mapInputs Map of previous transactions that have outputs we're spending
548 @return maximum number of sigops required to validate this transaction's inputs
549 @see CTransaction::FetchInputs
551 unsigned int GetP2SHSigOpCount(const MapPrevTx& mapInputs) const;
553 /** Amount of bitcoins spent by this transaction.
554 @return sum of all outputs (note: does not include fees)
556 int64 GetValueOut() const
559 BOOST_FOREACH(const CTxOut& txout, vout)
561 nValueOut += txout.nValue;
562 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
563 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
568 /** Amount of bitcoins coming in to this transaction
569 Note that lightweight clients may not know anything besides the hash of previous transactions,
570 so may not be able to calculate this.
572 @param[in] mapInputs Map of previous transactions that have outputs we're spending
573 @return Sum of value of all inputs (scriptSigs)
574 @see CTransaction::FetchInputs
576 int64 GetValueIn(const MapPrevTx& mapInputs) const;
578 static bool AllowFree(double dPriority)
580 // Large (in bytes) low-priority (new, small-coin) transactions
582 return dPriority > COIN * 144 / 250;
585 int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=false, enum GetMinFee_mode mode=GMF_BLOCK) const
587 // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
588 int64 nBaseFee = (mode == GMF_RELAY) ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
590 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION);
591 unsigned int nNewBlockSize = nBlockSize + nBytes;
592 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
598 // Transactions under 10K are free
599 // (about 4500bc if made of 50bc inputs)
605 // Free transaction area
606 if (nNewBlockSize < 27000)
611 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
612 if (nMinFee < nBaseFee)
614 BOOST_FOREACH(const CTxOut& txout, vout)
615 if (txout.nValue < CENT)
619 // Raise the price as the block approaches full
620 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
622 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
624 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
627 if (!MoneyRange(nMinFee))
633 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
635 CAutoFile filein = CAutoFile(OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb"), SER_DISK, CLIENT_VERSION);
637 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
640 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
641 return error("CTransaction::ReadFromDisk() : fseek failed");
646 catch (std::exception &e) {
647 return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
650 // Return file pointer
653 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
654 return error("CTransaction::ReadFromDisk() : second fseek failed");
655 *pfileRet = filein.release();
660 friend bool operator==(const CTransaction& a, const CTransaction& b)
662 return (a.nVersion == b.nVersion &&
663 a.nTime == b.nTime &&
666 a.nLockTime == b.nLockTime);
669 friend bool operator!=(const CTransaction& a, const CTransaction& b)
675 std::string ToStringShort() const
678 str += strprintf("%s %s", GetHash().ToString().c_str(), IsCoinBase()? "base" : (IsCoinStake()? "stake" : "user"));
682 std::string ToString() const
685 str += IsCoinBase()? "Coinbase" : (IsCoinStake()? "Coinstake" : "CTransaction");
686 str += strprintf("(hash=%s, nTime=%d, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
687 GetHash().ToString().substr(0,10).c_str(),
693 for (unsigned int i = 0; i < vin.size(); i++)
694 str += " " + vin[i].ToString() + "\n";
695 for (unsigned int i = 0; i < vout.size(); i++)
696 str += " " + vout[i].ToString() + "\n";
702 printf("%s", ToString().c_str());
706 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
707 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
708 bool ReadFromDisk(COutPoint prevout);
709 bool DisconnectInputs(CTxDB& txdb);
711 /** Fetch from memory and/or disk. inputsRet keys are transaction hashes.
713 @param[in] txdb Transaction database
714 @param[in] mapTestPool List of pending changes to the transaction index database
715 @param[in] fBlock True if being called to add a new best-block to the chain
716 @param[in] fMiner True if being called by CreateNewBlock
717 @param[out] inputsRet Pointers to this transaction's inputs
718 @param[out] fInvalid returns true if transaction is invalid
719 @return Returns true if all inputs are in txdb or mapTestPool
721 bool FetchInputs(CTxDB& txdb, const std::map<uint256, CTxIndex>& mapTestPool,
722 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid);
724 /** Sanity check previous transactions, then, if all checks succeed,
725 mark them as spent by this transaction.
727 @param[in] inputs Previous transactions (from FetchInputs)
728 @param[out] mapTestPool Keeps track of inputs that need to be updated on disk
729 @param[in] posThisTx Position of this transaction on disk
730 @param[in] pindexBlock
731 @param[in] fBlock true if called from ConnectBlock
732 @param[in] fMiner true if called from CreateNewBlock
733 @param[in] fStrictPayToScriptHash true if fully validating p2sh transactions
734 @return Returns true if all checks succeed
736 bool ConnectInputs(CTxDB& txdb, MapPrevTx inputs,
737 std::map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
738 const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash=true);
739 bool ClientConnectInputs();
740 bool CheckTransaction() const;
741 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
742 bool GetCoinAge(CTxDB& txdb, uint64& nCoinAge) const; // ppcoin: get transaction coin age
743 bool CheckProofOfStake(unsigned int nBits) const;
746 const CTxOut& GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const;
753 /** A transaction with a merkle branch linking it to the block chain. */
754 class CMerkleTx : public CTransaction
758 std::vector<uint256> vMerkleBranch;
762 mutable bool fMerkleVerified;
770 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
779 fMerkleVerified = false;
785 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
786 nVersion = this->nVersion;
787 READWRITE(hashBlock);
788 READWRITE(vMerkleBranch);
793 int SetMerkleBranch(const CBlock* pblock=NULL);
794 int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
795 int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
796 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
797 int GetBlocksToMaturity() const;
798 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
799 bool AcceptToMemoryPool();
805 /** A txdb record that contains the disk location of a transaction and the
806 * locations of transactions that spend its outputs. vSpent is really only
807 * used as a flag, but having the location is very helpful for debugging.
813 std::vector<CDiskTxPos> vSpent;
820 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
823 vSpent.resize(nOutputs);
828 if (!(nType & SER_GETHASH))
845 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
847 return (a.pos == b.pos &&
848 a.vSpent == b.vSpent);
851 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
855 int GetDepthInMainChain() const;
863 /** Nodes collect new transactions into a block, hash them into a hash tree,
864 * and scan through nonce values to make the block's hash satisfy proof-of-work
865 * requirements. When they solve the proof-of-work, they broadcast the block
866 * to everyone and the block is added to the block chain. The first transaction
867 * in the block is a special one that creates a new coin owned by the creator
870 * Blocks are appended to blk0001.dat files on disk. Their location on disk
871 * is indexed by CBlockIndex objects in memory.
878 uint256 hashPrevBlock;
879 uint256 hashMerkleRoot;
885 std::vector<CTransaction> vtx;
887 // ppcoin: block signature - signed by coin base txout[0]'s owner
888 std::vector<unsigned char> vchBlockSig;
891 mutable std::vector<uint256> vMerkleTree;
893 // Denial-of-service detection:
895 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
904 READWRITE(this->nVersion);
905 nVersion = this->nVersion;
906 READWRITE(hashPrevBlock);
907 READWRITE(hashMerkleRoot);
912 // ConnectBlock depends on vtx following header to generate CDiskTxPos
913 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
916 READWRITE(vchBlockSig);
920 const_cast<CBlock*>(this)->vtx.clear();
921 const_cast<CBlock*>(this)->vchBlockSig.clear();
944 uint256 GetHash() const
946 return Hash(BEGIN(nVersion), END(nNonce));
949 int64 GetBlockTime() const
954 void UpdateTime(const CBlockIndex* pindexPrev);
956 // ppcoin: two types of block: proof-of-work or proof-of-stake
957 bool IsProofOfStake() const
959 return (vtx.size() > 1 && vtx[1].IsCoinStake());
962 bool IsProofOfWork() const
964 return !IsProofOfStake();
967 std::pair<COutPoint, unsigned int> GetProofOfStake() const
969 return IsProofOfStake()? std::make_pair(vtx[1].vin[0].prevout, vtx[1].nTime) : std::make_pair(COutPoint(), (unsigned int)0);
972 // ppcoin: get max transaction timestamp
973 int64 GetMaxTransactionTime() const
975 int64 maxTransactionTime = 0;
976 BOOST_FOREACH(const CTransaction& tx, vtx)
977 maxTransactionTime = std::max(maxTransactionTime, (int64)tx.nTime);
978 return maxTransactionTime;
981 uint256 BuildMerkleTree() const
984 BOOST_FOREACH(const CTransaction& tx, vtx)
985 vMerkleTree.push_back(tx.GetHash());
987 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
989 for (int i = 0; i < nSize; i += 2)
991 int i2 = std::min(i+1, nSize-1);
992 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
993 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
997 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
1000 std::vector<uint256> GetMerkleBranch(int nIndex) const
1002 if (vMerkleTree.empty())
1004 std::vector<uint256> vMerkleBranch;
1006 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1008 int i = std::min(nIndex^1, nSize-1);
1009 vMerkleBranch.push_back(vMerkleTree[j+i]);
1013 return vMerkleBranch;
1016 static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
1020 BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
1023 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
1025 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
1032 bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
1034 // Open history file to append
1035 CAutoFile fileout = CAutoFile(AppendBlockFile(nFileRet), SER_DISK, CLIENT_VERSION);
1037 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
1039 // Write index header
1040 unsigned int nSize = fileout.GetSerializeSize(*this);
1041 fileout << FLATDATA(pchMessageStart) << nSize;
1044 long fileOutPos = ftell(fileout);
1046 return error("CBlock::WriteToDisk() : ftell failed");
1047 nBlockPosRet = fileOutPos;
1050 // Flush stdio buffers and commit to disk before returning
1052 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
1055 _commit(_fileno(fileout));
1057 fsync(fileno(fileout));
1064 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
1068 // Open history file to read
1069 CAutoFile filein = CAutoFile(OpenBlockFile(nFile, nBlockPos, "rb"), SER_DISK, CLIENT_VERSION);
1071 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1072 if (!fReadTransactions)
1073 filein.nType |= SER_BLOCKHEADERONLY;
1079 catch (std::exception &e) {
1080 return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
1084 if (fReadTransactions && IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
1085 return error("CBlock::ReadFromDisk() : errors in block header");
1094 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d, vchBlockSig=%s)\n",
1095 GetHash().ToString().substr(0,20).c_str(),
1097 hashPrevBlock.ToString().substr(0,20).c_str(),
1098 hashMerkleRoot.ToString().substr(0,10).c_str(),
1099 nTime, nBits, nNonce,
1101 HexStr(vchBlockSig.begin(), vchBlockSig.end()).c_str());
1102 for (unsigned int i = 0; i < vtx.size(); i++)
1107 printf(" vMerkleTree: ");
1108 for (unsigned int i = 0; i < vMerkleTree.size(); i++)
1109 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1114 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1115 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1116 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1117 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1118 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1119 bool CheckBlock() const;
1121 bool GetCoinAge(uint64& nCoinAge) const; // ppcoin: calculate total coin age spent in block
1122 bool SignBlock(const CKeyStore& keystore);
1123 bool CheckBlockSignature() const;
1126 bool SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew);
1134 /** The block chain is a tree shaped structure starting with the
1135 * genesis block at the root, with each block potentially having multiple
1136 * candidates to be the next block. pprev and pnext link a path through the
1137 * main/longest chain. A blockindex may have multiple pprev pointing back
1138 * to it, but pnext will only point forward to the longest branch, or will
1139 * be null if the block is not part of the longest chain.
1144 const uint256* phashBlock;
1148 unsigned int nBlockPos;
1149 CBigNum bnChainTrust; // ppcoin: trust score of block chain
1153 bool fProofOfStake; // ppcoin: is the block of proof-of-stake type
1154 COutPoint prevoutStake;
1155 unsigned int nStakeTime;
1159 uint256 hashMerkleRoot;
1162 unsigned int nNonce;
1176 fProofOfStake = true;
1177 prevoutStake.SetNull();
1187 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1193 nBlockPos = nBlockPosIn;
1198 fProofOfStake = block.IsProofOfStake();
1201 prevoutStake = block.vtx[1].vin[0].prevout;
1202 nStakeTime = block.vtx[1].nTime;
1206 prevoutStake.SetNull();
1210 nVersion = block.nVersion;
1211 hashMerkleRoot = block.hashMerkleRoot;
1212 nTime = block.nTime;
1213 nBits = block.nBits;
1214 nNonce = block.nNonce;
1217 CBlock GetBlockHeader() const
1220 block.nVersion = nVersion;
1222 block.hashPrevBlock = pprev->GetBlockHash();
1223 block.hashMerkleRoot = hashMerkleRoot;
1224 block.nTime = nTime;
1225 block.nBits = nBits;
1226 block.nNonce = nNonce;
1230 uint256 GetBlockHash() const
1235 int64 GetBlockTime() const
1237 return (int64)nTime;
1240 CBigNum GetBlockTrust() const
1243 bnTarget.SetCompact(nBits);
1246 return (fProofOfStake? (CBigNum(1)<<256) / (bnTarget+1) : 1);
1249 bool IsInMainChain() const
1251 return (pnext || this == pindexBest);
1254 bool CheckIndex() const
1256 return IsProofOfWork() ? CheckProofOfWork(GetBlockHash(), nBits) : true;
1259 bool EraseBlockFromDisk()
1261 // Open history file
1262 CAutoFile fileout = CAutoFile(OpenBlockFile(nFile, nBlockPos, "rb+"), SER_DISK, CLIENT_VERSION);
1266 // Overwrite with empty null block
1274 enum { nMedianTimeSpan=11 };
1276 int64 GetMedianTimePast() const
1278 int64 pmedian[nMedianTimeSpan];
1279 int64* pbegin = &pmedian[nMedianTimeSpan];
1280 int64* pend = &pmedian[nMedianTimeSpan];
1282 const CBlockIndex* pindex = this;
1283 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1284 *(--pbegin) = pindex->GetBlockTime();
1286 std::sort(pbegin, pend);
1287 return pbegin[(pend - pbegin)/2];
1290 int64 GetMedianTime() const
1292 const CBlockIndex* pindex = this;
1293 for (int i = 0; i < nMedianTimeSpan/2; i++)
1296 return GetBlockTime();
1297 pindex = pindex->pnext;
1299 return pindex->GetMedianTimePast();
1302 bool IsProofOfWork() const
1304 return !fProofOfStake;
1307 bool IsProofOfStake() const
1309 return fProofOfStake;
1312 std::string ToString() const
1314 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)",
1315 pprev, pnext, nFile, nBlockPos, nHeight,
1316 FormatMoney(nMint).c_str(), FormatMoney(nMoneySupply).c_str(),
1317 fProofOfStake, prevoutStake.ToString().c_str(), nStakeTime,
1318 hashMerkleRoot.ToString().substr(0,10).c_str(),
1319 GetBlockHash().ToString().substr(0,20).c_str());
1324 printf("%s\n", ToString().c_str());
1330 /** Used to marshal pointers into hashes for db storage. */
1331 class CDiskBlockIndex : public CBlockIndex
1343 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1345 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1346 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1351 if (!(nType & SER_GETHASH))
1352 READWRITE(nVersion);
1354 READWRITE(hashNext);
1356 READWRITE(nBlockPos);
1359 READWRITE(nMoneySupply);
1360 READWRITE(fProofOfStake);
1363 READWRITE(prevoutStake);
1364 READWRITE(nStakeTime);
1368 const_cast<CDiskBlockIndex*>(this)->prevoutStake.SetNull();
1369 const_cast<CDiskBlockIndex*>(this)->nStakeTime = 0;
1373 READWRITE(this->nVersion);
1374 READWRITE(hashPrev);
1375 READWRITE(hashMerkleRoot);
1381 uint256 GetBlockHash() const
1384 block.nVersion = nVersion;
1385 block.hashPrevBlock = hashPrev;
1386 block.hashMerkleRoot = hashMerkleRoot;
1387 block.nTime = nTime;
1388 block.nBits = nBits;
1389 block.nNonce = nNonce;
1390 return block.GetHash();
1394 std::string ToString() const
1396 std::string str = "CDiskBlockIndex(";
1397 str += CBlockIndex::ToString();
1398 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1399 GetBlockHash().ToString().c_str(),
1400 hashPrev.ToString().substr(0,20).c_str(),
1401 hashNext.ToString().substr(0,20).c_str());
1407 printf("%s\n", ToString().c_str());
1418 /** Describes a place in the block chain to another node such that if the
1419 * other node doesn't have the same branch, it can find a recent common trunk.
1420 * The further back it is, the further before the fork it may be.
1425 std::vector<uint256> vHave;
1432 explicit CBlockLocator(const CBlockIndex* pindex)
1437 explicit CBlockLocator(uint256 hashBlock)
1439 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1440 if (mi != mapBlockIndex.end())
1444 CBlockLocator(const std::vector<uint256>& vHaveIn)
1451 if (!(nType & SER_GETHASH))
1452 READWRITE(nVersion);
1463 return vHave.empty();
1466 void Set(const CBlockIndex* pindex)
1472 vHave.push_back(pindex->GetBlockHash());
1474 // Exponentially larger steps back
1475 for (int i = 0; pindex && i < nStep; i++)
1476 pindex = pindex->pprev;
1477 if (vHave.size() > 10)
1480 vHave.push_back(hashGenesisBlock);
1483 int GetDistanceBack()
1485 // Retrace how far back it was in the sender's branch
1488 BOOST_FOREACH(const uint256& hash, vHave)
1490 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1491 if (mi != mapBlockIndex.end())
1493 CBlockIndex* pindex = (*mi).second;
1494 if (pindex->IsInMainChain())
1504 CBlockIndex* GetBlockIndex()
1506 // Find the first block the caller has in the main chain
1507 BOOST_FOREACH(const uint256& hash, vHave)
1509 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1510 if (mi != mapBlockIndex.end())
1512 CBlockIndex* pindex = (*mi).second;
1513 if (pindex->IsInMainChain())
1517 return pindexGenesisBlock;
1520 uint256 GetBlockHash()
1522 // Find the first block the caller has in the main chain
1523 BOOST_FOREACH(const uint256& hash, vHave)
1525 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1526 if (mi != mapBlockIndex.end())
1528 CBlockIndex* pindex = (*mi).second;
1529 if (pindex->IsInMainChain())
1533 return hashGenesisBlock;
1538 CBlockIndex* pindex = GetBlockIndex();
1541 return pindex->nHeight;
1553 /** Alerts are for notifying old versions if they become too obsolete and
1554 * need to upgrade. The message is displayed in the status bar.
1555 * Alert messages are broadcast as a vector of signed data. Unserializing may
1556 * not read the entire buffer if the alert is for a newer version, but older
1557 * versions can still relay the original data.
1559 class CUnsignedAlert
1563 int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
1567 std::set<int> setCancel;
1568 int nMinVer; // lowest version inclusive
1569 int nMaxVer; // highest version inclusive
1570 std::set<std::string> setSubVer; // empty matches all
1574 std::string strComment;
1575 std::string strStatusBar;
1576 std::string strReserved;
1580 READWRITE(this->nVersion);
1581 nVersion = this->nVersion;
1582 READWRITE(nRelayUntil);
1583 READWRITE(nExpiration);
1586 READWRITE(setCancel);
1589 READWRITE(setSubVer);
1590 READWRITE(nPriority);
1592 READWRITE(strComment);
1593 READWRITE(strStatusBar);
1594 READWRITE(strReserved);
1611 strStatusBar.clear();
1612 strReserved.clear();
1615 std::string ToString() const
1617 std::string strSetCancel;
1618 BOOST_FOREACH(int n, setCancel)
1619 strSetCancel += strprintf("%d ", n);
1620 std::string strSetSubVer;
1621 BOOST_FOREACH(std::string str, setSubVer)
1622 strSetSubVer += "\"" + str + "\" ";
1626 " nRelayUntil = %"PRI64d"\n"
1627 " nExpiration = %"PRI64d"\n"
1635 " strComment = \"%s\"\n"
1636 " strStatusBar = \"%s\"\n"
1643 strSetCancel.c_str(),
1646 strSetSubVer.c_str(),
1649 strStatusBar.c_str());
1654 printf("%s", ToString().c_str());
1658 /** An alert is a combination of a serialized CUnsignedAlert and a signature. */
1659 class CAlert : public CUnsignedAlert
1662 std::vector<unsigned char> vchMsg;
1663 std::vector<unsigned char> vchSig;
1678 CUnsignedAlert::SetNull();
1685 return (nExpiration == 0);
1688 uint256 GetHash() const
1690 return SerializeHash(*this);
1693 bool IsInEffect() const
1695 return (GetAdjustedTime() < nExpiration);
1698 bool Cancels(const CAlert& alert) const
1701 return false; // this was a no-op before 31403
1702 return (alert.nID <= nCancel || setCancel.count(alert.nID));
1705 bool AppliesTo(int nVersion, std::string strSubVerIn) const
1707 // TODO: rework for client-version-embedded-in-strSubVer ?
1708 return (IsInEffect() &&
1709 nMinVer <= nVersion && nVersion <= nMaxVer &&
1710 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1713 bool AppliesToMe() const
1715 return AppliesTo(PROTOCOL_VERSION, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<std::string>()));
1718 bool RelayTo(CNode* pnode) const
1722 // returns true if wasn't already contained in the set
1723 if (pnode->setKnown.insert(GetHash()).second)
1725 if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
1727 GetAdjustedTime() < nRelayUntil)
1729 pnode->PushMessage("alert", *this);
1736 bool CheckSignature()
1739 if (!key.SetPubKey(ParseHex("04a0a849dd49b113d3179a332dd77715c43be4d0076e2f19e66de23dd707e56630f792f298dfd209bf042bb3561f4af6983f3d81e439737ab0bf7f898fecd21aab")))
1740 return error("CAlert::CheckSignature() : SetPubKey failed");
1741 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
1742 return error("CAlert::CheckSignature() : verify signature failed");
1744 // Now unserialize the data
1745 CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION);
1746 sMsg >> *(CUnsignedAlert*)this;
1750 bool ProcessAlert();
1756 mutable CCriticalSection cs;
1757 std::map<uint256, CTransaction> mapTx;
1758 std::map<COutPoint, CInPoint> mapNextTx;
1760 bool accept(CTxDB& txdb, CTransaction &tx,
1761 bool fCheckInputs, bool* pfMissingInputs);
1762 bool addUnchecked(CTransaction &tx);
1763 bool remove(CTransaction &tx);
1765 unsigned long size()
1768 return mapTx.size();
1771 bool exists(uint256 hash)
1773 return (mapTx.count(hash) != 0);
1776 CTransaction& lookup(uint256 hash)
1782 extern CTxMemPool mempool;