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 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 %s %s", FormatMoney(nValue).c_str(), scriptPubKey.ToString(true).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().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 char pchMessageStart[4];
1041 GetMessageStart(pchMessageStart, true);
1042 unsigned int nSize = fileout.GetSerializeSize(*this);
1043 fileout << FLATDATA(pchMessageStart) << nSize;
1046 long fileOutPos = ftell(fileout);
1048 return error("CBlock::WriteToDisk() : ftell failed");
1049 nBlockPosRet = fileOutPos;
1052 // Flush stdio buffers and commit to disk before returning
1054 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
1057 _commit(_fileno(fileout));
1059 fsync(fileno(fileout));
1066 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
1070 // Open history file to read
1071 CAutoFile filein = CAutoFile(OpenBlockFile(nFile, nBlockPos, "rb"), SER_DISK, CLIENT_VERSION);
1073 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1074 if (!fReadTransactions)
1075 filein.nType |= SER_BLOCKHEADERONLY;
1081 catch (std::exception &e) {
1082 return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
1086 if (fReadTransactions && IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
1087 return error("CBlock::ReadFromDisk() : errors in block header");
1096 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d, vchBlockSig=%s)\n",
1097 GetHash().ToString().substr(0,20).c_str(),
1099 hashPrevBlock.ToString().substr(0,20).c_str(),
1100 hashMerkleRoot.ToString().substr(0,10).c_str(),
1101 nTime, nBits, nNonce,
1103 HexStr(vchBlockSig.begin(), vchBlockSig.end()).c_str());
1104 for (unsigned int i = 0; i < vtx.size(); i++)
1109 printf(" vMerkleTree: ");
1110 for (unsigned int i = 0; i < vMerkleTree.size(); i++)
1111 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1116 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1117 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1118 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1119 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1120 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1121 bool CheckBlock() const;
1123 bool GetCoinAge(uint64& nCoinAge) const; // ppcoin: calculate total coin age spent in block
1124 bool SignBlock(const CKeyStore& keystore);
1125 bool CheckBlockSignature() const;
1128 bool SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew);
1136 /** The block chain is a tree shaped structure starting with the
1137 * genesis block at the root, with each block potentially having multiple
1138 * candidates to be the next block. pprev and pnext link a path through the
1139 * main/longest chain. A blockindex may have multiple pprev pointing back
1140 * to it, but pnext will only point forward to the longest branch, or will
1141 * be null if the block is not part of the longest chain.
1146 const uint256* phashBlock;
1150 unsigned int nBlockPos;
1151 CBigNum bnChainTrust; // ppcoin: trust score of block chain
1155 bool fProofOfStake; // ppcoin: is the block of proof-of-stake type
1156 COutPoint prevoutStake;
1157 unsigned int nStakeTime;
1161 uint256 hashMerkleRoot;
1164 unsigned int nNonce;
1178 fProofOfStake = true;
1179 prevoutStake.SetNull();
1189 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1195 nBlockPos = nBlockPosIn;
1200 fProofOfStake = block.IsProofOfStake();
1203 prevoutStake = block.vtx[1].vin[0].prevout;
1204 nStakeTime = block.vtx[1].nTime;
1208 prevoutStake.SetNull();
1212 nVersion = block.nVersion;
1213 hashMerkleRoot = block.hashMerkleRoot;
1214 nTime = block.nTime;
1215 nBits = block.nBits;
1216 nNonce = block.nNonce;
1219 CBlock GetBlockHeader() const
1222 block.nVersion = nVersion;
1224 block.hashPrevBlock = pprev->GetBlockHash();
1225 block.hashMerkleRoot = hashMerkleRoot;
1226 block.nTime = nTime;
1227 block.nBits = nBits;
1228 block.nNonce = nNonce;
1232 uint256 GetBlockHash() const
1237 int64 GetBlockTime() const
1239 return (int64)nTime;
1242 CBigNum GetBlockTrust() const
1245 bnTarget.SetCompact(nBits);
1248 return (fProofOfStake? (CBigNum(1)<<256) / (bnTarget+1) : 1);
1251 bool IsInMainChain() const
1253 return (pnext || this == pindexBest);
1256 bool CheckIndex() const
1258 return IsProofOfWork() ? CheckProofOfWork(GetBlockHash(), nBits) : true;
1261 bool EraseBlockFromDisk()
1263 // Open history file
1264 CAutoFile fileout = CAutoFile(OpenBlockFile(nFile, nBlockPos, "rb+"), SER_DISK, CLIENT_VERSION);
1268 // Overwrite with empty null block
1276 enum { nMedianTimeSpan=11 };
1278 int64 GetMedianTimePast() const
1280 int64 pmedian[nMedianTimeSpan];
1281 int64* pbegin = &pmedian[nMedianTimeSpan];
1282 int64* pend = &pmedian[nMedianTimeSpan];
1284 const CBlockIndex* pindex = this;
1285 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1286 *(--pbegin) = pindex->GetBlockTime();
1288 std::sort(pbegin, pend);
1289 return pbegin[(pend - pbegin)/2];
1292 int64 GetMedianTime() const
1294 const CBlockIndex* pindex = this;
1295 for (int i = 0; i < nMedianTimeSpan/2; i++)
1298 return GetBlockTime();
1299 pindex = pindex->pnext;
1301 return pindex->GetMedianTimePast();
1304 bool IsProofOfWork() const
1306 return !fProofOfStake;
1309 bool IsProofOfStake() const
1311 return fProofOfStake;
1314 std::string ToString() const
1316 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)",
1317 pprev, pnext, nFile, nBlockPos, nHeight,
1318 FormatMoney(nMint).c_str(), FormatMoney(nMoneySupply).c_str(),
1319 fProofOfStake, prevoutStake.ToString().c_str(), nStakeTime,
1320 hashMerkleRoot.ToString().substr(0,10).c_str(),
1321 GetBlockHash().ToString().substr(0,20).c_str());
1326 printf("%s\n", ToString().c_str());
1332 /** Used to marshal pointers into hashes for db storage. */
1333 class CDiskBlockIndex : public CBlockIndex
1345 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1347 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1348 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1353 if (!(nType & SER_GETHASH))
1354 READWRITE(nVersion);
1356 READWRITE(hashNext);
1358 READWRITE(nBlockPos);
1361 READWRITE(nMoneySupply);
1362 READWRITE(fProofOfStake);
1365 READWRITE(prevoutStake);
1366 READWRITE(nStakeTime);
1370 const_cast<CDiskBlockIndex*>(this)->prevoutStake.SetNull();
1371 const_cast<CDiskBlockIndex*>(this)->nStakeTime = 0;
1375 READWRITE(this->nVersion);
1376 READWRITE(hashPrev);
1377 READWRITE(hashMerkleRoot);
1383 uint256 GetBlockHash() const
1386 block.nVersion = nVersion;
1387 block.hashPrevBlock = hashPrev;
1388 block.hashMerkleRoot = hashMerkleRoot;
1389 block.nTime = nTime;
1390 block.nBits = nBits;
1391 block.nNonce = nNonce;
1392 return block.GetHash();
1396 std::string ToString() const
1398 std::string str = "CDiskBlockIndex(";
1399 str += CBlockIndex::ToString();
1400 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1401 GetBlockHash().ToString().c_str(),
1402 hashPrev.ToString().substr(0,20).c_str(),
1403 hashNext.ToString().substr(0,20).c_str());
1409 printf("%s\n", ToString().c_str());
1420 /** Describes a place in the block chain to another node such that if the
1421 * other node doesn't have the same branch, it can find a recent common trunk.
1422 * The further back it is, the further before the fork it may be.
1427 std::vector<uint256> vHave;
1434 explicit CBlockLocator(const CBlockIndex* pindex)
1439 explicit CBlockLocator(uint256 hashBlock)
1441 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1442 if (mi != mapBlockIndex.end())
1446 CBlockLocator(const std::vector<uint256>& vHaveIn)
1453 if (!(nType & SER_GETHASH))
1454 READWRITE(nVersion);
1465 return vHave.empty();
1468 void Set(const CBlockIndex* pindex)
1474 vHave.push_back(pindex->GetBlockHash());
1476 // Exponentially larger steps back
1477 for (int i = 0; pindex && i < nStep; i++)
1478 pindex = pindex->pprev;
1479 if (vHave.size() > 10)
1482 vHave.push_back(hashGenesisBlock);
1485 int GetDistanceBack()
1487 // Retrace how far back it was in the sender's branch
1490 BOOST_FOREACH(const uint256& hash, vHave)
1492 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1493 if (mi != mapBlockIndex.end())
1495 CBlockIndex* pindex = (*mi).second;
1496 if (pindex->IsInMainChain())
1506 CBlockIndex* GetBlockIndex()
1508 // Find the first block the caller has in the main chain
1509 BOOST_FOREACH(const uint256& hash, vHave)
1511 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1512 if (mi != mapBlockIndex.end())
1514 CBlockIndex* pindex = (*mi).second;
1515 if (pindex->IsInMainChain())
1519 return pindexGenesisBlock;
1522 uint256 GetBlockHash()
1524 // Find the first block the caller has in the main chain
1525 BOOST_FOREACH(const uint256& hash, vHave)
1527 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1528 if (mi != mapBlockIndex.end())
1530 CBlockIndex* pindex = (*mi).second;
1531 if (pindex->IsInMainChain())
1535 return hashGenesisBlock;
1540 CBlockIndex* pindex = GetBlockIndex();
1543 return pindex->nHeight;
1555 /** Alerts are for notifying old versions if they become too obsolete and
1556 * need to upgrade. The message is displayed in the status bar.
1557 * Alert messages are broadcast as a vector of signed data. Unserializing may
1558 * not read the entire buffer if the alert is for a newer version, but older
1559 * versions can still relay the original data.
1561 class CUnsignedAlert
1565 int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
1569 std::set<int> setCancel;
1570 int nMinVer; // lowest version inclusive
1571 int nMaxVer; // highest version inclusive
1572 std::set<std::string> setSubVer; // empty matches all
1576 std::string strComment;
1577 std::string strStatusBar;
1578 std::string strReserved;
1582 READWRITE(this->nVersion);
1583 nVersion = this->nVersion;
1584 READWRITE(nRelayUntil);
1585 READWRITE(nExpiration);
1588 READWRITE(setCancel);
1591 READWRITE(setSubVer);
1592 READWRITE(nPriority);
1594 READWRITE(strComment);
1595 READWRITE(strStatusBar);
1596 READWRITE(strReserved);
1613 strStatusBar.clear();
1614 strReserved.clear();
1617 std::string ToString() const
1619 std::string strSetCancel;
1620 BOOST_FOREACH(int n, setCancel)
1621 strSetCancel += strprintf("%d ", n);
1622 std::string strSetSubVer;
1623 BOOST_FOREACH(std::string str, setSubVer)
1624 strSetSubVer += "\"" + str + "\" ";
1628 " nRelayUntil = %"PRI64d"\n"
1629 " nExpiration = %"PRI64d"\n"
1637 " strComment = \"%s\"\n"
1638 " strStatusBar = \"%s\"\n"
1645 strSetCancel.c_str(),
1648 strSetSubVer.c_str(),
1651 strStatusBar.c_str());
1656 printf("%s", ToString().c_str());
1660 /** An alert is a combination of a serialized CUnsignedAlert and a signature. */
1661 class CAlert : public CUnsignedAlert
1664 std::vector<unsigned char> vchMsg;
1665 std::vector<unsigned char> vchSig;
1680 CUnsignedAlert::SetNull();
1687 return (nExpiration == 0);
1690 uint256 GetHash() const
1692 return SerializeHash(*this);
1695 bool IsInEffect() const
1697 return (GetAdjustedTime() < nExpiration);
1700 bool Cancels(const CAlert& alert) const
1703 return false; // this was a no-op before 31403
1704 return (alert.nID <= nCancel || setCancel.count(alert.nID));
1707 bool AppliesTo(int nVersion, std::string strSubVerIn) const
1709 // TODO: rework for client-version-embedded-in-strSubVer ?
1710 return (IsInEffect() &&
1711 nMinVer <= nVersion && nVersion <= nMaxVer &&
1712 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1715 bool AppliesToMe() const
1717 return AppliesTo(PROTOCOL_VERSION, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<std::string>()));
1720 bool RelayTo(CNode* pnode) const
1724 // returns true if wasn't already contained in the set
1725 if (pnode->setKnown.insert(GetHash()).second)
1727 if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
1729 GetAdjustedTime() < nRelayUntil)
1731 pnode->PushMessage("alert", *this);
1738 bool CheckSignature()
1741 if (!key.SetPubKey(ParseHex("04a0a849dd49b113d3179a332dd77715c43be4d0076e2f19e66de23dd707e56630f792f298dfd209bf042bb3561f4af6983f3d81e439737ab0bf7f898fecd21aab")))
1742 return error("CAlert::CheckSignature() : SetPubKey failed");
1743 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
1744 return error("CAlert::CheckSignature() : verify signature failed");
1746 // Now unserialize the data
1747 CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION);
1748 sMsg >> *(CUnsignedAlert*)this;
1752 bool ProcessAlert();
1758 mutable CCriticalSection cs;
1759 std::map<uint256, CTransaction> mapTx;
1760 std::map<COutPoint, CInPoint> mapNextTx;
1762 bool accept(CTxDB& txdb, CTransaction &tx,
1763 bool fCheckInputs, bool* pfMissingInputs);
1764 bool addUnchecked(CTransaction &tx);
1765 bool remove(CTransaction &tx);
1767 unsigned long size()
1770 return mapTx.size();
1773 bool exists(uint256 hash)
1775 return (mapTx.count(hash) != 0);
1778 CTransaction& lookup(uint256 hash)
1784 extern CTxMemPool mempool;