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 && (!vin[0].prevout.IsNull()) && 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
1133 bool fProofOfStake; // ppcoin: is the block of proof-of-stake type
1134 COutPoint prevoutStake;
1135 unsigned int nStakeTime;
1139 uint256 hashMerkleRoot;
1142 unsigned int nNonce;
1156 fProofOfStake = true;
1157 prevoutStake.SetNull();
1167 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1173 nBlockPos = nBlockPosIn;
1178 fProofOfStake = block.IsProofOfStake();
1181 prevoutStake = block.vtx[1].vin[0].prevout;
1182 nStakeTime = block.vtx[1].nTime;
1186 prevoutStake.SetNull();
1190 nVersion = block.nVersion;
1191 hashMerkleRoot = block.hashMerkleRoot;
1192 nTime = block.nTime;
1193 nBits = block.nBits;
1194 nNonce = block.nNonce;
1197 CBlock GetBlockHeader() const
1200 block.nVersion = nVersion;
1202 block.hashPrevBlock = pprev->GetBlockHash();
1203 block.hashMerkleRoot = hashMerkleRoot;
1204 block.nTime = nTime;
1205 block.nBits = nBits;
1206 block.nNonce = nNonce;
1210 uint256 GetBlockHash() const
1215 int64 GetBlockTime() const
1217 return (int64)nTime;
1220 CBigNum GetBlockTrust() const
1223 bnTarget.SetCompact(nBits);
1226 return (fProofOfStake? (CBigNum(1)<<256) / (bnTarget+1) : 1);
1229 bool IsInMainChain() const
1231 return (pnext || this == pindexBest);
1234 bool CheckIndex() const
1236 return IsProofOfWork() ? CheckProofOfWork(GetBlockHash(), nBits) : true;
1239 bool EraseBlockFromDisk()
1241 // Open history file
1242 CAutoFile fileout = CAutoFile(OpenBlockFile(nFile, nBlockPos, "rb+"), SER_DISK, CLIENT_VERSION);
1246 // Overwrite with empty null block
1254 enum { nMedianTimeSpan=11 };
1256 int64 GetMedianTimePast() const
1258 int64 pmedian[nMedianTimeSpan];
1259 int64* pbegin = &pmedian[nMedianTimeSpan];
1260 int64* pend = &pmedian[nMedianTimeSpan];
1262 const CBlockIndex* pindex = this;
1263 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1264 *(--pbegin) = pindex->GetBlockTime();
1266 std::sort(pbegin, pend);
1267 return pbegin[(pend - pbegin)/2];
1270 int64 GetMedianTime() const
1272 const CBlockIndex* pindex = this;
1273 for (int i = 0; i < nMedianTimeSpan/2; i++)
1276 return GetBlockTime();
1277 pindex = pindex->pnext;
1279 return pindex->GetMedianTimePast();
1282 bool IsProofOfWork() const
1284 return !fProofOfStake;
1287 bool IsProofOfStake() const
1289 return fProofOfStake;
1292 std::string ToString() const
1294 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)",
1295 pprev, pnext, nFile, nBlockPos, nHeight,
1296 FormatMoney(nMint).c_str(), FormatMoney(nMoneySupply).c_str(),
1297 fProofOfStake, prevoutStake.ToString().c_str(), nStakeTime,
1298 hashMerkleRoot.ToString().substr(0,10).c_str(),
1299 GetBlockHash().ToString().substr(0,20).c_str());
1304 printf("%s\n", ToString().c_str());
1310 /** Used to marshal pointers into hashes for db storage. */
1311 class CDiskBlockIndex : public CBlockIndex
1323 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1325 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1326 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1331 if (!(nType & SER_GETHASH))
1332 READWRITE(nVersion);
1334 READWRITE(hashNext);
1336 READWRITE(nBlockPos);
1339 READWRITE(nMoneySupply);
1340 READWRITE(fProofOfStake);
1343 READWRITE(prevoutStake);
1344 READWRITE(nStakeTime);
1348 const_cast<CDiskBlockIndex*>(this)->prevoutStake.SetNull();
1349 const_cast<CDiskBlockIndex*>(this)->nStakeTime = 0;
1353 READWRITE(this->nVersion);
1354 READWRITE(hashPrev);
1355 READWRITE(hashMerkleRoot);
1361 uint256 GetBlockHash() const
1364 block.nVersion = nVersion;
1365 block.hashPrevBlock = hashPrev;
1366 block.hashMerkleRoot = hashMerkleRoot;
1367 block.nTime = nTime;
1368 block.nBits = nBits;
1369 block.nNonce = nNonce;
1370 return block.GetHash();
1374 std::string ToString() const
1376 std::string str = "CDiskBlockIndex(";
1377 str += CBlockIndex::ToString();
1378 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1379 GetBlockHash().ToString().c_str(),
1380 hashPrev.ToString().substr(0,20).c_str(),
1381 hashNext.ToString().substr(0,20).c_str());
1387 printf("%s\n", ToString().c_str());
1398 /** Describes a place in the block chain to another node such that if the
1399 * other node doesn't have the same branch, it can find a recent common trunk.
1400 * The further back it is, the further before the fork it may be.
1405 std::vector<uint256> vHave;
1412 explicit CBlockLocator(const CBlockIndex* pindex)
1417 explicit CBlockLocator(uint256 hashBlock)
1419 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1420 if (mi != mapBlockIndex.end())
1424 CBlockLocator(const std::vector<uint256>& vHaveIn)
1431 if (!(nType & SER_GETHASH))
1432 READWRITE(nVersion);
1443 return vHave.empty();
1446 void Set(const CBlockIndex* pindex)
1452 vHave.push_back(pindex->GetBlockHash());
1454 // Exponentially larger steps back
1455 for (int i = 0; pindex && i < nStep; i++)
1456 pindex = pindex->pprev;
1457 if (vHave.size() > 10)
1460 vHave.push_back(hashGenesisBlock);
1463 int GetDistanceBack()
1465 // Retrace how far back it was in the sender's branch
1468 BOOST_FOREACH(const uint256& hash, vHave)
1470 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1471 if (mi != mapBlockIndex.end())
1473 CBlockIndex* pindex = (*mi).second;
1474 if (pindex->IsInMainChain())
1484 CBlockIndex* GetBlockIndex()
1486 // Find the first block the caller has in the main chain
1487 BOOST_FOREACH(const uint256& hash, vHave)
1489 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1490 if (mi != mapBlockIndex.end())
1492 CBlockIndex* pindex = (*mi).second;
1493 if (pindex->IsInMainChain())
1497 return pindexGenesisBlock;
1500 uint256 GetBlockHash()
1502 // Find the first block the caller has in the main chain
1503 BOOST_FOREACH(const uint256& hash, vHave)
1505 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1506 if (mi != mapBlockIndex.end())
1508 CBlockIndex* pindex = (*mi).second;
1509 if (pindex->IsInMainChain())
1513 return hashGenesisBlock;
1518 CBlockIndex* pindex = GetBlockIndex();
1521 return pindex->nHeight;
1533 /** Alerts are for notifying old versions if they become too obsolete and
1534 * need to upgrade. The message is displayed in the status bar.
1535 * Alert messages are broadcast as a vector of signed data. Unserializing may
1536 * not read the entire buffer if the alert is for a newer version, but older
1537 * versions can still relay the original data.
1539 class CUnsignedAlert
1543 int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
1547 std::set<int> setCancel;
1548 int nMinVer; // lowest version inclusive
1549 int nMaxVer; // highest version inclusive
1550 std::set<std::string> setSubVer; // empty matches all
1554 std::string strComment;
1555 std::string strStatusBar;
1556 std::string strReserved;
1560 READWRITE(this->nVersion);
1561 nVersion = this->nVersion;
1562 READWRITE(nRelayUntil);
1563 READWRITE(nExpiration);
1566 READWRITE(setCancel);
1569 READWRITE(setSubVer);
1570 READWRITE(nPriority);
1572 READWRITE(strComment);
1573 READWRITE(strStatusBar);
1574 READWRITE(strReserved);
1591 strStatusBar.clear();
1592 strReserved.clear();
1595 std::string ToString() const
1597 std::string strSetCancel;
1598 BOOST_FOREACH(int n, setCancel)
1599 strSetCancel += strprintf("%d ", n);
1600 std::string strSetSubVer;
1601 BOOST_FOREACH(std::string str, setSubVer)
1602 strSetSubVer += "\"" + str + "\" ";
1606 " nRelayUntil = %"PRI64d"\n"
1607 " nExpiration = %"PRI64d"\n"
1615 " strComment = \"%s\"\n"
1616 " strStatusBar = \"%s\"\n"
1623 strSetCancel.c_str(),
1626 strSetSubVer.c_str(),
1629 strStatusBar.c_str());
1634 printf("%s", ToString().c_str());
1638 /** An alert is a combination of a serialized CUnsignedAlert and a signature. */
1639 class CAlert : public CUnsignedAlert
1642 std::vector<unsigned char> vchMsg;
1643 std::vector<unsigned char> vchSig;
1658 CUnsignedAlert::SetNull();
1665 return (nExpiration == 0);
1668 uint256 GetHash() const
1670 return SerializeHash(*this);
1673 bool IsInEffect() const
1675 return (GetAdjustedTime() < nExpiration);
1678 bool Cancels(const CAlert& alert) const
1681 return false; // this was a no-op before 31403
1682 return (alert.nID <= nCancel || setCancel.count(alert.nID));
1685 bool AppliesTo(int nVersion, std::string strSubVerIn) const
1687 // TODO: rework for client-version-embedded-in-strSubVer ?
1688 return (IsInEffect() &&
1689 nMinVer <= nVersion && nVersion <= nMaxVer &&
1690 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1693 bool AppliesToMe() const
1695 return AppliesTo(PROTOCOL_VERSION, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<std::string>()));
1698 bool RelayTo(CNode* pnode) const
1702 // returns true if wasn't already contained in the set
1703 if (pnode->setKnown.insert(GetHash()).second)
1705 if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
1707 GetAdjustedTime() < nRelayUntil)
1709 pnode->PushMessage("alert", *this);
1716 bool CheckSignature()
1719 if (!key.SetPubKey(ParseHex("04a0a849dd49b113d3179a332dd77715c43be4d0076e2f19e66de23dd707e56630f792f298dfd209bf042bb3561f4af6983f3d81e439737ab0bf7f898fecd21aab")))
1720 return error("CAlert::CheckSignature() : SetPubKey failed");
1721 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
1722 return error("CAlert::CheckSignature() : verify signature failed");
1724 // Now unserialize the data
1725 CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION);
1726 sMsg >> *(CUnsignedAlert*)this;
1730 bool ProcessAlert();
1736 mutable CCriticalSection cs;
1737 std::map<uint256, CTransaction> mapTx;
1738 std::map<COutPoint, CInPoint> mapNextTx;
1740 bool accept(CTxDB& txdb, CTransaction &tx,
1741 bool fCheckInputs, bool* pfMissingInputs);
1742 bool addUnchecked(CTransaction &tx);
1743 bool remove(CTransaction &tx);
1745 unsigned long size()
1748 return mapTx.size();
1751 bool exists(uint256 hash)
1753 return (mapTx.count(hash) != 0);
1756 CTransaction& lookup(uint256 hash)
1762 extern CTxMemPool mempool;