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 GetProofOfStakeReward(int64 nCoinAge);
109 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime);
110 int GetNumBlocksOfPeers();
111 bool IsInitialBlockDownload();
112 std::string GetWarnings(std::string strFor);
113 uint256 WantedByOrphan(const CBlock* pblockOrphan);
114 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake);
115 void BitcoinMiner(CWallet *pwallet, bool fProofOfStake);
127 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
129 /** Position on disk for a particular transaction. */
134 unsigned int nBlockPos;
142 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
145 nBlockPos = nBlockPosIn;
149 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
150 void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
151 bool IsNull() const { return (nFile == -1); }
153 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
155 return (a.nFile == b.nFile &&
156 a.nBlockPos == b.nBlockPos &&
157 a.nTxPos == b.nTxPos);
160 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
165 std::string ToString() const
170 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
175 printf("%s", ToString().c_str());
181 /** An inpoint - a combination of a transaction and an index n into its vin */
188 CInPoint() { SetNull(); }
189 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
190 void SetNull() { ptx = NULL; n = -1; }
191 bool IsNull() const { return (ptx == NULL && n == -1); }
196 /** An outpoint - a combination of a transaction hash and an index n into its vout */
203 COutPoint() { SetNull(); }
204 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
205 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
206 void SetNull() { hash = 0; n = -1; }
207 bool IsNull() const { return (hash == 0 && n == -1); }
209 friend bool operator<(const COutPoint& a, const COutPoint& b)
211 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
214 friend bool operator==(const COutPoint& a, const COutPoint& b)
216 return (a.hash == b.hash && a.n == b.n);
219 friend bool operator!=(const COutPoint& a, const COutPoint& b)
224 std::string ToString() const
226 return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,10).c_str(), n);
231 printf("%s\n", ToString().c_str());
238 /** An input of a transaction. It contains the location of the previous
239 * transaction's output that it claims and a signature that matches the
240 * output's public key.
247 unsigned int nSequence;
251 nSequence = std::numeric_limits<unsigned int>::max();
254 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
257 scriptSig = scriptSigIn;
258 nSequence = nSequenceIn;
261 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
263 prevout = COutPoint(hashPrevTx, nOut);
264 scriptSig = scriptSigIn;
265 nSequence = nSequenceIn;
271 READWRITE(scriptSig);
272 READWRITE(nSequence);
277 return (nSequence == std::numeric_limits<unsigned int>::max());
280 friend bool operator==(const CTxIn& a, const CTxIn& b)
282 return (a.prevout == b.prevout &&
283 a.scriptSig == b.scriptSig &&
284 a.nSequence == b.nSequence);
287 friend bool operator!=(const CTxIn& a, const CTxIn& b)
292 std::string ToString() const
296 str += prevout.ToString();
297 if (prevout.IsNull())
298 str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
300 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
301 if (nSequence != std::numeric_limits<unsigned int>::max())
302 str += strprintf(", nSequence=%u", nSequence);
309 printf("%s\n", ToString().c_str());
316 /** An output of a transaction. It contains the public key that the next input
317 * must be able to sign with to claim it.
323 CScript scriptPubKey;
330 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
333 scriptPubKey = scriptPubKeyIn;
339 READWRITE(scriptPubKey);
345 scriptPubKey.clear();
350 return (nValue == -1);
356 scriptPubKey.clear();
361 return (nValue == 0 && scriptPubKey.empty());
364 uint256 GetHash() const
366 return SerializeHash(*this);
369 friend bool operator==(const CTxOut& a, const CTxOut& b)
371 return (a.nValue == b.nValue &&
372 a.scriptPubKey == b.scriptPubKey);
375 friend bool operator!=(const CTxOut& a, const CTxOut& b)
380 std::string ToString() const
382 if (IsEmpty()) return "CTxOut(empty)";
383 if (scriptPubKey.size() < 6)
384 return "CTxOut(error)";
385 return strprintf("CTxOut(nValue=%s, scriptPubKey=%s)", FormatMoney(nValue).c_str(), scriptPubKey.ToString().substr(0,30).c_str());
390 printf("%s\n", ToString().c_str());
404 typedef std::map<uint256, std::pair<CTxIndex, CTransaction> > MapPrevTx;
406 /** The basic transaction that is broadcasted on the network and contained in
407 * blocks. A transaction can contain multiple inputs and outputs.
414 std::vector<CTxIn> vin;
415 std::vector<CTxOut> vout;
416 unsigned int nLockTime;
418 // Denial-of-service detection:
420 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
429 READWRITE(this->nVersion);
430 nVersion = this->nVersion;
434 READWRITE(nLockTime);
440 nTime = GetAdjustedTime();
444 nDoS = 0; // Denial-of-service prevention
449 return (vin.empty() && vout.empty());
452 uint256 GetHash() const
454 return SerializeHash(*this);
457 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
459 // Time based nLockTime implemented in 0.1.6
462 if (nBlockHeight == 0)
463 nBlockHeight = nBestHeight;
465 nBlockTime = GetAdjustedTime();
466 if ((int64)nLockTime < ((int64)nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
468 BOOST_FOREACH(const CTxIn& txin, vin)
474 bool IsNewerThan(const CTransaction& old) const
476 if (vin.size() != old.vin.size())
478 for (unsigned int i = 0; i < vin.size(); i++)
479 if (vin[i].prevout != old.vin[i].prevout)
483 unsigned int nLowest = std::numeric_limits<unsigned int>::max();
484 for (unsigned int i = 0; i < vin.size(); i++)
486 if (vin[i].nSequence != old.vin[i].nSequence)
488 if (vin[i].nSequence <= nLowest)
491 nLowest = vin[i].nSequence;
493 if (old.vin[i].nSequence < nLowest)
496 nLowest = old.vin[i].nSequence;
503 bool IsCoinBase() const
505 return (vin.size() == 1 && vin[0].prevout.IsNull() && vout.size() == 1);
508 bool IsCoinStake() const
510 // ppcoin: the coin stake transaction is marked with the first output empty
511 return (vin.size() > 0 && vout.size() == 2 && vout[0].IsEmpty());
514 /** Check for standard transaction types
515 @return True if all outputs (scriptPubKeys) use only standard transaction forms
517 bool IsStandard() const;
519 /** Check for standard transaction types
520 @param[in] mapInputs Map of previous transactions that have outputs we're spending
521 @return True if all inputs (scriptSigs) use only standard transaction forms
522 @see CTransaction::FetchInputs
524 bool AreInputsStandard(const MapPrevTx& mapInputs) const;
526 /** Count ECDSA signature operations the old-fashioned (pre-0.6) way
527 @return number of sigops this transaction's outputs will produce when spent
528 @see CTransaction::FetchInputs
530 unsigned int GetLegacySigOpCount() const;
532 /** Count ECDSA signature operations in pay-to-script-hash inputs.
534 @param[in] mapInputs Map of previous transactions that have outputs we're spending
535 @return maximum number of sigops required to validate this transaction's inputs
536 @see CTransaction::FetchInputs
538 unsigned int GetP2SHSigOpCount(const MapPrevTx& mapInputs) const;
540 /** Amount of bitcoins spent by this transaction.
541 @return sum of all outputs (note: does not include fees)
543 int64 GetValueOut() const
546 BOOST_FOREACH(const CTxOut& txout, vout)
548 nValueOut += txout.nValue;
549 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
550 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
555 /** Amount of bitcoins coming in to this transaction
556 Note that lightweight clients may not know anything besides the hash of previous transactions,
557 so may not be able to calculate this.
559 @param[in] mapInputs Map of previous transactions that have outputs we're spending
560 @return Sum of value of all inputs (scriptSigs)
561 @see CTransaction::FetchInputs
563 int64 GetValueIn(const MapPrevTx& mapInputs) const;
565 static bool AllowFree(double dPriority)
567 // Large (in bytes) low-priority (new, small-coin) transactions
569 return dPriority > COIN * 144 / 250;
572 int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=false, enum GetMinFee_mode mode=GMF_BLOCK) const
574 // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
575 int64 nBaseFee = (mode == GMF_RELAY) ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
577 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION);
578 unsigned int nNewBlockSize = nBlockSize + nBytes;
579 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
585 // Transactions under 10K are free
586 // (about 4500bc if made of 50bc inputs)
592 // Free transaction area
593 if (nNewBlockSize < 27000)
598 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
599 if (nMinFee < nBaseFee)
601 BOOST_FOREACH(const CTxOut& txout, vout)
602 if (txout.nValue < CENT)
606 // Raise the price as the block approaches full
607 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
609 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
611 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
614 if (!MoneyRange(nMinFee))
620 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
622 CAutoFile filein = CAutoFile(OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb"), SER_DISK, CLIENT_VERSION);
624 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
627 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
628 return error("CTransaction::ReadFromDisk() : fseek failed");
633 catch (std::exception &e) {
634 return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
637 // Return file pointer
640 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
641 return error("CTransaction::ReadFromDisk() : second fseek failed");
642 *pfileRet = filein.release();
647 friend bool operator==(const CTransaction& a, const CTransaction& b)
649 return (a.nVersion == b.nVersion &&
650 a.nTime == b.nTime &&
653 a.nLockTime == b.nLockTime);
656 friend bool operator!=(const CTransaction& a, const CTransaction& b)
662 std::string ToString() const
665 str += IsCoinBase()? "Coinbase" : (IsCoinStake()? "Coinstake" : "CTransaction");
666 str += strprintf("(hash=%s, nTime=%d, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
667 GetHash().ToString().substr(0,10).c_str(),
673 for (unsigned int i = 0; i < vin.size(); i++)
674 str += " " + vin[i].ToString() + "\n";
675 for (unsigned int i = 0; i < vout.size(); i++)
676 str += " " + vout[i].ToString() + "\n";
682 printf("%s", ToString().c_str());
686 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
687 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
688 bool ReadFromDisk(COutPoint prevout);
689 bool DisconnectInputs(CTxDB& txdb);
691 /** Fetch from memory and/or disk. inputsRet keys are transaction hashes.
693 @param[in] txdb Transaction database
694 @param[in] mapTestPool List of pending changes to the transaction index database
695 @param[in] fBlock True if being called to add a new best-block to the chain
696 @param[in] fMiner True if being called by CreateNewBlock
697 @param[out] inputsRet Pointers to this transaction's inputs
698 @param[out] fInvalid returns true if transaction is invalid
699 @return Returns true if all inputs are in txdb or mapTestPool
701 bool FetchInputs(CTxDB& txdb, const std::map<uint256, CTxIndex>& mapTestPool,
702 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid);
704 /** Sanity check previous transactions, then, if all checks succeed,
705 mark them as spent by this transaction.
707 @param[in] inputs Previous transactions (from FetchInputs)
708 @param[out] mapTestPool Keeps track of inputs that need to be updated on disk
709 @param[in] posThisTx Position of this transaction on disk
710 @param[in] pindexBlock
711 @param[in] fBlock true if called from ConnectBlock
712 @param[in] fMiner true if called from CreateNewBlock
713 @param[in] fStrictPayToScriptHash true if fully validating p2sh transactions
714 @return Returns true if all checks succeed
716 bool ConnectInputs(CTxDB& txdb, MapPrevTx inputs,
717 std::map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
718 const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash=true);
719 bool ClientConnectInputs();
720 bool CheckTransaction() const;
721 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
722 bool GetCoinAge(CTxDB& txdb, uint64& nCoinAge) const; // ppcoin: get transaction coin age
723 bool CheckProofOfStake(unsigned int nBits) const;
726 const CTxOut& GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const;
733 /** A transaction with a merkle branch linking it to the block chain. */
734 class CMerkleTx : public CTransaction
738 std::vector<uint256> vMerkleBranch;
742 mutable bool fMerkleVerified;
750 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
759 fMerkleVerified = false;
765 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
766 nVersion = this->nVersion;
767 READWRITE(hashBlock);
768 READWRITE(vMerkleBranch);
773 int SetMerkleBranch(const CBlock* pblock=NULL);
774 int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
775 int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
776 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
777 int GetBlocksToMaturity() const;
778 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
779 bool AcceptToMemoryPool();
785 /** A txdb record that contains the disk location of a transaction and the
786 * locations of transactions that spend its outputs. vSpent is really only
787 * used as a flag, but having the location is very helpful for debugging.
793 std::vector<CDiskTxPos> vSpent;
800 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
803 vSpent.resize(nOutputs);
808 if (!(nType & SER_GETHASH))
825 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
827 return (a.pos == b.pos &&
828 a.vSpent == b.vSpent);
831 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
835 int GetDepthInMainChain() const;
843 /** Nodes collect new transactions into a block, hash them into a hash tree,
844 * and scan through nonce values to make the block's hash satisfy proof-of-work
845 * requirements. When they solve the proof-of-work, they broadcast the block
846 * to everyone and the block is added to the block chain. The first transaction
847 * in the block is a special one that creates a new coin owned by the creator
850 * Blocks are appended to blk0001.dat files on disk. Their location on disk
851 * is indexed by CBlockIndex objects in memory.
858 uint256 hashPrevBlock;
859 uint256 hashMerkleRoot;
865 std::vector<CTransaction> vtx;
867 // ppcoin: block signature - signed by coin base txout[0]'s owner
868 std::vector<unsigned char> vchBlockSig;
871 mutable std::vector<uint256> vMerkleTree;
873 // Denial-of-service detection:
875 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
884 READWRITE(this->nVersion);
885 nVersion = this->nVersion;
886 READWRITE(hashPrevBlock);
887 READWRITE(hashMerkleRoot);
892 // ConnectBlock depends on vtx following header to generate CDiskTxPos
893 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
896 READWRITE(vchBlockSig);
900 const_cast<CBlock*>(this)->vtx.clear();
901 const_cast<CBlock*>(this)->vchBlockSig.clear();
924 uint256 GetHash() const
926 return Hash(BEGIN(nVersion), END(nNonce));
929 int64 GetBlockTime() const
934 void UpdateTime(const CBlockIndex* pindexPrev);
936 // ppcoin: two types of block: proof-of-work or proof-of-stake
937 bool IsProofOfStake() const
939 return (vtx.size() > 1 && vtx[1].IsCoinStake());
942 bool IsProofOfWork() const
944 return !IsProofOfStake();
947 std::pair<COutPoint, unsigned int> GetProofOfStake() const
949 return IsProofOfStake()? std::make_pair(vtx[1].vin[0].prevout, vtx[1].nTime) : std::make_pair(COutPoint(), (unsigned int)0);
952 // ppcoin: get max transaction timestamp
953 int64 GetMaxTransactionTime() const
955 int64 maxTransactionTime = 0;
956 BOOST_FOREACH(const CTransaction& tx, vtx)
957 maxTransactionTime = std::max(maxTransactionTime, (int64)tx.nTime);
958 return maxTransactionTime;
961 uint256 BuildMerkleTree() const
964 BOOST_FOREACH(const CTransaction& tx, vtx)
965 vMerkleTree.push_back(tx.GetHash());
967 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
969 for (int i = 0; i < nSize; i += 2)
971 int i2 = std::min(i+1, nSize-1);
972 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
973 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
977 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
980 std::vector<uint256> GetMerkleBranch(int nIndex) const
982 if (vMerkleTree.empty())
984 std::vector<uint256> vMerkleBranch;
986 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
988 int i = std::min(nIndex^1, nSize-1);
989 vMerkleBranch.push_back(vMerkleTree[j+i]);
993 return vMerkleBranch;
996 static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
1000 BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
1003 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
1005 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
1012 bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
1014 // Open history file to append
1015 CAutoFile fileout = CAutoFile(AppendBlockFile(nFileRet), SER_DISK, CLIENT_VERSION);
1017 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
1019 // Write index header
1020 unsigned int nSize = fileout.GetSerializeSize(*this);
1021 fileout << FLATDATA(pchMessageStart) << nSize;
1024 long fileOutPos = ftell(fileout);
1026 return error("CBlock::WriteToDisk() : ftell failed");
1027 nBlockPosRet = fileOutPos;
1030 // Flush stdio buffers and commit to disk before returning
1032 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
1035 _commit(_fileno(fileout));
1037 fsync(fileno(fileout));
1044 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
1048 // Open history file to read
1049 CAutoFile filein = CAutoFile(OpenBlockFile(nFile, nBlockPos, "rb"), SER_DISK, CLIENT_VERSION);
1051 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1052 if (!fReadTransactions)
1053 filein.nType |= SER_BLOCKHEADERONLY;
1059 catch (std::exception &e) {
1060 return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
1064 if (fReadTransactions && IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
1065 return error("CBlock::ReadFromDisk() : errors in block header");
1074 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d, vchBlockSig=%s)\n",
1075 GetHash().ToString().substr(0,20).c_str(),
1077 hashPrevBlock.ToString().substr(0,20).c_str(),
1078 hashMerkleRoot.ToString().substr(0,10).c_str(),
1079 nTime, nBits, nNonce,
1081 HexStr(vchBlockSig.begin(), vchBlockSig.end()).c_str());
1082 for (unsigned int i = 0; i < vtx.size(); i++)
1087 printf(" vMerkleTree: ");
1088 for (unsigned int i = 0; i < vMerkleTree.size(); i++)
1089 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1094 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1095 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1096 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1097 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1098 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1099 bool CheckBlock() const;
1101 bool GetCoinAge(uint64& nCoinAge) const; // ppcoin: calculate total coin age spent in block
1102 bool SignBlock(const CKeyStore& keystore);
1103 bool CheckBlockSignature() const;
1106 bool SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew);
1114 /** The block chain is a tree shaped structure starting with the
1115 * genesis block at the root, with each block potentially having multiple
1116 * candidates to be the next block. pprev and pnext link a path through the
1117 * main/longest chain. A blockindex may have multiple pprev pointing back
1118 * to it, but pnext will only point forward to the longest branch, or will
1119 * be null if the block is not part of the longest chain.
1124 const uint256* phashBlock;
1128 unsigned int nBlockPos;
1129 CBigNum bnChainTrust; // ppcoin: trust score of block chain
1131 bool fProofOfStake; // ppcoin: is the block of proof-of-stake type
1132 COutPoint prevoutStake;
1133 unsigned int nStakeTime;
1137 uint256 hashMerkleRoot;
1140 unsigned int nNonce;
1152 fProofOfStake = true;
1153 prevoutStake.SetNull();
1163 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1169 nBlockPos = nBlockPosIn;
1172 fProofOfStake = block.IsProofOfStake();
1175 prevoutStake = block.vtx[1].vin[0].prevout;
1176 nStakeTime = block.vtx[1].nTime;
1180 prevoutStake.SetNull();
1184 nVersion = block.nVersion;
1185 hashMerkleRoot = block.hashMerkleRoot;
1186 nTime = block.nTime;
1187 nBits = block.nBits;
1188 nNonce = block.nNonce;
1191 CBlock GetBlockHeader() const
1194 block.nVersion = nVersion;
1196 block.hashPrevBlock = pprev->GetBlockHash();
1197 block.hashMerkleRoot = hashMerkleRoot;
1198 block.nTime = nTime;
1199 block.nBits = nBits;
1200 block.nNonce = nNonce;
1204 uint256 GetBlockHash() const
1209 int64 GetBlockTime() const
1211 return (int64)nTime;
1214 CBigNum GetBlockTrust() const
1217 bnTarget.SetCompact(nBits);
1220 return (fProofOfStake? (CBigNum(1)<<256) / (bnTarget+1) : 1);
1223 bool IsInMainChain() const
1225 return (pnext || this == pindexBest);
1228 bool CheckIndex() const
1230 return IsProofOfWork() ? CheckProofOfWork(GetBlockHash(), nBits) : true;
1233 bool EraseBlockFromDisk()
1235 // Open history file
1236 CAutoFile fileout = CAutoFile(OpenBlockFile(nFile, nBlockPos, "rb+"), SER_DISK, CLIENT_VERSION);
1240 // Overwrite with empty null block
1248 enum { nMedianTimeSpan=11 };
1250 int64 GetMedianTimePast() const
1252 int64 pmedian[nMedianTimeSpan];
1253 int64* pbegin = &pmedian[nMedianTimeSpan];
1254 int64* pend = &pmedian[nMedianTimeSpan];
1256 const CBlockIndex* pindex = this;
1257 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1258 *(--pbegin) = pindex->GetBlockTime();
1260 std::sort(pbegin, pend);
1261 return pbegin[(pend - pbegin)/2];
1264 int64 GetMedianTime() const
1266 const CBlockIndex* pindex = this;
1267 for (int i = 0; i < nMedianTimeSpan/2; i++)
1270 return GetBlockTime();
1271 pindex = pindex->pnext;
1273 return pindex->GetMedianTimePast();
1276 bool IsProofOfWork() const
1278 return !fProofOfStake;
1281 bool IsProofOfStake() const
1283 return fProofOfStake;
1286 std::string ToString() const
1288 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, fProofOfStake=%d prevoutStake=(%s), nStakeTime=%d merkle=%s, hashBlock=%s)",
1289 pprev, pnext, nFile, nBlockPos, nHeight,
1290 fProofOfStake, prevoutStake.ToString().c_str(), nStakeTime,
1291 hashMerkleRoot.ToString().substr(0,10).c_str(),
1292 GetBlockHash().ToString().substr(0,20).c_str());
1297 printf("%s\n", ToString().c_str());
1303 /** Used to marshal pointers into hashes for db storage. */
1304 class CDiskBlockIndex : public CBlockIndex
1316 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1318 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1319 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1324 if (!(nType & SER_GETHASH))
1325 READWRITE(nVersion);
1327 READWRITE(hashNext);
1329 READWRITE(nBlockPos);
1331 READWRITE(fProofOfStake);
1334 READWRITE(prevoutStake);
1335 READWRITE(nStakeTime);
1339 const_cast<CDiskBlockIndex*>(this)->prevoutStake.SetNull();
1340 const_cast<CDiskBlockIndex*>(this)->nStakeTime = 0;
1344 READWRITE(this->nVersion);
1345 READWRITE(hashPrev);
1346 READWRITE(hashMerkleRoot);
1352 uint256 GetBlockHash() const
1355 block.nVersion = nVersion;
1356 block.hashPrevBlock = hashPrev;
1357 block.hashMerkleRoot = hashMerkleRoot;
1358 block.nTime = nTime;
1359 block.nBits = nBits;
1360 block.nNonce = nNonce;
1361 return block.GetHash();
1365 std::string ToString() const
1367 std::string str = "CDiskBlockIndex(";
1368 str += CBlockIndex::ToString();
1369 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1370 GetBlockHash().ToString().c_str(),
1371 hashPrev.ToString().substr(0,20).c_str(),
1372 hashNext.ToString().substr(0,20).c_str());
1378 printf("%s\n", ToString().c_str());
1389 /** Describes a place in the block chain to another node such that if the
1390 * other node doesn't have the same branch, it can find a recent common trunk.
1391 * The further back it is, the further before the fork it may be.
1396 std::vector<uint256> vHave;
1403 explicit CBlockLocator(const CBlockIndex* pindex)
1408 explicit CBlockLocator(uint256 hashBlock)
1410 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1411 if (mi != mapBlockIndex.end())
1415 CBlockLocator(const std::vector<uint256>& vHaveIn)
1422 if (!(nType & SER_GETHASH))
1423 READWRITE(nVersion);
1434 return vHave.empty();
1437 void Set(const CBlockIndex* pindex)
1443 vHave.push_back(pindex->GetBlockHash());
1445 // Exponentially larger steps back
1446 for (int i = 0; pindex && i < nStep; i++)
1447 pindex = pindex->pprev;
1448 if (vHave.size() > 10)
1451 vHave.push_back(hashGenesisBlock);
1454 int GetDistanceBack()
1456 // Retrace how far back it was in the sender's branch
1459 BOOST_FOREACH(const uint256& hash, vHave)
1461 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1462 if (mi != mapBlockIndex.end())
1464 CBlockIndex* pindex = (*mi).second;
1465 if (pindex->IsInMainChain())
1475 CBlockIndex* GetBlockIndex()
1477 // Find the first block the caller has in the main chain
1478 BOOST_FOREACH(const uint256& hash, vHave)
1480 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1481 if (mi != mapBlockIndex.end())
1483 CBlockIndex* pindex = (*mi).second;
1484 if (pindex->IsInMainChain())
1488 return pindexGenesisBlock;
1491 uint256 GetBlockHash()
1493 // Find the first block the caller has in the main chain
1494 BOOST_FOREACH(const uint256& hash, vHave)
1496 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1497 if (mi != mapBlockIndex.end())
1499 CBlockIndex* pindex = (*mi).second;
1500 if (pindex->IsInMainChain())
1504 return hashGenesisBlock;
1509 CBlockIndex* pindex = GetBlockIndex();
1512 return pindex->nHeight;
1524 /** Alerts are for notifying old versions if they become too obsolete and
1525 * need to upgrade. The message is displayed in the status bar.
1526 * Alert messages are broadcast as a vector of signed data. Unserializing may
1527 * not read the entire buffer if the alert is for a newer version, but older
1528 * versions can still relay the original data.
1530 class CUnsignedAlert
1534 int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
1538 std::set<int> setCancel;
1539 int nMinVer; // lowest version inclusive
1540 int nMaxVer; // highest version inclusive
1541 std::set<std::string> setSubVer; // empty matches all
1545 std::string strComment;
1546 std::string strStatusBar;
1547 std::string strReserved;
1551 READWRITE(this->nVersion);
1552 nVersion = this->nVersion;
1553 READWRITE(nRelayUntil);
1554 READWRITE(nExpiration);
1557 READWRITE(setCancel);
1560 READWRITE(setSubVer);
1561 READWRITE(nPriority);
1563 READWRITE(strComment);
1564 READWRITE(strStatusBar);
1565 READWRITE(strReserved);
1582 strStatusBar.clear();
1583 strReserved.clear();
1586 std::string ToString() const
1588 std::string strSetCancel;
1589 BOOST_FOREACH(int n, setCancel)
1590 strSetCancel += strprintf("%d ", n);
1591 std::string strSetSubVer;
1592 BOOST_FOREACH(std::string str, setSubVer)
1593 strSetSubVer += "\"" + str + "\" ";
1597 " nRelayUntil = %"PRI64d"\n"
1598 " nExpiration = %"PRI64d"\n"
1606 " strComment = \"%s\"\n"
1607 " strStatusBar = \"%s\"\n"
1614 strSetCancel.c_str(),
1617 strSetSubVer.c_str(),
1620 strStatusBar.c_str());
1625 printf("%s", ToString().c_str());
1629 /** An alert is a combination of a serialized CUnsignedAlert and a signature. */
1630 class CAlert : public CUnsignedAlert
1633 std::vector<unsigned char> vchMsg;
1634 std::vector<unsigned char> vchSig;
1649 CUnsignedAlert::SetNull();
1656 return (nExpiration == 0);
1659 uint256 GetHash() const
1661 return SerializeHash(*this);
1664 bool IsInEffect() const
1666 return (GetAdjustedTime() < nExpiration);
1669 bool Cancels(const CAlert& alert) const
1672 return false; // this was a no-op before 31403
1673 return (alert.nID <= nCancel || setCancel.count(alert.nID));
1676 bool AppliesTo(int nVersion, std::string strSubVerIn) const
1678 // TODO: rework for client-version-embedded-in-strSubVer ?
1679 return (IsInEffect() &&
1680 nMinVer <= nVersion && nVersion <= nMaxVer &&
1681 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1684 bool AppliesToMe() const
1686 return AppliesTo(PROTOCOL_VERSION, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<std::string>()));
1689 bool RelayTo(CNode* pnode) const
1693 // returns true if wasn't already contained in the set
1694 if (pnode->setKnown.insert(GetHash()).second)
1696 if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
1698 GetAdjustedTime() < nRelayUntil)
1700 pnode->PushMessage("alert", *this);
1707 bool CheckSignature()
1710 if (!key.SetPubKey(ParseHex("04a0a849dd49b113d3179a332dd77715c43be4d0076e2f19e66de23dd707e56630f792f298dfd209bf042bb3561f4af6983f3d81e439737ab0bf7f898fecd21aab")))
1711 return error("CAlert::CheckSignature() : SetPubKey failed");
1712 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
1713 return error("CAlert::CheckSignature() : verify signature failed");
1715 // Now unserialize the data
1716 CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION);
1717 sMsg >> *(CUnsignedAlert*)this;
1721 bool ProcessAlert();
1727 mutable CCriticalSection cs;
1728 std::map<uint256, CTransaction> mapTx;
1729 std::map<COutPoint, CInPoint> mapNextTx;
1731 bool accept(CTxDB& txdb, CTransaction &tx,
1732 bool fCheckInputs, bool* pfMissingInputs);
1733 bool addUnchecked(CTransaction &tx);
1734 bool remove(CTransaction &tx);
1736 unsigned long size()
1739 return mapTx.size();
1742 bool exists(uint256 hash)
1744 return (mapTx.count(hash) != 0);
1747 CTransaction& lookup(uint256 hash)
1753 extern CTxMemPool mempool;