1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Copyright (c) 2011-2012 The PPCoin developers
4 // Distributed under the MIT/X11 software license, see the accompanying
5 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
14 #include <io.h> /* for _commit */
28 class CRequestTracker;
31 static const unsigned int MAX_BLOCK_SIZE = 1000000;
32 static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/2;
33 static const unsigned int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
34 static const unsigned int MAX_ORPHAN_TRANSACTIONS = MAX_BLOCK_SIZE/100;
35 static const int64 MIN_TX_FEE = 10000;
36 static const int64 MIN_RELAY_TX_FEE = 10000;
37 static const int64 MAX_MONEY = 2000000000 * COIN;
38 inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
39 static const int COINBASE_MATURITY = 100;
40 // Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp.
41 static const int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC
43 static const int fHaveUPnP = true;
45 static const int fHaveUPnP = false;
48 static const uint256 hashGenesisBlockOfficial("0x000000007c82d1f0aa2896b01bf533a8cc26a1f44790be4ceb4ecde7bee24add");
49 static const uint256 hashGenesisBlockTestNet("0x00000007199508e34a9ff81e6ec0c477a4cccff2a4767a8eee39c11db367b008");
51 extern CScript COINBASE_FLAGS;
58 extern CCriticalSection cs_main;
59 extern std::map<uint256, CBlockIndex*> mapBlockIndex;
60 extern std::set<std::pair<COutPoint, unsigned int> > setStakeSeen;
61 extern uint256 hashGenesisBlock;
62 extern CBlockIndex* pindexGenesisBlock;
63 extern int nBestHeight;
64 extern uint64 nBestChainTrust;
65 extern uint64 nBestInvalidTrust;
66 extern uint256 hashBestChain;
67 extern CBlockIndex* pindexBest;
68 extern unsigned int nTransactionsUpdated;
69 extern uint64 nLastBlockTx;
70 extern uint64 nLastBlockSize;
71 extern const std::string strMessageMagic;
72 extern double dHashesPerSec;
73 extern int64 nHPSTimerStart;
74 extern int64 nTimeBestReceived;
75 extern CCriticalSection cs_setpwalletRegistered;
76 extern std::set<CWallet*> setpwalletRegistered;
77 extern std::map<uint256, CBlock*> mapOrphanBlocks;
80 extern int64 nTransactionFee;
81 extern int64 nBalanceReserve;
91 void RegisterWallet(CWallet* pwalletIn);
92 void UnregisterWallet(CWallet* pwalletIn);
93 bool ProcessBlock(CNode* pfrom, CBlock* pblock);
94 bool CheckDiskSpace(uint64 nAdditionalBytes=0);
95 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
96 FILE* AppendBlockFile(unsigned int& nFileRet);
97 bool LoadBlockIndex(bool fAllowNew=true);
98 void PrintBlockTree();
99 bool ProcessMessages(CNode* pfrom);
100 bool SendMessages(CNode* pto, bool fSendTrickle);
101 void GenerateBitcoins(bool fGenerate, CWallet* pwallet);
102 CBlock* CreateNewBlock(CWallet* pwallet, bool fProofOfWorkOnly=false);
103 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce);
104 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
105 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey);
106 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
107 int64 GetProofOfStakeReward(int64 nCoinAge);
108 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime);
109 int GetNumBlocksOfPeers();
110 bool IsInitialBlockDownload();
111 std::string GetWarnings(std::string strFor);
112 bool Reorganize(CTxDB& txdb, CBlockIndex* pindexNew);
113 uint256 WantedByOrphan(const CBlock* pblockOrphan);
114 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake);
126 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
128 /** Position on disk for a particular transaction. */
133 unsigned int nBlockPos;
141 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
144 nBlockPos = nBlockPosIn;
148 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
149 void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
150 bool IsNull() const { return (nFile == -1); }
152 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
154 return (a.nFile == b.nFile &&
155 a.nBlockPos == b.nBlockPos &&
156 a.nTxPos == b.nTxPos);
159 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
164 std::string ToString() const
169 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
174 printf("%s", ToString().c_str());
180 /** An inpoint - a combination of a transaction and an index n into its vin */
187 CInPoint() { SetNull(); }
188 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
189 void SetNull() { ptx = NULL; n = -1; }
190 bool IsNull() const { return (ptx == NULL && n == -1); }
195 /** An outpoint - a combination of a transaction hash and an index n into its vout */
202 COutPoint() { SetNull(); }
203 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
204 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
205 void SetNull() { hash = 0; n = -1; }
206 bool IsNull() const { return (hash == 0 && n == -1); }
208 friend bool operator<(const COutPoint& a, const COutPoint& b)
210 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
213 friend bool operator==(const COutPoint& a, const COutPoint& b)
215 return (a.hash == b.hash && a.n == b.n);
218 friend bool operator!=(const COutPoint& a, const COutPoint& b)
223 std::string ToString() const
225 return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,10).c_str(), n);
230 printf("%s\n", ToString().c_str());
237 /** An input of a transaction. It contains the location of the previous
238 * transaction's output that it claims and a signature that matches the
239 * output's public key.
246 unsigned int nSequence;
250 nSequence = std::numeric_limits<unsigned int>::max();
253 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
256 scriptSig = scriptSigIn;
257 nSequence = nSequenceIn;
260 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
262 prevout = COutPoint(hashPrevTx, nOut);
263 scriptSig = scriptSigIn;
264 nSequence = nSequenceIn;
270 READWRITE(scriptSig);
271 READWRITE(nSequence);
276 return (nSequence == std::numeric_limits<unsigned int>::max());
279 friend bool operator==(const CTxIn& a, const CTxIn& b)
281 return (a.prevout == b.prevout &&
282 a.scriptSig == b.scriptSig &&
283 a.nSequence == b.nSequence);
286 friend bool operator!=(const CTxIn& a, const CTxIn& b)
291 std::string ToString() const
295 str += prevout.ToString();
296 if (prevout.IsNull())
297 str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
299 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
300 if (nSequence != std::numeric_limits<unsigned int>::max())
301 str += strprintf(", nSequence=%u", nSequence);
308 printf("%s\n", ToString().c_str());
315 /** An output of a transaction. It contains the public key that the next input
316 * must be able to sign with to claim it.
322 CScript scriptPubKey;
329 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
332 scriptPubKey = scriptPubKeyIn;
338 READWRITE(scriptPubKey);
344 scriptPubKey.clear();
349 return (nValue == -1);
355 scriptPubKey.clear();
360 return (nValue == 0 && scriptPubKey.empty());
363 uint256 GetHash() const
365 return SerializeHash(*this);
368 friend bool operator==(const CTxOut& a, const CTxOut& b)
370 return (a.nValue == b.nValue &&
371 a.scriptPubKey == b.scriptPubKey);
374 friend bool operator!=(const CTxOut& a, const CTxOut& b)
379 std::string ToString() const
381 if (IsEmpty()) return "CTxOut(empty)";
382 if (scriptPubKey.size() < 6)
383 return "CTxOut(error)";
384 return strprintf("CTxOut(nValue=%s, scriptPubKey=%s)", FormatMoney(nValue).c_str(), scriptPubKey.ToString().substr(0,30).c_str());
389 printf("%s\n", ToString().c_str());
403 typedef std::map<uint256, std::pair<CTxIndex, CTransaction> > MapPrevTx;
405 /** The basic transaction that is broadcasted on the network and contained in
406 * blocks. A transaction can contain multiple inputs and outputs.
413 std::vector<CTxIn> vin;
414 std::vector<CTxOut> vout;
415 unsigned int nLockTime;
417 // Denial-of-service detection:
419 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
428 READWRITE(this->nVersion);
429 nVersion = this->nVersion;
433 READWRITE(nLockTime);
439 nTime = GetAdjustedTime();
443 nDoS = 0; // Denial-of-service prevention
448 return (vin.empty() && vout.empty());
451 uint256 GetHash() const
453 return SerializeHash(*this);
456 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
458 // Time based nLockTime implemented in 0.1.6
461 if (nBlockHeight == 0)
462 nBlockHeight = nBestHeight;
464 nBlockTime = GetAdjustedTime();
465 if ((int64)nLockTime < ((int64)nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
467 BOOST_FOREACH(const CTxIn& txin, vin)
473 bool IsNewerThan(const CTransaction& old) const
475 if (vin.size() != old.vin.size())
477 for (unsigned int i = 0; i < vin.size(); i++)
478 if (vin[i].prevout != old.vin[i].prevout)
482 unsigned int nLowest = std::numeric_limits<unsigned int>::max();
483 for (unsigned int i = 0; i < vin.size(); i++)
485 if (vin[i].nSequence != old.vin[i].nSequence)
487 if (vin[i].nSequence <= nLowest)
490 nLowest = vin[i].nSequence;
492 if (old.vin[i].nSequence < nLowest)
495 nLowest = old.vin[i].nSequence;
502 bool IsCoinBase() const
504 return (vin.size() == 1 && vin[0].prevout.IsNull() && vout.size() == 1);
507 bool IsCoinStake() const
509 // ppcoin: the coin stake transaction is marked with the first output empty
510 return (vin.size() > 0 && vout.size() == 2 && vout[0].IsEmpty());
513 /** Check for standard transaction types
514 @return True if all outputs (scriptPubKeys) use only standard transaction forms
516 bool IsStandard() const;
518 /** Check for standard transaction types
519 @param[in] mapInputs Map of previous transactions that have outputs we're spending
520 @return True if all inputs (scriptSigs) use only standard transaction forms
521 @see CTransaction::FetchInputs
523 bool AreInputsStandard(const MapPrevTx& mapInputs) const;
525 /** Count ECDSA signature operations the old-fashioned (pre-0.6) way
526 @return number of sigops this transaction's outputs will produce when spent
527 @see CTransaction::FetchInputs
529 unsigned int GetLegacySigOpCount() const;
531 /** Count ECDSA signature operations in pay-to-script-hash inputs.
533 @param[in] mapInputs Map of previous transactions that have outputs we're spending
534 @return maximum number of sigops required to validate this transaction's inputs
535 @see CTransaction::FetchInputs
537 unsigned int GetP2SHSigOpCount(const MapPrevTx& mapInputs) const;
539 /** Amount of bitcoins spent by this transaction.
540 @return sum of all outputs (note: does not include fees)
542 int64 GetValueOut() const
545 BOOST_FOREACH(const CTxOut& txout, vout)
547 nValueOut += txout.nValue;
548 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
549 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
554 /** Amount of bitcoins coming in to this transaction
555 Note that lightweight clients may not know anything besides the hash of previous transactions,
556 so may not be able to calculate this.
558 @param[in] mapInputs Map of previous transactions that have outputs we're spending
559 @return Sum of value of all inputs (scriptSigs)
560 @see CTransaction::FetchInputs
562 int64 GetValueIn(const MapPrevTx& mapInputs) const;
564 static bool AllowFree(double dPriority)
566 // Large (in bytes) low-priority (new, small-coin) transactions
568 return dPriority > COIN * 144 / 250;
571 int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=false, enum GetMinFee_mode mode=GMF_BLOCK) const
573 // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
574 int64 nBaseFee = (mode == GMF_RELAY) ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
576 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION);
577 unsigned int nNewBlockSize = nBlockSize + nBytes;
578 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
584 // Transactions under 10K are free
585 // (about 4500bc if made of 50bc inputs)
591 // Free transaction area
592 if (nNewBlockSize < 27000)
597 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
598 if (nMinFee < nBaseFee)
600 BOOST_FOREACH(const CTxOut& txout, vout)
601 if (txout.nValue < CENT)
605 // Raise the price as the block approaches full
606 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
608 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
610 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
613 if (!MoneyRange(nMinFee))
619 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
621 CAutoFile filein = CAutoFile(OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb"), SER_DISK, CLIENT_VERSION);
623 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
626 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
627 return error("CTransaction::ReadFromDisk() : fseek failed");
632 catch (std::exception &e) {
633 return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
636 // Return file pointer
639 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
640 return error("CTransaction::ReadFromDisk() : second fseek failed");
641 *pfileRet = filein.release();
646 friend bool operator==(const CTransaction& a, const CTransaction& b)
648 return (a.nVersion == b.nVersion &&
649 a.nTime == b.nTime &&
652 a.nLockTime == b.nLockTime);
655 friend bool operator!=(const CTransaction& a, const CTransaction& b)
661 std::string ToString() const
664 str += IsCoinBase()? "Coinbase" : (IsCoinStake()? "Coinstake" : "CTransaction");
665 str += strprintf("(hash=%s, nTime=%d, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
666 GetHash().ToString().substr(0,10).c_str(),
672 for (unsigned int i = 0; i < vin.size(); i++)
673 str += " " + vin[i].ToString() + "\n";
674 for (unsigned int i = 0; i < vout.size(); i++)
675 str += " " + vout[i].ToString() + "\n";
681 printf("%s", ToString().c_str());
685 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
686 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
687 bool ReadFromDisk(COutPoint prevout);
688 bool DisconnectInputs(CTxDB& txdb);
690 /** Fetch from memory and/or disk. inputsRet keys are transaction hashes.
692 @param[in] txdb Transaction database
693 @param[in] mapTestPool List of pending changes to the transaction index database
694 @param[in] fBlock True if being called to add a new best-block to the chain
695 @param[in] fMiner True if being called by CreateNewBlock
696 @param[out] inputsRet Pointers to this transaction's inputs
697 @param[out] fInvalid returns true if transaction is invalid
698 @return Returns true if all inputs are in txdb or mapTestPool
700 bool FetchInputs(CTxDB& txdb, const std::map<uint256, CTxIndex>& mapTestPool,
701 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid);
703 /** Sanity check previous transactions, then, if all checks succeed,
704 mark them as spent by this transaction.
706 @param[in] inputs Previous transactions (from FetchInputs)
707 @param[out] mapTestPool Keeps track of inputs that need to be updated on disk
708 @param[in] posThisTx Position of this transaction on disk
709 @param[in] pindexBlock
710 @param[in] fBlock true if called from ConnectBlock
711 @param[in] fMiner true if called from CreateNewBlock
712 @param[in] fStrictPayToScriptHash true if fully validating p2sh transactions
713 @return Returns true if all checks succeed
715 bool ConnectInputs(CTxDB& txdb, MapPrevTx inputs,
716 std::map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
717 const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash=true);
718 bool ClientConnectInputs();
719 bool CheckTransaction() const;
720 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
721 bool GetCoinAge(CTxDB& txdb, uint64& nCoinAge) const; // ppcoin: get transaction coin age
722 bool CheckProofOfStake(unsigned int nBits) const;
725 const CTxOut& GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const;
732 /** A transaction with a merkle branch linking it to the block chain. */
733 class CMerkleTx : public CTransaction
737 std::vector<uint256> vMerkleBranch;
741 mutable bool fMerkleVerified;
749 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
758 fMerkleVerified = false;
764 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
765 nVersion = this->nVersion;
766 READWRITE(hashBlock);
767 READWRITE(vMerkleBranch);
772 int SetMerkleBranch(const CBlock* pblock=NULL);
773 int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
774 int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
775 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
776 int GetBlocksToMaturity() const;
777 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
778 bool AcceptToMemoryPool();
784 /** A txdb record that contains the disk location of a transaction and the
785 * locations of transactions that spend its outputs. vSpent is really only
786 * used as a flag, but having the location is very helpful for debugging.
792 std::vector<CDiskTxPos> vSpent;
799 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
802 vSpent.resize(nOutputs);
807 if (!(nType & SER_GETHASH))
824 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
826 return (a.pos == b.pos &&
827 a.vSpent == b.vSpent);
830 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
834 int GetDepthInMainChain() const;
842 /** Nodes collect new transactions into a block, hash them into a hash tree,
843 * and scan through nonce values to make the block's hash satisfy proof-of-work
844 * requirements. When they solve the proof-of-work, they broadcast the block
845 * to everyone and the block is added to the block chain. The first transaction
846 * in the block is a special one that creates a new coin owned by the creator
849 * Blocks are appended to blk0001.dat files on disk. Their location on disk
850 * is indexed by CBlockIndex objects in memory.
857 uint256 hashPrevBlock;
858 uint256 hashMerkleRoot;
864 std::vector<CTransaction> vtx;
866 // ppcoin: block signature - signed by coin base txout[0]'s owner
867 std::vector<unsigned char> vchBlockSig;
870 mutable std::vector<uint256> vMerkleTree;
872 // Denial-of-service detection:
874 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
883 READWRITE(this->nVersion);
884 nVersion = this->nVersion;
885 READWRITE(hashPrevBlock);
886 READWRITE(hashMerkleRoot);
891 // ConnectBlock depends on vtx following header to generate CDiskTxPos
892 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
895 READWRITE(vchBlockSig);
899 const_cast<CBlock*>(this)->vtx.clear();
900 const_cast<CBlock*>(this)->vchBlockSig.clear();
923 uint256 GetHash() const
925 return Hash(BEGIN(nVersion), END(nNonce));
928 int64 GetBlockTime() const
933 void UpdateTime(const CBlockIndex* pindexPrev);
935 // ppcoin: two types of block: proof-of-work or proof-of-stake
936 bool IsProofOfStake() const
938 return (vtx.size() > 1 && vtx[1].IsCoinStake());
941 bool IsProofOfWork() const
943 return !IsProofOfStake();
946 std::pair<COutPoint, unsigned int> GetProofOfStake() const
948 return IsProofOfStake()? std::make_pair(vtx[1].vin[0].prevout, vtx[1].nTime) : std::make_pair(COutPoint(), (unsigned int)0);
951 // ppcoin: get max transaction timestamp
952 int64 GetMaxTransactionTime() const
954 int64 maxTransactionTime = 0;
955 BOOST_FOREACH(const CTransaction& tx, vtx)
956 maxTransactionTime = std::max(maxTransactionTime, (int64)tx.nTime);
957 return maxTransactionTime;
960 uint256 BuildMerkleTree() const
963 BOOST_FOREACH(const CTransaction& tx, vtx)
964 vMerkleTree.push_back(tx.GetHash());
966 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
968 for (int i = 0; i < nSize; i += 2)
970 int i2 = std::min(i+1, nSize-1);
971 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
972 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
976 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
979 std::vector<uint256> GetMerkleBranch(int nIndex) const
981 if (vMerkleTree.empty())
983 std::vector<uint256> vMerkleBranch;
985 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
987 int i = std::min(nIndex^1, nSize-1);
988 vMerkleBranch.push_back(vMerkleTree[j+i]);
992 return vMerkleBranch;
995 static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
999 BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
1002 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
1004 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
1011 bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
1013 // Open history file to append
1014 CAutoFile fileout = CAutoFile(AppendBlockFile(nFileRet), SER_DISK, CLIENT_VERSION);
1016 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
1018 // Write index header
1019 unsigned int nSize = fileout.GetSerializeSize(*this);
1020 fileout << FLATDATA(pchMessageStart) << nSize;
1023 long fileOutPos = ftell(fileout);
1025 return error("CBlock::WriteToDisk() : ftell failed");
1026 nBlockPosRet = fileOutPos;
1029 // Flush stdio buffers and commit to disk before returning
1031 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
1034 _commit(_fileno(fileout));
1036 fsync(fileno(fileout));
1043 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
1047 // Open history file to read
1048 CAutoFile filein = CAutoFile(OpenBlockFile(nFile, nBlockPos, "rb"), SER_DISK, CLIENT_VERSION);
1050 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1051 if (!fReadTransactions)
1052 filein.nType |= SER_BLOCKHEADERONLY;
1058 catch (std::exception &e) {
1059 return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
1063 if (fReadTransactions && IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
1064 return error("CBlock::ReadFromDisk() : errors in block header");
1073 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d, vchBlockSig=%s)\n",
1074 GetHash().ToString().substr(0,20).c_str(),
1076 hashPrevBlock.ToString().substr(0,20).c_str(),
1077 hashMerkleRoot.ToString().substr(0,10).c_str(),
1078 nTime, nBits, nNonce,
1080 HexStr(vchBlockSig.begin(), vchBlockSig.end()).c_str());
1081 for (unsigned int i = 0; i < vtx.size(); i++)
1086 printf(" vMerkleTree: ");
1087 for (unsigned int i = 0; i < vMerkleTree.size(); i++)
1088 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1093 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1094 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1095 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1096 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1097 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1098 bool CheckBlock() const;
1100 bool GetCoinAge(uint64& nCoinAge) const; // ppcoin: calculate total coin age spent in block
1101 bool SignBlock(const CKeyStore& keystore);
1102 bool CheckBlockSignature() const;
1105 bool SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew);
1113 /** The block chain is a tree shaped structure starting with the
1114 * genesis block at the root, with each block potentially having multiple
1115 * candidates to be the next block. pprev and pnext link a path through the
1116 * main/longest chain. A blockindex may have multiple pprev pointing back
1117 * to it, but pnext will only point forward to the longest branch, or will
1118 * be null if the block is not part of the longest chain.
1123 const uint256* phashBlock;
1127 unsigned int nBlockPos;
1128 uint64 nChainTrust;// ppcoin: trust score of chain, in the unit of coin-days
1130 bool fProofOfStake; // ppcoin: is the block of proof-of-stake type
1131 COutPoint prevoutStake;
1132 unsigned int nStakeTime;
1136 uint256 hashMerkleRoot;
1139 unsigned int nNonce;
1151 fProofOfStake = true;
1152 prevoutStake.SetNull();
1162 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1168 nBlockPos = nBlockPosIn;
1171 fProofOfStake = block.IsProofOfStake();
1174 prevoutStake = block.vtx[1].vin[0].prevout;
1175 nStakeTime = block.vtx[1].nTime;
1179 prevoutStake.SetNull();
1183 nVersion = block.nVersion;
1184 hashMerkleRoot = block.hashMerkleRoot;
1185 nTime = block.nTime;
1186 nBits = block.nBits;
1187 nNonce = block.nNonce;
1190 CBlock GetBlockHeader() const
1193 block.nVersion = nVersion;
1195 block.hashPrevBlock = pprev->GetBlockHash();
1196 block.hashMerkleRoot = hashMerkleRoot;
1197 block.nTime = nTime;
1198 block.nBits = nBits;
1199 block.nNonce = nNonce;
1203 uint256 GetBlockHash() const
1208 int64 GetBlockTime() const
1210 return (int64)nTime;
1213 int64 GetBlockTrust() const
1215 return (nChainTrust - (pprev? pprev->nChainTrust : 0));
1218 bool IsInMainChain() const
1220 return (pnext || this == pindexBest);
1223 bool CheckIndex() const
1225 return IsProofOfWork() ? CheckProofOfWork(GetBlockHash(), nBits) : true;
1228 bool EraseBlockFromDisk()
1230 // Open history file
1231 CAutoFile fileout = CAutoFile(OpenBlockFile(nFile, nBlockPos, "rb+"), SER_DISK, CLIENT_VERSION);
1235 // Overwrite with empty null block
1243 enum { nMedianTimeSpan=11 };
1245 int64 GetMedianTimePast() const
1247 int64 pmedian[nMedianTimeSpan];
1248 int64* pbegin = &pmedian[nMedianTimeSpan];
1249 int64* pend = &pmedian[nMedianTimeSpan];
1251 const CBlockIndex* pindex = this;
1252 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1253 *(--pbegin) = pindex->GetBlockTime();
1255 std::sort(pbegin, pend);
1256 return pbegin[(pend - pbegin)/2];
1259 int64 GetMedianTime() const
1261 const CBlockIndex* pindex = this;
1262 for (int i = 0; i < nMedianTimeSpan/2; i++)
1265 return GetBlockTime();
1266 pindex = pindex->pnext;
1268 return pindex->GetMedianTimePast();
1271 bool IsProofOfWork() const
1273 return !fProofOfStake;
1276 bool IsProofOfStake() const
1278 return fProofOfStake;
1281 std::string ToString() const
1283 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nChainTrust=%"PRI64d" nHeight=%d, fProofOfStake=%d prevoutStake=(%s), nStakeTime=%d merkle=%s, hashBlock=%s)",
1284 pprev, pnext, nFile, nBlockPos, nChainTrust, nHeight,
1285 fProofOfStake, prevoutStake.ToString().c_str(), nStakeTime,
1286 hashMerkleRoot.ToString().substr(0,10).c_str(),
1287 GetBlockHash().ToString().substr(0,20).c_str());
1292 printf("%s\n", ToString().c_str());
1298 /** Used to marshal pointers into hashes for db storage. */
1299 class CDiskBlockIndex : public CBlockIndex
1311 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1313 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1314 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1319 if (!(nType & SER_GETHASH))
1320 READWRITE(nVersion);
1322 READWRITE(hashNext);
1324 READWRITE(nBlockPos);
1325 READWRITE(nChainTrust);
1327 READWRITE(fProofOfStake);
1330 READWRITE(prevoutStake);
1331 READWRITE(nStakeTime);
1335 const_cast<CDiskBlockIndex*>(this)->prevoutStake.SetNull();
1336 const_cast<CDiskBlockIndex*>(this)->nStakeTime = 0;
1340 READWRITE(this->nVersion);
1341 READWRITE(hashPrev);
1342 READWRITE(hashMerkleRoot);
1348 uint256 GetBlockHash() const
1351 block.nVersion = nVersion;
1352 block.hashPrevBlock = hashPrev;
1353 block.hashMerkleRoot = hashMerkleRoot;
1354 block.nTime = nTime;
1355 block.nBits = nBits;
1356 block.nNonce = nNonce;
1357 return block.GetHash();
1361 std::string ToString() const
1363 std::string str = "CDiskBlockIndex(";
1364 str += CBlockIndex::ToString();
1365 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1366 GetBlockHash().ToString().c_str(),
1367 hashPrev.ToString().substr(0,20).c_str(),
1368 hashNext.ToString().substr(0,20).c_str());
1374 printf("%s\n", ToString().c_str());
1385 /** Describes a place in the block chain to another node such that if the
1386 * other node doesn't have the same branch, it can find a recent common trunk.
1387 * The further back it is, the further before the fork it may be.
1392 std::vector<uint256> vHave;
1399 explicit CBlockLocator(const CBlockIndex* pindex)
1404 explicit CBlockLocator(uint256 hashBlock)
1406 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1407 if (mi != mapBlockIndex.end())
1411 CBlockLocator(const std::vector<uint256>& vHaveIn)
1418 if (!(nType & SER_GETHASH))
1419 READWRITE(nVersion);
1430 return vHave.empty();
1433 void Set(const CBlockIndex* pindex)
1439 vHave.push_back(pindex->GetBlockHash());
1441 // Exponentially larger steps back
1442 for (int i = 0; pindex && i < nStep; i++)
1443 pindex = pindex->pprev;
1444 if (vHave.size() > 10)
1447 vHave.push_back(hashGenesisBlock);
1450 int GetDistanceBack()
1452 // Retrace how far back it was in the sender's branch
1455 BOOST_FOREACH(const uint256& hash, vHave)
1457 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1458 if (mi != mapBlockIndex.end())
1460 CBlockIndex* pindex = (*mi).second;
1461 if (pindex->IsInMainChain())
1471 CBlockIndex* GetBlockIndex()
1473 // Find the first block the caller has in the main chain
1474 BOOST_FOREACH(const uint256& hash, vHave)
1476 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1477 if (mi != mapBlockIndex.end())
1479 CBlockIndex* pindex = (*mi).second;
1480 if (pindex->IsInMainChain())
1484 return pindexGenesisBlock;
1487 uint256 GetBlockHash()
1489 // Find the first block the caller has in the main chain
1490 BOOST_FOREACH(const uint256& hash, vHave)
1492 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1493 if (mi != mapBlockIndex.end())
1495 CBlockIndex* pindex = (*mi).second;
1496 if (pindex->IsInMainChain())
1500 return hashGenesisBlock;
1505 CBlockIndex* pindex = GetBlockIndex();
1508 return pindex->nHeight;
1520 /** Alerts are for notifying old versions if they become too obsolete and
1521 * need to upgrade. The message is displayed in the status bar.
1522 * Alert messages are broadcast as a vector of signed data. Unserializing may
1523 * not read the entire buffer if the alert is for a newer version, but older
1524 * versions can still relay the original data.
1526 class CUnsignedAlert
1530 int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
1534 std::set<int> setCancel;
1535 int nMinVer; // lowest version inclusive
1536 int nMaxVer; // highest version inclusive
1537 std::set<std::string> setSubVer; // empty matches all
1541 std::string strComment;
1542 std::string strStatusBar;
1543 std::string strReserved;
1547 READWRITE(this->nVersion);
1548 nVersion = this->nVersion;
1549 READWRITE(nRelayUntil);
1550 READWRITE(nExpiration);
1553 READWRITE(setCancel);
1556 READWRITE(setSubVer);
1557 READWRITE(nPriority);
1559 READWRITE(strComment);
1560 READWRITE(strStatusBar);
1561 READWRITE(strReserved);
1578 strStatusBar.clear();
1579 strReserved.clear();
1582 std::string ToString() const
1584 std::string strSetCancel;
1585 BOOST_FOREACH(int n, setCancel)
1586 strSetCancel += strprintf("%d ", n);
1587 std::string strSetSubVer;
1588 BOOST_FOREACH(std::string str, setSubVer)
1589 strSetSubVer += "\"" + str + "\" ";
1593 " nRelayUntil = %"PRI64d"\n"
1594 " nExpiration = %"PRI64d"\n"
1602 " strComment = \"%s\"\n"
1603 " strStatusBar = \"%s\"\n"
1610 strSetCancel.c_str(),
1613 strSetSubVer.c_str(),
1616 strStatusBar.c_str());
1621 printf("%s", ToString().c_str());
1625 /** An alert is a combination of a serialized CUnsignedAlert and a signature. */
1626 class CAlert : public CUnsignedAlert
1629 std::vector<unsigned char> vchMsg;
1630 std::vector<unsigned char> vchSig;
1645 CUnsignedAlert::SetNull();
1652 return (nExpiration == 0);
1655 uint256 GetHash() const
1657 return SerializeHash(*this);
1660 bool IsInEffect() const
1662 return (GetAdjustedTime() < nExpiration);
1665 bool Cancels(const CAlert& alert) const
1668 return false; // this was a no-op before 31403
1669 return (alert.nID <= nCancel || setCancel.count(alert.nID));
1672 bool AppliesTo(int nVersion, std::string strSubVerIn) const
1674 // TODO: rework for client-version-embedded-in-strSubVer ?
1675 return (IsInEffect() &&
1676 nMinVer <= nVersion && nVersion <= nMaxVer &&
1677 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1680 bool AppliesToMe() const
1682 return AppliesTo(PROTOCOL_VERSION, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<std::string>()));
1685 bool RelayTo(CNode* pnode) const
1689 // returns true if wasn't already contained in the set
1690 if (pnode->setKnown.insert(GetHash()).second)
1692 if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
1694 GetAdjustedTime() < nRelayUntil)
1696 pnode->PushMessage("alert", *this);
1703 bool CheckSignature()
1706 if (!key.SetPubKey(ParseHex("0487ca85b6ae9d311f996c7616d20d0c88a5b4f07d25e78f419019f35cce6522acf978b2d99f0e7a58db1f120439e5c1889266927854aa57c93956c2569188a539")))
1707 return error("CAlert::CheckSignature() : SetPubKey failed");
1708 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
1709 return error("CAlert::CheckSignature() : verify signature failed");
1711 // Now unserialize the data
1712 CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION);
1713 sMsg >> *(CUnsignedAlert*)this;
1717 bool ProcessAlert();
1723 mutable CCriticalSection cs;
1724 std::map<uint256, CTransaction> mapTx;
1725 std::map<COutPoint, CInPoint> mapNextTx;
1727 bool accept(CTxDB& txdb, CTransaction &tx,
1728 bool fCheckInputs, bool* pfMissingInputs);
1729 bool addUnchecked(CTransaction &tx);
1730 bool remove(CTransaction &tx);
1732 unsigned long size()
1735 return mapTx.size();
1738 bool exists(uint256 hash)
1740 return (mapTx.count(hash) != 0);
1743 CTransaction& lookup(uint256 hash)
1749 extern CTxMemPool mempool;