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 = 10000;
36 static const int64 MIN_RELAY_TX_FEE = 10000;
37 static const int64 MAX_MONEY = 2000000000 * COIN;
38 inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
39 static const int COINBASE_MATURITY = 100;
40 // Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp.
41 static const int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC
43 static const int fHaveUPnP = true;
45 static const int fHaveUPnP = false;
48 static const uint256 hashGenesisBlockOfficial("0x000000007c82d1f0aa2896b01bf533a8cc26a1f44790be4ceb4ecde7bee24add");
49 static const uint256 hashGenesisBlockTestNet("0x00000007199508e34a9ff81e6ec0c477a4cccff2a4767a8eee39c11db367b008");
51 extern CScript COINBASE_FLAGS;
58 extern CCriticalSection cs_main;
59 extern std::map<uint256, CBlockIndex*> mapBlockIndex;
60 extern std::set<std::pair<COutPoint, unsigned int> > setStakeSeen;
61 extern uint256 hashGenesisBlock;
62 extern CBlockIndex* pindexGenesisBlock;
63 extern int nBestHeight;
64 extern uint64 nBestChainTrust;
65 extern uint64 nBestInvalidTrust;
66 extern uint256 hashBestChain;
67 extern CBlockIndex* pindexBest;
68 extern unsigned int nTransactionsUpdated;
69 extern uint64 nLastBlockTx;
70 extern uint64 nLastBlockSize;
71 extern const std::string strMessageMagic;
72 extern double dHashesPerSec;
73 extern int64 nHPSTimerStart;
74 extern int64 nTimeBestReceived;
75 extern CCriticalSection cs_setpwalletRegistered;
76 extern std::set<CWallet*> setpwalletRegistered;
77 extern std::map<uint256, CBlock*> mapOrphanBlocks;
80 extern int64 nTransactionFee;
90 void RegisterWallet(CWallet* pwalletIn);
91 void UnregisterWallet(CWallet* pwalletIn);
92 bool ProcessBlock(CNode* pfrom, CBlock* pblock);
93 bool CheckDiskSpace(uint64 nAdditionalBytes=0);
94 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
95 FILE* AppendBlockFile(unsigned int& nFileRet);
96 bool LoadBlockIndex(bool fAllowNew=true);
97 void PrintBlockTree();
98 bool ProcessMessages(CNode* pfrom);
99 bool SendMessages(CNode* pto, bool fSendTrickle);
100 void GenerateBitcoins(bool fGenerate, CWallet* pwallet);
101 CBlock* CreateNewBlock(CWallet* pwallet, bool fProofOfWorkOnly=false);
102 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce);
103 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
104 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey);
105 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
106 int64 GetProofOfStakeReward(int64 nCoinAge);
107 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime);
108 int GetNumBlocksOfPeers();
109 bool IsInitialBlockDownload();
110 std::string GetWarnings(std::string strFor);
111 bool Reorganize(CTxDB& txdb, CBlockIndex* pindexNew);
112 uint256 WantedByOrphan(const CBlock* pblockOrphan);
113 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake);
125 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
127 /** Position on disk for a particular transaction. */
132 unsigned int nBlockPos;
140 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
143 nBlockPos = nBlockPosIn;
147 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
148 void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
149 bool IsNull() const { return (nFile == -1); }
151 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
153 return (a.nFile == b.nFile &&
154 a.nBlockPos == b.nBlockPos &&
155 a.nTxPos == b.nTxPos);
158 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
163 std::string ToString() const
168 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
173 printf("%s", ToString().c_str());
179 /** An inpoint - a combination of a transaction and an index n into its vin */
186 CInPoint() { SetNull(); }
187 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
188 void SetNull() { ptx = NULL; n = -1; }
189 bool IsNull() const { return (ptx == NULL && n == -1); }
194 /** An outpoint - a combination of a transaction hash and an index n into its vout */
201 COutPoint() { SetNull(); }
202 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
203 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
204 void SetNull() { hash = 0; n = -1; }
205 bool IsNull() const { return (hash == 0 && n == -1); }
207 friend bool operator<(const COutPoint& a, const COutPoint& b)
209 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
212 friend bool operator==(const COutPoint& a, const COutPoint& b)
214 return (a.hash == b.hash && a.n == b.n);
217 friend bool operator!=(const COutPoint& a, const COutPoint& b)
222 std::string ToString() const
224 return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,10).c_str(), n);
229 printf("%s\n", ToString().c_str());
236 /** An input of a transaction. It contains the location of the previous
237 * transaction's output that it claims and a signature that matches the
238 * output's public key.
245 unsigned int nSequence;
249 nSequence = std::numeric_limits<unsigned int>::max();
252 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
255 scriptSig = scriptSigIn;
256 nSequence = nSequenceIn;
259 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
261 prevout = COutPoint(hashPrevTx, nOut);
262 scriptSig = scriptSigIn;
263 nSequence = nSequenceIn;
269 READWRITE(scriptSig);
270 READWRITE(nSequence);
275 return (nSequence == std::numeric_limits<unsigned int>::max());
278 friend bool operator==(const CTxIn& a, const CTxIn& b)
280 return (a.prevout == b.prevout &&
281 a.scriptSig == b.scriptSig &&
282 a.nSequence == b.nSequence);
285 friend bool operator!=(const CTxIn& a, const CTxIn& b)
290 std::string ToString() const
294 str += prevout.ToString();
295 if (prevout.IsNull())
296 str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
298 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
299 if (nSequence != std::numeric_limits<unsigned int>::max())
300 str += strprintf(", nSequence=%u", nSequence);
307 printf("%s\n", ToString().c_str());
314 /** An output of a transaction. It contains the public key that the next input
315 * must be able to sign with to claim it.
321 CScript scriptPubKey;
328 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
331 scriptPubKey = scriptPubKeyIn;
337 READWRITE(scriptPubKey);
343 scriptPubKey.clear();
348 return (nValue == -1);
354 scriptPubKey.clear();
359 return (nValue == 0 && scriptPubKey.empty());
362 uint256 GetHash() const
364 return SerializeHash(*this);
367 friend bool operator==(const CTxOut& a, const CTxOut& b)
369 return (a.nValue == b.nValue &&
370 a.scriptPubKey == b.scriptPubKey);
373 friend bool operator!=(const CTxOut& a, const CTxOut& b)
378 std::string ToString() const
380 if (IsEmpty()) return "CTxOut(empty)";
381 if (scriptPubKey.size() < 6)
382 return "CTxOut(error)";
383 return strprintf("CTxOut(nValue=%s, scriptPubKey=%s)", FormatMoney(nValue).c_str(), scriptPubKey.ToString().substr(0,30).c_str());
388 printf("%s\n", ToString().c_str());
402 typedef std::map<uint256, std::pair<CTxIndex, CTransaction> > MapPrevTx;
404 /** The basic transaction that is broadcasted on the network and contained in
405 * blocks. A transaction can contain multiple inputs and outputs.
412 std::vector<CTxIn> vin;
413 std::vector<CTxOut> vout;
414 unsigned int nLockTime;
416 // Denial-of-service detection:
418 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
427 READWRITE(this->nVersion);
428 nVersion = this->nVersion;
432 READWRITE(nLockTime);
438 nTime = GetAdjustedTime();
442 nDoS = 0; // Denial-of-service prevention
447 return (vin.empty() && vout.empty());
450 uint256 GetHash() const
452 return SerializeHash(*this);
455 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
457 // Time based nLockTime implemented in 0.1.6
460 if (nBlockHeight == 0)
461 nBlockHeight = nBestHeight;
463 nBlockTime = GetAdjustedTime();
464 if ((int64)nLockTime < ((int64)nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
466 BOOST_FOREACH(const CTxIn& txin, vin)
472 bool IsNewerThan(const CTransaction& old) const
474 if (vin.size() != old.vin.size())
476 for (unsigned int i = 0; i < vin.size(); i++)
477 if (vin[i].prevout != old.vin[i].prevout)
481 unsigned int nLowest = std::numeric_limits<unsigned int>::max();
482 for (unsigned int i = 0; i < vin.size(); i++)
484 if (vin[i].nSequence != old.vin[i].nSequence)
486 if (vin[i].nSequence <= nLowest)
489 nLowest = vin[i].nSequence;
491 if (old.vin[i].nSequence < nLowest)
494 nLowest = old.vin[i].nSequence;
501 bool IsCoinBase() const
503 return (vin.size() == 1 && vin[0].prevout.IsNull() && vout.size() == 1);
506 bool IsCoinStake() const
508 // ppcoin: the coin stake transaction is marked with the first output empty
509 return (vin.size() > 0 && vout.size() == 2 && vout[0].IsEmpty());
512 /** Check for standard transaction types
513 @return True if all outputs (scriptPubKeys) use only standard transaction forms
515 bool IsStandard() const;
517 /** Check for standard transaction types
518 @param[in] mapInputs Map of previous transactions that have outputs we're spending
519 @return True if all inputs (scriptSigs) use only standard transaction forms
520 @see CTransaction::FetchInputs
522 bool AreInputsStandard(const MapPrevTx& mapInputs) const;
524 /** Count ECDSA signature operations the old-fashioned (pre-0.6) way
525 @return number of sigops this transaction's outputs will produce when spent
526 @see CTransaction::FetchInputs
528 unsigned int GetLegacySigOpCount() const;
530 /** Count ECDSA signature operations in pay-to-script-hash inputs.
532 @param[in] mapInputs Map of previous transactions that have outputs we're spending
533 @return maximum number of sigops required to validate this transaction's inputs
534 @see CTransaction::FetchInputs
536 unsigned int GetP2SHSigOpCount(const MapPrevTx& mapInputs) const;
538 /** Amount of bitcoins spent by this transaction.
539 @return sum of all outputs (note: does not include fees)
541 int64 GetValueOut() const
544 BOOST_FOREACH(const CTxOut& txout, vout)
546 nValueOut += txout.nValue;
547 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
548 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
553 /** Amount of bitcoins coming in to this transaction
554 Note that lightweight clients may not know anything besides the hash of previous transactions,
555 so may not be able to calculate this.
557 @param[in] mapInputs Map of previous transactions that have outputs we're spending
558 @return Sum of value of all inputs (scriptSigs)
559 @see CTransaction::FetchInputs
561 int64 GetValueIn(const MapPrevTx& mapInputs) const;
563 static bool AllowFree(double dPriority)
565 // Large (in bytes) low-priority (new, small-coin) transactions
567 return dPriority > COIN * 144 / 250;
570 int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=false, enum GetMinFee_mode mode=GMF_BLOCK) const
572 // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
573 int64 nBaseFee = (mode == GMF_RELAY) ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
575 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION);
576 unsigned int nNewBlockSize = nBlockSize + nBytes;
577 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
583 // Transactions under 10K are free
584 // (about 4500bc if made of 50bc inputs)
590 // Free transaction area
591 if (nNewBlockSize < 27000)
596 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
597 if (nMinFee < nBaseFee)
599 BOOST_FOREACH(const CTxOut& txout, vout)
600 if (txout.nValue < CENT)
604 // Raise the price as the block approaches full
605 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
607 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
609 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
612 if (!MoneyRange(nMinFee))
618 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
620 CAutoFile filein = CAutoFile(OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb"), SER_DISK, CLIENT_VERSION);
622 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
625 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
626 return error("CTransaction::ReadFromDisk() : fseek failed");
631 catch (std::exception &e) {
632 return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
635 // Return file pointer
638 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
639 return error("CTransaction::ReadFromDisk() : second fseek failed");
640 *pfileRet = filein.release();
645 friend bool operator==(const CTransaction& a, const CTransaction& b)
647 return (a.nVersion == b.nVersion &&
648 a.nTime == b.nTime &&
651 a.nLockTime == b.nLockTime);
654 friend bool operator!=(const CTransaction& a, const CTransaction& b)
660 std::string ToString() const
663 str += IsCoinBase()? "Coinbase" : (IsCoinStake()? "Coinstake" : "CTransaction");
664 str += strprintf("(hash=%s, nTime=%d, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
665 GetHash().ToString().substr(0,10).c_str(),
671 for (unsigned int i = 0; i < vin.size(); i++)
672 str += " " + vin[i].ToString() + "\n";
673 for (unsigned int i = 0; i < vout.size(); i++)
674 str += " " + vout[i].ToString() + "\n";
680 printf("%s", ToString().c_str());
684 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
685 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
686 bool ReadFromDisk(COutPoint prevout);
687 bool DisconnectInputs(CTxDB& txdb);
689 /** Fetch from memory and/or disk. inputsRet keys are transaction hashes.
691 @param[in] txdb Transaction database
692 @param[in] mapTestPool List of pending changes to the transaction index database
693 @param[in] fBlock True if being called to add a new best-block to the chain
694 @param[in] fMiner True if being called by CreateNewBlock
695 @param[out] inputsRet Pointers to this transaction's inputs
696 @param[out] fInvalid returns true if transaction is invalid
697 @return Returns true if all inputs are in txdb or mapTestPool
699 bool FetchInputs(CTxDB& txdb, const std::map<uint256, CTxIndex>& mapTestPool,
700 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid);
702 /** Sanity check previous transactions, then, if all checks succeed,
703 mark them as spent by this transaction.
705 @param[in] inputs Previous transactions (from FetchInputs)
706 @param[out] mapTestPool Keeps track of inputs that need to be updated on disk
707 @param[in] posThisTx Position of this transaction on disk
708 @param[in] pindexBlock
709 @param[in] fBlock true if called from ConnectBlock
710 @param[in] fMiner true if called from CreateNewBlock
711 @param[in] fStrictPayToScriptHash true if fully validating p2sh transactions
712 @return Returns true if all checks succeed
714 bool ConnectInputs(CTxDB& txdb, MapPrevTx inputs,
715 std::map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
716 const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash=true);
717 bool ClientConnectInputs();
718 bool CheckTransaction() const;
719 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
720 bool GetCoinAge(CTxDB& txdb, uint64& nCoinAge) const; // ppcoin: get transaction coin age
721 bool CheckProofOfStake(unsigned int nBits) const;
724 const CTxOut& GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const;
731 /** A transaction with a merkle branch linking it to the block chain. */
732 class CMerkleTx : public CTransaction
736 std::vector<uint256> vMerkleBranch;
740 mutable bool fMerkleVerified;
748 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
757 fMerkleVerified = false;
763 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
764 nVersion = this->nVersion;
765 READWRITE(hashBlock);
766 READWRITE(vMerkleBranch);
771 int SetMerkleBranch(const CBlock* pblock=NULL);
772 int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
773 int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
774 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
775 int GetBlocksToMaturity() const;
776 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
777 bool AcceptToMemoryPool();
783 /** A txdb record that contains the disk location of a transaction and the
784 * locations of transactions that spend its outputs. vSpent is really only
785 * used as a flag, but having the location is very helpful for debugging.
791 std::vector<CDiskTxPos> vSpent;
798 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
801 vSpent.resize(nOutputs);
806 if (!(nType & SER_GETHASH))
823 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
825 return (a.pos == b.pos &&
826 a.vSpent == b.vSpent);
829 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
833 int GetDepthInMainChain() const;
841 /** Nodes collect new transactions into a block, hash them into a hash tree,
842 * and scan through nonce values to make the block's hash satisfy proof-of-work
843 * requirements. When they solve the proof-of-work, they broadcast the block
844 * to everyone and the block is added to the block chain. The first transaction
845 * in the block is a special one that creates a new coin owned by the creator
848 * Blocks are appended to blk0001.dat files on disk. Their location on disk
849 * is indexed by CBlockIndex objects in memory.
856 uint256 hashPrevBlock;
857 uint256 hashMerkleRoot;
863 std::vector<CTransaction> vtx;
865 // ppcoin: block signature - signed by coin base txout[0]'s owner
866 std::vector<unsigned char> vchBlockSig;
869 mutable std::vector<uint256> vMerkleTree;
871 // Denial-of-service detection:
873 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
882 READWRITE(this->nVersion);
883 nVersion = this->nVersion;
884 READWRITE(hashPrevBlock);
885 READWRITE(hashMerkleRoot);
890 // ConnectBlock depends on vtx following header to generate CDiskTxPos
891 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
894 READWRITE(vchBlockSig);
898 const_cast<CBlock*>(this)->vtx.clear();
899 const_cast<CBlock*>(this)->vchBlockSig.clear();
922 uint256 GetHash() const
924 return Hash(BEGIN(nVersion), END(nNonce));
927 int64 GetBlockTime() const
932 void UpdateTime(const CBlockIndex* pindexPrev);
934 // ppcoin: two types of block: proof-of-work or proof-of-stake
935 bool IsProofOfStake() const
937 return (vtx.size() > 1 && vtx[1].IsCoinStake());
940 bool IsProofOfWork() const
942 return !IsProofOfStake();
945 std::pair<COutPoint, unsigned int> GetProofOfStake() const
947 return IsProofOfStake()? std::make_pair(vtx[1].vin[0].prevout, vtx[1].nTime) : std::make_pair(COutPoint(), (unsigned int)0);
950 // ppcoin: get max transaction timestamp
951 int64 GetMaxTransactionTime() const
953 int64 maxTransactionTime = 0;
954 BOOST_FOREACH(const CTransaction& tx, vtx)
955 maxTransactionTime = std::max(maxTransactionTime, (int64)tx.nTime);
956 return maxTransactionTime;
959 uint256 BuildMerkleTree() const
962 BOOST_FOREACH(const CTransaction& tx, vtx)
963 vMerkleTree.push_back(tx.GetHash());
965 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
967 for (int i = 0; i < nSize; i += 2)
969 int i2 = std::min(i+1, nSize-1);
970 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
971 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
975 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
978 std::vector<uint256> GetMerkleBranch(int nIndex) const
980 if (vMerkleTree.empty())
982 std::vector<uint256> vMerkleBranch;
984 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
986 int i = std::min(nIndex^1, nSize-1);
987 vMerkleBranch.push_back(vMerkleTree[j+i]);
991 return vMerkleBranch;
994 static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
998 BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
1001 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
1003 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
1010 bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
1012 // Open history file to append
1013 CAutoFile fileout = CAutoFile(AppendBlockFile(nFileRet), SER_DISK, CLIENT_VERSION);
1015 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
1017 // Write index header
1018 unsigned int nSize = fileout.GetSerializeSize(*this);
1019 fileout << FLATDATA(pchMessageStart) << nSize;
1022 long fileOutPos = ftell(fileout);
1024 return error("CBlock::WriteToDisk() : ftell failed");
1025 nBlockPosRet = fileOutPos;
1028 // Flush stdio buffers and commit to disk before returning
1030 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
1033 _commit(_fileno(fileout));
1035 fsync(fileno(fileout));
1042 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
1046 // Open history file to read
1047 CAutoFile filein = CAutoFile(OpenBlockFile(nFile, nBlockPos, "rb"), SER_DISK, CLIENT_VERSION);
1049 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1050 if (!fReadTransactions)
1051 filein.nType |= SER_BLOCKHEADERONLY;
1057 catch (std::exception &e) {
1058 return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
1062 if (fReadTransactions && IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
1063 return error("CBlock::ReadFromDisk() : errors in block header");
1072 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d, vchBlockSig=%s)\n",
1073 GetHash().ToString().substr(0,20).c_str(),
1075 hashPrevBlock.ToString().substr(0,20).c_str(),
1076 hashMerkleRoot.ToString().substr(0,10).c_str(),
1077 nTime, nBits, nNonce,
1079 HexStr(vchBlockSig.begin(), vchBlockSig.end()).c_str());
1080 for (unsigned int i = 0; i < vtx.size(); i++)
1085 printf(" vMerkleTree: ");
1086 for (unsigned int i = 0; i < vMerkleTree.size(); i++)
1087 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1092 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1093 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1094 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1095 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1096 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1097 bool CheckBlock() const;
1099 bool GetCoinAge(uint64& nCoinAge) const; // ppcoin: calculate total coin age spent in block
1100 bool SignBlock(const CKeyStore& keystore);
1101 bool CheckBlockSignature() const;
1104 bool SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew);
1112 /** The block chain is a tree shaped structure starting with the
1113 * genesis block at the root, with each block potentially having multiple
1114 * candidates to be the next block. pprev and pnext link a path through the
1115 * main/longest chain. A blockindex may have multiple pprev pointing back
1116 * to it, but pnext will only point forward to the longest branch, or will
1117 * be null if the block is not part of the longest chain.
1122 const uint256* phashBlock;
1126 unsigned int nBlockPos;
1127 uint64 nChainTrust;// ppcoin: trust score of chain, in the unit of coin-days
1129 bool fProofOfStake; // ppcoin: is the block of proof-of-stake type
1130 COutPoint prevoutStake;
1131 unsigned int nStakeTime;
1135 uint256 hashMerkleRoot;
1138 unsigned int nNonce;
1150 fProofOfStake = true;
1151 prevoutStake.SetNull();
1161 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1167 nBlockPos = nBlockPosIn;
1170 fProofOfStake = block.IsProofOfStake();
1173 prevoutStake = block.vtx[1].vin[0].prevout;
1174 nStakeTime = block.vtx[1].nTime;
1178 prevoutStake.SetNull();
1182 nVersion = block.nVersion;
1183 hashMerkleRoot = block.hashMerkleRoot;
1184 nTime = block.nTime;
1185 nBits = block.nBits;
1186 nNonce = block.nNonce;
1189 CBlock GetBlockHeader() const
1192 block.nVersion = nVersion;
1194 block.hashPrevBlock = pprev->GetBlockHash();
1195 block.hashMerkleRoot = hashMerkleRoot;
1196 block.nTime = nTime;
1197 block.nBits = nBits;
1198 block.nNonce = nNonce;
1202 uint256 GetBlockHash() const
1207 int64 GetBlockTime() const
1209 return (int64)nTime;
1212 int64 GetBlockTrust() const
1214 return (nChainTrust - (pprev? pprev->nChainTrust : 0));
1217 bool IsInMainChain() const
1219 return (pnext || this == pindexBest);
1222 bool CheckIndex() const
1224 return IsProofOfWork() ? CheckProofOfWork(GetBlockHash(), nBits) : true;
1227 bool EraseBlockFromDisk()
1229 // Open history file
1230 CAutoFile fileout = CAutoFile(OpenBlockFile(nFile, nBlockPos, "rb+"), SER_DISK, CLIENT_VERSION);
1234 // Overwrite with empty null block
1242 enum { nMedianTimeSpan=11 };
1244 int64 GetMedianTimePast() const
1246 int64 pmedian[nMedianTimeSpan];
1247 int64* pbegin = &pmedian[nMedianTimeSpan];
1248 int64* pend = &pmedian[nMedianTimeSpan];
1250 const CBlockIndex* pindex = this;
1251 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1252 *(--pbegin) = pindex->GetBlockTime();
1254 std::sort(pbegin, pend);
1255 return pbegin[(pend - pbegin)/2];
1258 int64 GetMedianTime() const
1260 const CBlockIndex* pindex = this;
1261 for (int i = 0; i < nMedianTimeSpan/2; i++)
1264 return GetBlockTime();
1265 pindex = pindex->pnext;
1267 return pindex->GetMedianTimePast();
1270 bool IsProofOfWork() const
1272 return !fProofOfStake;
1275 bool IsProofOfStake() const
1277 return fProofOfStake;
1280 std::string ToString() const
1282 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nChainTrust=%"PRI64d" nHeight=%d, fProofOfStake=%d prevoutStake=(%s), nStakeTime=%d merkle=%s, hashBlock=%s)",
1283 pprev, pnext, nFile, nBlockPos, nChainTrust, nHeight,
1284 fProofOfStake, prevoutStake.ToString().c_str(), nStakeTime,
1285 hashMerkleRoot.ToString().substr(0,10).c_str(),
1286 GetBlockHash().ToString().substr(0,20).c_str());
1291 printf("%s\n", ToString().c_str());
1297 /** Used to marshal pointers into hashes for db storage. */
1298 class CDiskBlockIndex : public CBlockIndex
1310 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1312 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1313 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1318 if (!(nType & SER_GETHASH))
1319 READWRITE(nVersion);
1321 READWRITE(hashNext);
1323 READWRITE(nBlockPos);
1324 READWRITE(nChainTrust);
1326 READWRITE(fProofOfStake);
1329 READWRITE(prevoutStake);
1330 READWRITE(nStakeTime);
1334 const_cast<CDiskBlockIndex*>(this)->prevoutStake.SetNull();
1335 const_cast<CDiskBlockIndex*>(this)->nStakeTime = 0;
1339 READWRITE(this->nVersion);
1340 READWRITE(hashPrev);
1341 READWRITE(hashMerkleRoot);
1347 uint256 GetBlockHash() const
1350 block.nVersion = nVersion;
1351 block.hashPrevBlock = hashPrev;
1352 block.hashMerkleRoot = hashMerkleRoot;
1353 block.nTime = nTime;
1354 block.nBits = nBits;
1355 block.nNonce = nNonce;
1356 return block.GetHash();
1360 std::string ToString() const
1362 std::string str = "CDiskBlockIndex(";
1363 str += CBlockIndex::ToString();
1364 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1365 GetBlockHash().ToString().c_str(),
1366 hashPrev.ToString().substr(0,20).c_str(),
1367 hashNext.ToString().substr(0,20).c_str());
1373 printf("%s\n", ToString().c_str());
1384 /** Describes a place in the block chain to another node such that if the
1385 * other node doesn't have the same branch, it can find a recent common trunk.
1386 * The further back it is, the further before the fork it may be.
1391 std::vector<uint256> vHave;
1398 explicit CBlockLocator(const CBlockIndex* pindex)
1403 explicit CBlockLocator(uint256 hashBlock)
1405 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1406 if (mi != mapBlockIndex.end())
1410 CBlockLocator(const std::vector<uint256>& vHaveIn)
1417 if (!(nType & SER_GETHASH))
1418 READWRITE(nVersion);
1429 return vHave.empty();
1432 void Set(const CBlockIndex* pindex)
1438 vHave.push_back(pindex->GetBlockHash());
1440 // Exponentially larger steps back
1441 for (int i = 0; pindex && i < nStep; i++)
1442 pindex = pindex->pprev;
1443 if (vHave.size() > 10)
1446 vHave.push_back(hashGenesisBlock);
1449 int GetDistanceBack()
1451 // Retrace how far back it was in the sender's branch
1454 BOOST_FOREACH(const uint256& hash, vHave)
1456 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1457 if (mi != mapBlockIndex.end())
1459 CBlockIndex* pindex = (*mi).second;
1460 if (pindex->IsInMainChain())
1470 CBlockIndex* GetBlockIndex()
1472 // Find the first block the caller has in the main chain
1473 BOOST_FOREACH(const uint256& hash, vHave)
1475 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1476 if (mi != mapBlockIndex.end())
1478 CBlockIndex* pindex = (*mi).second;
1479 if (pindex->IsInMainChain())
1483 return pindexGenesisBlock;
1486 uint256 GetBlockHash()
1488 // Find the first block the caller has in the main chain
1489 BOOST_FOREACH(const uint256& hash, vHave)
1491 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1492 if (mi != mapBlockIndex.end())
1494 CBlockIndex* pindex = (*mi).second;
1495 if (pindex->IsInMainChain())
1499 return hashGenesisBlock;
1504 CBlockIndex* pindex = GetBlockIndex();
1507 return pindex->nHeight;
1519 /** Alerts are for notifying old versions if they become too obsolete and
1520 * need to upgrade. The message is displayed in the status bar.
1521 * Alert messages are broadcast as a vector of signed data. Unserializing may
1522 * not read the entire buffer if the alert is for a newer version, but older
1523 * versions can still relay the original data.
1525 class CUnsignedAlert
1529 int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
1533 std::set<int> setCancel;
1534 int nMinVer; // lowest version inclusive
1535 int nMaxVer; // highest version inclusive
1536 std::set<std::string> setSubVer; // empty matches all
1540 std::string strComment;
1541 std::string strStatusBar;
1542 std::string strReserved;
1546 READWRITE(this->nVersion);
1547 nVersion = this->nVersion;
1548 READWRITE(nRelayUntil);
1549 READWRITE(nExpiration);
1552 READWRITE(setCancel);
1555 READWRITE(setSubVer);
1556 READWRITE(nPriority);
1558 READWRITE(strComment);
1559 READWRITE(strStatusBar);
1560 READWRITE(strReserved);
1577 strStatusBar.clear();
1578 strReserved.clear();
1581 std::string ToString() const
1583 std::string strSetCancel;
1584 BOOST_FOREACH(int n, setCancel)
1585 strSetCancel += strprintf("%d ", n);
1586 std::string strSetSubVer;
1587 BOOST_FOREACH(std::string str, setSubVer)
1588 strSetSubVer += "\"" + str + "\" ";
1592 " nRelayUntil = %"PRI64d"\n"
1593 " nExpiration = %"PRI64d"\n"
1601 " strComment = \"%s\"\n"
1602 " strStatusBar = \"%s\"\n"
1609 strSetCancel.c_str(),
1612 strSetSubVer.c_str(),
1615 strStatusBar.c_str());
1620 printf("%s", ToString().c_str());
1624 /** An alert is a combination of a serialized CUnsignedAlert and a signature. */
1625 class CAlert : public CUnsignedAlert
1628 std::vector<unsigned char> vchMsg;
1629 std::vector<unsigned char> vchSig;
1644 CUnsignedAlert::SetNull();
1651 return (nExpiration == 0);
1654 uint256 GetHash() const
1656 return SerializeHash(*this);
1659 bool IsInEffect() const
1661 return (GetAdjustedTime() < nExpiration);
1664 bool Cancels(const CAlert& alert) const
1667 return false; // this was a no-op before 31403
1668 return (alert.nID <= nCancel || setCancel.count(alert.nID));
1671 bool AppliesTo(int nVersion, std::string strSubVerIn) const
1673 // TODO: rework for client-version-embedded-in-strSubVer ?
1674 return (IsInEffect() &&
1675 nMinVer <= nVersion && nVersion <= nMaxVer &&
1676 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1679 bool AppliesToMe() const
1681 return AppliesTo(PROTOCOL_VERSION, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<std::string>()));
1684 bool RelayTo(CNode* pnode) const
1688 // returns true if wasn't already contained in the set
1689 if (pnode->setKnown.insert(GetHash()).second)
1691 if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
1693 GetAdjustedTime() < nRelayUntil)
1695 pnode->PushMessage("alert", *this);
1702 bool CheckSignature()
1705 if (!key.SetPubKey(ParseHex("0487ca85b6ae9d311f996c7616d20d0c88a5b4f07d25e78f419019f35cce6522acf978b2d99f0e7a58db1f120439e5c1889266927854aa57c93956c2569188a539")))
1706 return error("CAlert::CheckSignature() : SetPubKey failed");
1707 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
1708 return error("CAlert::CheckSignature() : verify signature failed");
1710 // Now unserialize the data
1711 CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION);
1712 sMsg >> *(CUnsignedAlert*)this;
1716 bool ProcessAlert();
1722 mutable CCriticalSection cs;
1723 std::map<uint256, CTransaction> mapTx;
1724 std::map<COutPoint, CInPoint> mapNextTx;
1726 bool accept(CTxDB& txdb, CTransaction &tx,
1727 bool fCheckInputs, bool* pfMissingInputs);
1728 bool addUnchecked(CTransaction &tx);
1729 bool remove(CTransaction &tx);
1731 unsigned long size()
1734 return mapTx.size();
1737 bool exists(uint256 hash)
1739 return (mapTx.count(hash) != 0);
1742 CTransaction& lookup(uint256 hash)
1748 extern CTxMemPool mempool;