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 CBlockIndex* pindexGenesisBlock;
65 extern int nBestHeight;
66 extern CBigNum bnBestChainTrust;
67 extern CBigNum bnBestInvalidTrust;
68 extern uint256 hashBestChain;
69 extern CBlockIndex* pindexBest;
70 extern unsigned int nTransactionsUpdated;
71 extern uint64 nLastBlockTx;
72 extern uint64 nLastBlockSize;
73 extern const std::string strMessageMagic;
74 extern double dHashesPerSec;
75 extern int64 nHPSTimerStart;
76 extern int64 nTimeBestReceived;
77 extern CCriticalSection cs_setpwalletRegistered;
78 extern std::set<CWallet*> setpwalletRegistered;
79 extern std::map<uint256, CBlock*> mapOrphanBlocks;
82 extern int64 nTransactionFee;
92 void RegisterWallet(CWallet* pwalletIn);
93 void UnregisterWallet(CWallet* pwalletIn);
94 bool ProcessBlock(CNode* pfrom, CBlock* pblock);
95 bool CheckDiskSpace(uint64 nAdditionalBytes=0);
96 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
97 FILE* AppendBlockFile(unsigned int& nFileRet);
98 bool LoadBlockIndex(bool fAllowNew=true);
99 void PrintBlockTree();
100 bool ProcessMessages(CNode* pfrom);
101 bool SendMessages(CNode* pto, bool fSendTrickle);
102 void GenerateBitcoins(bool fGenerate, CWallet* pwallet);
103 CBlock* CreateNewBlock(CWallet* pwallet, bool fProofOfStake=false);
104 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce);
105 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
106 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey);
107 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
108 int64 GetProofOfWorkReward(unsigned int nBits);
109 int64 GetProofOfStakeReward(int64 nCoinAge);
110 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime);
111 int GetNumBlocksOfPeers();
112 bool IsInitialBlockDownload();
113 std::string GetWarnings(std::string strFor);
114 uint256 WantedByOrphan(const CBlock* pblockOrphan);
115 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake);
116 void BitcoinMiner(CWallet *pwallet, bool fProofOfStake);
128 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
130 /** Position on disk for a particular transaction. */
135 unsigned int nBlockPos;
143 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
146 nBlockPos = nBlockPosIn;
150 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
151 void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
152 bool IsNull() const { return (nFile == -1); }
154 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
156 return (a.nFile == b.nFile &&
157 a.nBlockPos == b.nBlockPos &&
158 a.nTxPos == b.nTxPos);
161 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
166 std::string ToString() const
171 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
176 printf("%s", ToString().c_str());
182 /** An inpoint - a combination of a transaction and an index n into its vin */
189 CInPoint() { SetNull(); }
190 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
191 void SetNull() { ptx = NULL; n = -1; }
192 bool IsNull() const { return (ptx == NULL && n == -1); }
197 /** An outpoint - a combination of a transaction hash and an index n into its vout */
204 COutPoint() { SetNull(); }
205 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
206 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
207 void SetNull() { hash = 0; n = -1; }
208 bool IsNull() const { return (hash == 0 && n == -1); }
210 friend bool operator<(const COutPoint& a, const COutPoint& b)
212 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
215 friend bool operator==(const COutPoint& a, const COutPoint& b)
217 return (a.hash == b.hash && a.n == b.n);
220 friend bool operator!=(const COutPoint& a, const COutPoint& b)
225 std::string ToString() const
227 return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,10).c_str(), n);
232 printf("%s\n", ToString().c_str());
239 /** An input of a transaction. It contains the location of the previous
240 * transaction's output that it claims and a signature that matches the
241 * output's public key.
248 unsigned int nSequence;
252 nSequence = std::numeric_limits<unsigned int>::max();
255 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
258 scriptSig = scriptSigIn;
259 nSequence = nSequenceIn;
262 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
264 prevout = COutPoint(hashPrevTx, nOut);
265 scriptSig = scriptSigIn;
266 nSequence = nSequenceIn;
272 READWRITE(scriptSig);
273 READWRITE(nSequence);
278 return (nSequence == std::numeric_limits<unsigned int>::max());
281 friend bool operator==(const CTxIn& a, const CTxIn& b)
283 return (a.prevout == b.prevout &&
284 a.scriptSig == b.scriptSig &&
285 a.nSequence == b.nSequence);
288 friend bool operator!=(const CTxIn& a, const CTxIn& b)
293 std::string ToString() const
297 str += prevout.ToString();
298 if (prevout.IsNull())
299 str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
301 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
302 if (nSequence != std::numeric_limits<unsigned int>::max())
303 str += strprintf(", nSequence=%u", nSequence);
310 printf("%s\n", ToString().c_str());
317 /** An output of a transaction. It contains the public key that the next input
318 * must be able to sign with to claim it.
324 CScript scriptPubKey;
331 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
334 scriptPubKey = scriptPubKeyIn;
340 READWRITE(scriptPubKey);
346 scriptPubKey.clear();
351 return (nValue == -1);
357 scriptPubKey.clear();
362 return (nValue == 0 && scriptPubKey.empty());
365 uint256 GetHash() const
367 return SerializeHash(*this);
370 friend bool operator==(const CTxOut& a, const CTxOut& b)
372 return (a.nValue == b.nValue &&
373 a.scriptPubKey == b.scriptPubKey);
376 friend bool operator!=(const CTxOut& a, const CTxOut& b)
381 std::string ToString() const
383 if (IsEmpty()) return "CTxOut(empty)";
384 if (scriptPubKey.size() < 6)
385 return "CTxOut(error)";
386 return strprintf("CTxOut(nValue=%s, scriptPubKey=%s)", FormatMoney(nValue).c_str(), scriptPubKey.ToString().substr(0,30).c_str());
391 printf("%s\n", ToString().c_str());
405 typedef std::map<uint256, std::pair<CTxIndex, CTransaction> > MapPrevTx;
407 /** The basic transaction that is broadcasted on the network and contained in
408 * blocks. A transaction can contain multiple inputs and outputs.
415 std::vector<CTxIn> vin;
416 std::vector<CTxOut> vout;
417 unsigned int nLockTime;
419 // Denial-of-service detection:
421 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
430 READWRITE(this->nVersion);
431 nVersion = this->nVersion;
435 READWRITE(nLockTime);
441 nTime = GetAdjustedTime();
445 nDoS = 0; // Denial-of-service prevention
450 return (vin.empty() && vout.empty());
453 uint256 GetHash() const
455 return SerializeHash(*this);
458 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
460 // Time based nLockTime implemented in 0.1.6
463 if (nBlockHeight == 0)
464 nBlockHeight = nBestHeight;
466 nBlockTime = GetAdjustedTime();
467 if ((int64)nLockTime < ((int64)nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
469 BOOST_FOREACH(const CTxIn& txin, vin)
475 bool IsNewerThan(const CTransaction& old) const
477 if (vin.size() != old.vin.size())
479 for (unsigned int i = 0; i < vin.size(); i++)
480 if (vin[i].prevout != old.vin[i].prevout)
484 unsigned int nLowest = std::numeric_limits<unsigned int>::max();
485 for (unsigned int i = 0; i < vin.size(); i++)
487 if (vin[i].nSequence != old.vin[i].nSequence)
489 if (vin[i].nSequence <= nLowest)
492 nLowest = vin[i].nSequence;
494 if (old.vin[i].nSequence < nLowest)
497 nLowest = old.vin[i].nSequence;
504 bool IsCoinBase() const
506 return (vin.size() == 1 && vin[0].prevout.IsNull() && vout.size() >= 1);
509 bool IsCoinStake() const
511 // ppcoin: the coin stake transaction is marked with the first output empty
512 return (vin.size() > 0 && (!vin[0].prevout.IsNull()) && vout.size() >= 2 && vout[0].IsEmpty());
515 /** Check for standard transaction types
516 @return True if all outputs (scriptPubKeys) use only standard transaction forms
518 bool IsStandard() const;
520 /** Check for standard transaction types
521 @param[in] mapInputs Map of previous transactions that have outputs we're spending
522 @return True if all inputs (scriptSigs) use only standard transaction forms
523 @see CTransaction::FetchInputs
525 bool AreInputsStandard(const MapPrevTx& mapInputs) const;
527 /** Count ECDSA signature operations the old-fashioned (pre-0.6) way
528 @return number of sigops this transaction's outputs will produce when spent
529 @see CTransaction::FetchInputs
531 unsigned int GetLegacySigOpCount() const;
533 /** Count ECDSA signature operations in pay-to-script-hash inputs.
535 @param[in] mapInputs Map of previous transactions that have outputs we're spending
536 @return maximum number of sigops required to validate this transaction's inputs
537 @see CTransaction::FetchInputs
539 unsigned int GetP2SHSigOpCount(const MapPrevTx& mapInputs) const;
541 /** Amount of bitcoins spent by this transaction.
542 @return sum of all outputs (note: does not include fees)
544 int64 GetValueOut() const
547 BOOST_FOREACH(const CTxOut& txout, vout)
549 nValueOut += txout.nValue;
550 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
551 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
556 /** Amount of bitcoins coming in to this transaction
557 Note that lightweight clients may not know anything besides the hash of previous transactions,
558 so may not be able to calculate this.
560 @param[in] mapInputs Map of previous transactions that have outputs we're spending
561 @return Sum of value of all inputs (scriptSigs)
562 @see CTransaction::FetchInputs
564 int64 GetValueIn(const MapPrevTx& mapInputs) const;
566 static bool AllowFree(double dPriority)
568 // Large (in bytes) low-priority (new, small-coin) transactions
570 return dPriority > COIN * 144 / 250;
573 int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=false, enum GetMinFee_mode mode=GMF_BLOCK) const
575 // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
576 int64 nBaseFee = (mode == GMF_RELAY) ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
578 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION);
579 unsigned int nNewBlockSize = nBlockSize + nBytes;
580 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
586 // Transactions under 10K are free
587 // (about 4500bc if made of 50bc inputs)
593 // Free transaction area
594 if (nNewBlockSize < 27000)
599 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
600 if (nMinFee < nBaseFee)
602 BOOST_FOREACH(const CTxOut& txout, vout)
603 if (txout.nValue < CENT)
607 // Raise the price as the block approaches full
608 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
610 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
612 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
615 if (!MoneyRange(nMinFee))
621 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
623 CAutoFile filein = CAutoFile(OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb"), SER_DISK, CLIENT_VERSION);
625 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
628 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
629 return error("CTransaction::ReadFromDisk() : fseek failed");
634 catch (std::exception &e) {
635 return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
638 // Return file pointer
641 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
642 return error("CTransaction::ReadFromDisk() : second fseek failed");
643 *pfileRet = filein.release();
648 friend bool operator==(const CTransaction& a, const CTransaction& b)
650 return (a.nVersion == b.nVersion &&
651 a.nTime == b.nTime &&
654 a.nLockTime == b.nLockTime);
657 friend bool operator!=(const CTransaction& a, const CTransaction& b)
663 std::string ToString() const
666 str += IsCoinBase()? "Coinbase" : (IsCoinStake()? "Coinstake" : "CTransaction");
667 str += strprintf("(hash=%s, nTime=%d, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
668 GetHash().ToString().substr(0,10).c_str(),
674 for (unsigned int i = 0; i < vin.size(); i++)
675 str += " " + vin[i].ToString() + "\n";
676 for (unsigned int i = 0; i < vout.size(); i++)
677 str += " " + vout[i].ToString() + "\n";
683 printf("%s", ToString().c_str());
687 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
688 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
689 bool ReadFromDisk(COutPoint prevout);
690 bool DisconnectInputs(CTxDB& txdb);
692 /** Fetch from memory and/or disk. inputsRet keys are transaction hashes.
694 @param[in] txdb Transaction database
695 @param[in] mapTestPool List of pending changes to the transaction index database
696 @param[in] fBlock True if being called to add a new best-block to the chain
697 @param[in] fMiner True if being called by CreateNewBlock
698 @param[out] inputsRet Pointers to this transaction's inputs
699 @param[out] fInvalid returns true if transaction is invalid
700 @return Returns true if all inputs are in txdb or mapTestPool
702 bool FetchInputs(CTxDB& txdb, const std::map<uint256, CTxIndex>& mapTestPool,
703 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid);
705 /** Sanity check previous transactions, then, if all checks succeed,
706 mark them as spent by this transaction.
708 @param[in] inputs Previous transactions (from FetchInputs)
709 @param[out] mapTestPool Keeps track of inputs that need to be updated on disk
710 @param[in] posThisTx Position of this transaction on disk
711 @param[in] pindexBlock
712 @param[in] fBlock true if called from ConnectBlock
713 @param[in] fMiner true if called from CreateNewBlock
714 @param[in] fStrictPayToScriptHash true if fully validating p2sh transactions
715 @return Returns true if all checks succeed
717 bool ConnectInputs(CTxDB& txdb, MapPrevTx inputs,
718 std::map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
719 const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash=true);
720 bool ClientConnectInputs();
721 bool CheckTransaction() const;
722 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
723 bool GetCoinAge(CTxDB& txdb, uint64& nCoinAge) const; // ppcoin: get transaction coin age
724 bool CheckProofOfStake(unsigned int nBits) const;
727 const CTxOut& GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const;
734 /** A transaction with a merkle branch linking it to the block chain. */
735 class CMerkleTx : public CTransaction
739 std::vector<uint256> vMerkleBranch;
743 mutable bool fMerkleVerified;
751 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
760 fMerkleVerified = false;
766 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
767 nVersion = this->nVersion;
768 READWRITE(hashBlock);
769 READWRITE(vMerkleBranch);
774 int SetMerkleBranch(const CBlock* pblock=NULL);
775 int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
776 int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
777 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
778 int GetBlocksToMaturity() const;
779 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
780 bool AcceptToMemoryPool();
786 /** A txdb record that contains the disk location of a transaction and the
787 * locations of transactions that spend its outputs. vSpent is really only
788 * used as a flag, but having the location is very helpful for debugging.
794 std::vector<CDiskTxPos> vSpent;
801 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
804 vSpent.resize(nOutputs);
809 if (!(nType & SER_GETHASH))
826 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
828 return (a.pos == b.pos &&
829 a.vSpent == b.vSpent);
832 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
836 int GetDepthInMainChain() const;
844 /** Nodes collect new transactions into a block, hash them into a hash tree,
845 * and scan through nonce values to make the block's hash satisfy proof-of-work
846 * requirements. When they solve the proof-of-work, they broadcast the block
847 * to everyone and the block is added to the block chain. The first transaction
848 * in the block is a special one that creates a new coin owned by the creator
851 * Blocks are appended to blk0001.dat files on disk. Their location on disk
852 * is indexed by CBlockIndex objects in memory.
859 uint256 hashPrevBlock;
860 uint256 hashMerkleRoot;
866 std::vector<CTransaction> vtx;
868 // ppcoin: block signature - signed by coin base txout[0]'s owner
869 std::vector<unsigned char> vchBlockSig;
872 mutable std::vector<uint256> vMerkleTree;
874 // Denial-of-service detection:
876 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
885 READWRITE(this->nVersion);
886 nVersion = this->nVersion;
887 READWRITE(hashPrevBlock);
888 READWRITE(hashMerkleRoot);
893 // ConnectBlock depends on vtx following header to generate CDiskTxPos
894 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
897 READWRITE(vchBlockSig);
901 const_cast<CBlock*>(this)->vtx.clear();
902 const_cast<CBlock*>(this)->vchBlockSig.clear();
925 uint256 GetHash() const
927 return Hash(BEGIN(nVersion), END(nNonce));
930 int64 GetBlockTime() const
935 void UpdateTime(const CBlockIndex* pindexPrev);
937 // ppcoin: two types of block: proof-of-work or proof-of-stake
938 bool IsProofOfStake() const
940 return (vtx.size() > 1 && vtx[1].IsCoinStake());
943 bool IsProofOfWork() const
945 return !IsProofOfStake();
948 std::pair<COutPoint, unsigned int> GetProofOfStake() const
950 return IsProofOfStake()? std::make_pair(vtx[1].vin[0].prevout, vtx[1].nTime) : std::make_pair(COutPoint(), (unsigned int)0);
953 // ppcoin: get max transaction timestamp
954 int64 GetMaxTransactionTime() const
956 int64 maxTransactionTime = 0;
957 BOOST_FOREACH(const CTransaction& tx, vtx)
958 maxTransactionTime = std::max(maxTransactionTime, (int64)tx.nTime);
959 return maxTransactionTime;
962 uint256 BuildMerkleTree() const
965 BOOST_FOREACH(const CTransaction& tx, vtx)
966 vMerkleTree.push_back(tx.GetHash());
968 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
970 for (int i = 0; i < nSize; i += 2)
972 int i2 = std::min(i+1, nSize-1);
973 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
974 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
978 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
981 std::vector<uint256> GetMerkleBranch(int nIndex) const
983 if (vMerkleTree.empty())
985 std::vector<uint256> vMerkleBranch;
987 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
989 int i = std::min(nIndex^1, nSize-1);
990 vMerkleBranch.push_back(vMerkleTree[j+i]);
994 return vMerkleBranch;
997 static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
1001 BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
1004 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
1006 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
1013 bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
1015 // Open history file to append
1016 CAutoFile fileout = CAutoFile(AppendBlockFile(nFileRet), SER_DISK, CLIENT_VERSION);
1018 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
1020 // Write index header
1021 unsigned int nSize = fileout.GetSerializeSize(*this);
1022 fileout << FLATDATA(pchMessageStart) << nSize;
1025 long fileOutPos = ftell(fileout);
1027 return error("CBlock::WriteToDisk() : ftell failed");
1028 nBlockPosRet = fileOutPos;
1031 // Flush stdio buffers and commit to disk before returning
1033 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
1036 _commit(_fileno(fileout));
1038 fsync(fileno(fileout));
1045 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
1049 // Open history file to read
1050 CAutoFile filein = CAutoFile(OpenBlockFile(nFile, nBlockPos, "rb"), SER_DISK, CLIENT_VERSION);
1052 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1053 if (!fReadTransactions)
1054 filein.nType |= SER_BLOCKHEADERONLY;
1060 catch (std::exception &e) {
1061 return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
1065 if (fReadTransactions && IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
1066 return error("CBlock::ReadFromDisk() : errors in block header");
1075 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d, vchBlockSig=%s)\n",
1076 GetHash().ToString().substr(0,20).c_str(),
1078 hashPrevBlock.ToString().substr(0,20).c_str(),
1079 hashMerkleRoot.ToString().substr(0,10).c_str(),
1080 nTime, nBits, nNonce,
1082 HexStr(vchBlockSig.begin(), vchBlockSig.end()).c_str());
1083 for (unsigned int i = 0; i < vtx.size(); i++)
1088 printf(" vMerkleTree: ");
1089 for (unsigned int i = 0; i < vMerkleTree.size(); i++)
1090 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1095 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1096 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1097 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1098 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1099 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1100 bool CheckBlock() const;
1102 bool GetCoinAge(uint64& nCoinAge) const; // ppcoin: calculate total coin age spent in block
1103 bool SignBlock(const CKeyStore& keystore);
1104 bool CheckBlockSignature() const;
1107 bool SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew);
1115 /** The block chain is a tree shaped structure starting with the
1116 * genesis block at the root, with each block potentially having multiple
1117 * candidates to be the next block. pprev and pnext link a path through the
1118 * main/longest chain. A blockindex may have multiple pprev pointing back
1119 * to it, but pnext will only point forward to the longest branch, or will
1120 * be null if the block is not part of the longest chain.
1125 const uint256* phashBlock;
1129 unsigned int nBlockPos;
1130 CBigNum bnChainTrust; // ppcoin: trust score of block chain
1134 bool fProofOfStake; // ppcoin: is the block of proof-of-stake type
1135 COutPoint prevoutStake;
1136 unsigned int nStakeTime;
1140 uint256 hashMerkleRoot;
1143 unsigned int nNonce;
1157 fProofOfStake = true;
1158 prevoutStake.SetNull();
1168 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1174 nBlockPos = nBlockPosIn;
1179 fProofOfStake = block.IsProofOfStake();
1182 prevoutStake = block.vtx[1].vin[0].prevout;
1183 nStakeTime = block.vtx[1].nTime;
1187 prevoutStake.SetNull();
1191 nVersion = block.nVersion;
1192 hashMerkleRoot = block.hashMerkleRoot;
1193 nTime = block.nTime;
1194 nBits = block.nBits;
1195 nNonce = block.nNonce;
1198 CBlock GetBlockHeader() const
1201 block.nVersion = nVersion;
1203 block.hashPrevBlock = pprev->GetBlockHash();
1204 block.hashMerkleRoot = hashMerkleRoot;
1205 block.nTime = nTime;
1206 block.nBits = nBits;
1207 block.nNonce = nNonce;
1211 uint256 GetBlockHash() const
1216 int64 GetBlockTime() const
1218 return (int64)nTime;
1221 CBigNum GetBlockTrust() const
1224 bnTarget.SetCompact(nBits);
1227 return (fProofOfStake? (CBigNum(1)<<256) / (bnTarget+1) : 1);
1230 bool IsInMainChain() const
1232 return (pnext || this == pindexBest);
1235 bool CheckIndex() const
1237 return IsProofOfWork() ? CheckProofOfWork(GetBlockHash(), nBits) : true;
1240 bool EraseBlockFromDisk()
1242 // Open history file
1243 CAutoFile fileout = CAutoFile(OpenBlockFile(nFile, nBlockPos, "rb+"), SER_DISK, CLIENT_VERSION);
1247 // Overwrite with empty null block
1255 enum { nMedianTimeSpan=11 };
1257 int64 GetMedianTimePast() const
1259 int64 pmedian[nMedianTimeSpan];
1260 int64* pbegin = &pmedian[nMedianTimeSpan];
1261 int64* pend = &pmedian[nMedianTimeSpan];
1263 const CBlockIndex* pindex = this;
1264 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1265 *(--pbegin) = pindex->GetBlockTime();
1267 std::sort(pbegin, pend);
1268 return pbegin[(pend - pbegin)/2];
1271 int64 GetMedianTime() const
1273 const CBlockIndex* pindex = this;
1274 for (int i = 0; i < nMedianTimeSpan/2; i++)
1277 return GetBlockTime();
1278 pindex = pindex->pnext;
1280 return pindex->GetMedianTimePast();
1283 bool IsProofOfWork() const
1285 return !fProofOfStake;
1288 bool IsProofOfStake() const
1290 return fProofOfStake;
1293 std::string ToString() const
1295 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)",
1296 pprev, pnext, nFile, nBlockPos, nHeight,
1297 FormatMoney(nMint).c_str(), FormatMoney(nMoneySupply).c_str(),
1298 fProofOfStake, prevoutStake.ToString().c_str(), nStakeTime,
1299 hashMerkleRoot.ToString().substr(0,10).c_str(),
1300 GetBlockHash().ToString().substr(0,20).c_str());
1305 printf("%s\n", ToString().c_str());
1311 /** Used to marshal pointers into hashes for db storage. */
1312 class CDiskBlockIndex : public CBlockIndex
1324 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1326 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1327 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1332 if (!(nType & SER_GETHASH))
1333 READWRITE(nVersion);
1335 READWRITE(hashNext);
1337 READWRITE(nBlockPos);
1340 READWRITE(nMoneySupply);
1341 READWRITE(fProofOfStake);
1344 READWRITE(prevoutStake);
1345 READWRITE(nStakeTime);
1349 const_cast<CDiskBlockIndex*>(this)->prevoutStake.SetNull();
1350 const_cast<CDiskBlockIndex*>(this)->nStakeTime = 0;
1354 READWRITE(this->nVersion);
1355 READWRITE(hashPrev);
1356 READWRITE(hashMerkleRoot);
1362 uint256 GetBlockHash() const
1365 block.nVersion = nVersion;
1366 block.hashPrevBlock = hashPrev;
1367 block.hashMerkleRoot = hashMerkleRoot;
1368 block.nTime = nTime;
1369 block.nBits = nBits;
1370 block.nNonce = nNonce;
1371 return block.GetHash();
1375 std::string ToString() const
1377 std::string str = "CDiskBlockIndex(";
1378 str += CBlockIndex::ToString();
1379 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1380 GetBlockHash().ToString().c_str(),
1381 hashPrev.ToString().substr(0,20).c_str(),
1382 hashNext.ToString().substr(0,20).c_str());
1388 printf("%s\n", ToString().c_str());
1399 /** Describes a place in the block chain to another node such that if the
1400 * other node doesn't have the same branch, it can find a recent common trunk.
1401 * The further back it is, the further before the fork it may be.
1406 std::vector<uint256> vHave;
1413 explicit CBlockLocator(const CBlockIndex* pindex)
1418 explicit CBlockLocator(uint256 hashBlock)
1420 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1421 if (mi != mapBlockIndex.end())
1425 CBlockLocator(const std::vector<uint256>& vHaveIn)
1432 if (!(nType & SER_GETHASH))
1433 READWRITE(nVersion);
1444 return vHave.empty();
1447 void Set(const CBlockIndex* pindex)
1453 vHave.push_back(pindex->GetBlockHash());
1455 // Exponentially larger steps back
1456 for (int i = 0; pindex && i < nStep; i++)
1457 pindex = pindex->pprev;
1458 if (vHave.size() > 10)
1461 vHave.push_back(hashGenesisBlock);
1464 int GetDistanceBack()
1466 // Retrace how far back it was in the sender's branch
1469 BOOST_FOREACH(const uint256& hash, vHave)
1471 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1472 if (mi != mapBlockIndex.end())
1474 CBlockIndex* pindex = (*mi).second;
1475 if (pindex->IsInMainChain())
1485 CBlockIndex* GetBlockIndex()
1487 // Find the first block the caller has in the main chain
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())
1498 return pindexGenesisBlock;
1501 uint256 GetBlockHash()
1503 // Find the first block the caller has in the main chain
1504 BOOST_FOREACH(const uint256& hash, vHave)
1506 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1507 if (mi != mapBlockIndex.end())
1509 CBlockIndex* pindex = (*mi).second;
1510 if (pindex->IsInMainChain())
1514 return hashGenesisBlock;
1519 CBlockIndex* pindex = GetBlockIndex();
1522 return pindex->nHeight;
1534 /** Alerts are for notifying old versions if they become too obsolete and
1535 * need to upgrade. The message is displayed in the status bar.
1536 * Alert messages are broadcast as a vector of signed data. Unserializing may
1537 * not read the entire buffer if the alert is for a newer version, but older
1538 * versions can still relay the original data.
1540 class CUnsignedAlert
1544 int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
1548 std::set<int> setCancel;
1549 int nMinVer; // lowest version inclusive
1550 int nMaxVer; // highest version inclusive
1551 std::set<std::string> setSubVer; // empty matches all
1555 std::string strComment;
1556 std::string strStatusBar;
1557 std::string strReserved;
1561 READWRITE(this->nVersion);
1562 nVersion = this->nVersion;
1563 READWRITE(nRelayUntil);
1564 READWRITE(nExpiration);
1567 READWRITE(setCancel);
1570 READWRITE(setSubVer);
1571 READWRITE(nPriority);
1573 READWRITE(strComment);
1574 READWRITE(strStatusBar);
1575 READWRITE(strReserved);
1592 strStatusBar.clear();
1593 strReserved.clear();
1596 std::string ToString() const
1598 std::string strSetCancel;
1599 BOOST_FOREACH(int n, setCancel)
1600 strSetCancel += strprintf("%d ", n);
1601 std::string strSetSubVer;
1602 BOOST_FOREACH(std::string str, setSubVer)
1603 strSetSubVer += "\"" + str + "\" ";
1607 " nRelayUntil = %"PRI64d"\n"
1608 " nExpiration = %"PRI64d"\n"
1616 " strComment = \"%s\"\n"
1617 " strStatusBar = \"%s\"\n"
1624 strSetCancel.c_str(),
1627 strSetSubVer.c_str(),
1630 strStatusBar.c_str());
1635 printf("%s", ToString().c_str());
1639 /** An alert is a combination of a serialized CUnsignedAlert and a signature. */
1640 class CAlert : public CUnsignedAlert
1643 std::vector<unsigned char> vchMsg;
1644 std::vector<unsigned char> vchSig;
1659 CUnsignedAlert::SetNull();
1666 return (nExpiration == 0);
1669 uint256 GetHash() const
1671 return SerializeHash(*this);
1674 bool IsInEffect() const
1676 return (GetAdjustedTime() < nExpiration);
1679 bool Cancels(const CAlert& alert) const
1682 return false; // this was a no-op before 31403
1683 return (alert.nID <= nCancel || setCancel.count(alert.nID));
1686 bool AppliesTo(int nVersion, std::string strSubVerIn) const
1688 // TODO: rework for client-version-embedded-in-strSubVer ?
1689 return (IsInEffect() &&
1690 nMinVer <= nVersion && nVersion <= nMaxVer &&
1691 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1694 bool AppliesToMe() const
1696 return AppliesTo(PROTOCOL_VERSION, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<std::string>()));
1699 bool RelayTo(CNode* pnode) const
1703 // returns true if wasn't already contained in the set
1704 if (pnode->setKnown.insert(GetHash()).second)
1706 if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
1708 GetAdjustedTime() < nRelayUntil)
1710 pnode->PushMessage("alert", *this);
1717 bool CheckSignature()
1720 if (!key.SetPubKey(ParseHex("04a0a849dd49b113d3179a332dd77715c43be4d0076e2f19e66de23dd707e56630f792f298dfd209bf042bb3561f4af6983f3d81e439737ab0bf7f898fecd21aab")))
1721 return error("CAlert::CheckSignature() : SetPubKey failed");
1722 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
1723 return error("CAlert::CheckSignature() : verify signature failed");
1725 // Now unserialize the data
1726 CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION);
1727 sMsg >> *(CUnsignedAlert*)this;
1731 bool ProcessAlert();
1737 mutable CCriticalSection cs;
1738 std::map<uint256, CTransaction> mapTx;
1739 std::map<COutPoint, CInPoint> mapNextTx;
1741 bool accept(CTxDB& txdb, CTransaction &tx,
1742 bool fCheckInputs, bool* pfMissingInputs);
1743 bool addUnchecked(CTransaction &tx);
1744 bool remove(CTransaction &tx);
1746 unsigned long size()
1749 return mapTx.size();
1752 bool exists(uint256 hash)
1754 return (mapTx.count(hash) != 0);
1757 CTransaction& lookup(uint256 hash)
1763 extern CTxMemPool mempool;