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 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 = 100;
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("0x000000007c82d1f0aa2896b01bf533a8cc26a1f44790be4ceb4ecde7bee24add");
51 static const uint256 hashGenesisBlockTestNet("0x00000007199508e34a9ff81e6ec0c477a4cccff2a4767a8eee39c11db367b008");
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 uint64 nBestChainTrust;
67 extern uint64 nBestInvalidTrust;
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 bool Reorganize(CTxDB& txdb, CBlockIndex* pindexNew);
114 uint256 WantedByOrphan(const CBlock* pblockOrphan);
115 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake);
116 void BitcoinMiner(CWallet *pwallet, bool fProofOfStake);
128 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
130 /** Position on disk for a particular transaction. */
135 unsigned int nBlockPos;
143 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
146 nBlockPos = nBlockPosIn;
150 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
151 void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
152 bool IsNull() const { return (nFile == -1); }
154 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
156 return (a.nFile == b.nFile &&
157 a.nBlockPos == b.nBlockPos &&
158 a.nTxPos == b.nTxPos);
161 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
166 std::string ToString() const
171 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
176 printf("%s", ToString().c_str());
182 /** An inpoint - a combination of a transaction and an index n into its vin */
189 CInPoint() { SetNull(); }
190 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
191 void SetNull() { ptx = NULL; n = -1; }
192 bool IsNull() const { return (ptx == NULL && n == -1); }
197 /** An outpoint - a combination of a transaction hash and an index n into its vout */
204 COutPoint() { SetNull(); }
205 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
206 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
207 void SetNull() { hash = 0; n = -1; }
208 bool IsNull() const { return (hash == 0 && n == -1); }
210 friend bool operator<(const COutPoint& a, const COutPoint& b)
212 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
215 friend bool operator==(const COutPoint& a, const COutPoint& b)
217 return (a.hash == b.hash && a.n == b.n);
220 friend bool operator!=(const COutPoint& a, const COutPoint& b)
225 std::string ToString() const
227 return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,10).c_str(), n);
232 printf("%s\n", ToString().c_str());
239 /** An input of a transaction. It contains the location of the previous
240 * transaction's output that it claims and a signature that matches the
241 * output's public key.
248 unsigned int nSequence;
252 nSequence = std::numeric_limits<unsigned int>::max();
255 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
258 scriptSig = scriptSigIn;
259 nSequence = nSequenceIn;
262 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
264 prevout = COutPoint(hashPrevTx, nOut);
265 scriptSig = scriptSigIn;
266 nSequence = nSequenceIn;
272 READWRITE(scriptSig);
273 READWRITE(nSequence);
278 return (nSequence == std::numeric_limits<unsigned int>::max());
281 friend bool operator==(const CTxIn& a, const CTxIn& b)
283 return (a.prevout == b.prevout &&
284 a.scriptSig == b.scriptSig &&
285 a.nSequence == b.nSequence);
288 friend bool operator!=(const CTxIn& a, const CTxIn& b)
293 std::string ToString() const
297 str += prevout.ToString();
298 if (prevout.IsNull())
299 str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
301 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
302 if (nSequence != std::numeric_limits<unsigned int>::max())
303 str += strprintf(", nSequence=%u", nSequence);
310 printf("%s\n", ToString().c_str());
317 /** An output of a transaction. It contains the public key that the next input
318 * must be able to sign with to claim it.
324 CScript scriptPubKey;
331 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
334 scriptPubKey = scriptPubKeyIn;
340 READWRITE(scriptPubKey);
346 scriptPubKey.clear();
351 return (nValue == -1);
357 scriptPubKey.clear();
362 return (nValue == 0 && scriptPubKey.empty());
365 uint256 GetHash() const
367 return SerializeHash(*this);
370 friend bool operator==(const CTxOut& a, const CTxOut& b)
372 return (a.nValue == b.nValue &&
373 a.scriptPubKey == b.scriptPubKey);
376 friend bool operator!=(const CTxOut& a, const CTxOut& b)
381 std::string ToString() const
383 if (IsEmpty()) return "CTxOut(empty)";
384 if (scriptPubKey.size() < 6)
385 return "CTxOut(error)";
386 return strprintf("CTxOut(nValue=%s, scriptPubKey=%s)", FormatMoney(nValue).c_str(), scriptPubKey.ToString().substr(0,30).c_str());
391 printf("%s\n", ToString().c_str());
405 typedef std::map<uint256, std::pair<CTxIndex, CTransaction> > MapPrevTx;
407 /** The basic transaction that is broadcasted on the network and contained in
408 * blocks. A transaction can contain multiple inputs and outputs.
415 std::vector<CTxIn> vin;
416 std::vector<CTxOut> vout;
417 unsigned int nLockTime;
419 // Denial-of-service detection:
421 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
430 READWRITE(this->nVersion);
431 nVersion = this->nVersion;
435 READWRITE(nLockTime);
441 nTime = GetAdjustedTime();
445 nDoS = 0; // Denial-of-service prevention
450 return (vin.empty() && vout.empty());
453 uint256 GetHash() const
455 return SerializeHash(*this);
458 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
460 // Time based nLockTime implemented in 0.1.6
463 if (nBlockHeight == 0)
464 nBlockHeight = nBestHeight;
466 nBlockTime = GetAdjustedTime();
467 if ((int64)nLockTime < ((int64)nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
469 BOOST_FOREACH(const CTxIn& txin, vin)
475 bool IsNewerThan(const CTransaction& old) const
477 if (vin.size() != old.vin.size())
479 for (unsigned int i = 0; i < vin.size(); i++)
480 if (vin[i].prevout != old.vin[i].prevout)
484 unsigned int nLowest = std::numeric_limits<unsigned int>::max();
485 for (unsigned int i = 0; i < vin.size(); i++)
487 if (vin[i].nSequence != old.vin[i].nSequence)
489 if (vin[i].nSequence <= nLowest)
492 nLowest = vin[i].nSequence;
494 if (old.vin[i].nSequence < nLowest)
497 nLowest = old.vin[i].nSequence;
504 bool IsCoinBase() const
506 return (vin.size() == 1 && vin[0].prevout.IsNull() && vout.size() == 1);
509 bool IsCoinStake() const
511 // ppcoin: the coin stake transaction is marked with the first output empty
512 return (vin.size() > 0 && vout.size() == 2 && vout[0].IsEmpty());
515 /** Check for standard transaction types
516 @return True if all outputs (scriptPubKeys) use only standard transaction forms
518 bool IsStandard() const;
520 /** Check for standard transaction types
521 @param[in] mapInputs Map of previous transactions that have outputs we're spending
522 @return True if all inputs (scriptSigs) use only standard transaction forms
523 @see CTransaction::FetchInputs
525 bool AreInputsStandard(const MapPrevTx& mapInputs) const;
527 /** Count ECDSA signature operations the old-fashioned (pre-0.6) way
528 @return number of sigops this transaction's outputs will produce when spent
529 @see CTransaction::FetchInputs
531 unsigned int GetLegacySigOpCount() const;
533 /** Count ECDSA signature operations in pay-to-script-hash inputs.
535 @param[in] mapInputs Map of previous transactions that have outputs we're spending
536 @return maximum number of sigops required to validate this transaction's inputs
537 @see CTransaction::FetchInputs
539 unsigned int GetP2SHSigOpCount(const MapPrevTx& mapInputs) const;
541 /** Amount of bitcoins spent by this transaction.
542 @return sum of all outputs (note: does not include fees)
544 int64 GetValueOut() const
547 BOOST_FOREACH(const CTxOut& txout, vout)
549 nValueOut += txout.nValue;
550 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
551 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
556 /** Amount of bitcoins coming in to this transaction
557 Note that lightweight clients may not know anything besides the hash of previous transactions,
558 so may not be able to calculate this.
560 @param[in] mapInputs Map of previous transactions that have outputs we're spending
561 @return Sum of value of all inputs (scriptSigs)
562 @see CTransaction::FetchInputs
564 int64 GetValueIn(const MapPrevTx& mapInputs) const;
566 static bool AllowFree(double dPriority)
568 // Large (in bytes) low-priority (new, small-coin) transactions
570 return dPriority > COIN * 144 / 250;
573 int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=false, enum GetMinFee_mode mode=GMF_BLOCK) const
575 // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
576 int64 nBaseFee = (mode == GMF_RELAY) ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
578 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION);
579 unsigned int nNewBlockSize = nBlockSize + nBytes;
580 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
586 // Transactions under 10K are free
587 // (about 4500bc if made of 50bc inputs)
593 // Free transaction area
594 if (nNewBlockSize < 27000)
599 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
600 if (nMinFee < nBaseFee)
602 BOOST_FOREACH(const CTxOut& txout, vout)
603 if (txout.nValue < CENT)
607 // Raise the price as the block approaches full
608 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
610 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
612 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
615 if (!MoneyRange(nMinFee))
621 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
623 CAutoFile filein = CAutoFile(OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb"), SER_DISK, CLIENT_VERSION);
625 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
628 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
629 return error("CTransaction::ReadFromDisk() : fseek failed");
634 catch (std::exception &e) {
635 return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
638 // Return file pointer
641 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
642 return error("CTransaction::ReadFromDisk() : second fseek failed");
643 *pfileRet = filein.release();
648 friend bool operator==(const CTransaction& a, const CTransaction& b)
650 return (a.nVersion == b.nVersion &&
651 a.nTime == b.nTime &&
654 a.nLockTime == b.nLockTime);
657 friend bool operator!=(const CTransaction& a, const CTransaction& b)
663 std::string ToString() const
666 str += IsCoinBase()? "Coinbase" : (IsCoinStake()? "Coinstake" : "CTransaction");
667 str += strprintf("(hash=%s, nTime=%d, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
668 GetHash().ToString().substr(0,10).c_str(),
674 for (unsigned int i = 0; i < vin.size(); i++)
675 str += " " + vin[i].ToString() + "\n";
676 for (unsigned int i = 0; i < vout.size(); i++)
677 str += " " + vout[i].ToString() + "\n";
683 printf("%s", ToString().c_str());
687 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
688 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
689 bool ReadFromDisk(COutPoint prevout);
690 bool DisconnectInputs(CTxDB& txdb);
692 /** Fetch from memory and/or disk. inputsRet keys are transaction hashes.
694 @param[in] txdb Transaction database
695 @param[in] mapTestPool List of pending changes to the transaction index database
696 @param[in] fBlock True if being called to add a new best-block to the chain
697 @param[in] fMiner True if being called by CreateNewBlock
698 @param[out] inputsRet Pointers to this transaction's inputs
699 @param[out] fInvalid returns true if transaction is invalid
700 @return Returns true if all inputs are in txdb or mapTestPool
702 bool FetchInputs(CTxDB& txdb, const std::map<uint256, CTxIndex>& mapTestPool,
703 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid);
705 /** Sanity check previous transactions, then, if all checks succeed,
706 mark them as spent by this transaction.
708 @param[in] inputs Previous transactions (from FetchInputs)
709 @param[out] mapTestPool Keeps track of inputs that need to be updated on disk
710 @param[in] posThisTx Position of this transaction on disk
711 @param[in] pindexBlock
712 @param[in] fBlock true if called from ConnectBlock
713 @param[in] fMiner true if called from CreateNewBlock
714 @param[in] fStrictPayToScriptHash true if fully validating p2sh transactions
715 @return Returns true if all checks succeed
717 bool ConnectInputs(CTxDB& txdb, MapPrevTx inputs,
718 std::map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
719 const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash=true);
720 bool ClientConnectInputs();
721 bool CheckTransaction() const;
722 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
723 bool GetCoinAge(CTxDB& txdb, uint64& nCoinAge) const; // ppcoin: get transaction coin age
724 bool CheckProofOfStake(unsigned int nBits) const;
727 const CTxOut& GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const;
734 /** A transaction with a merkle branch linking it to the block chain. */
735 class CMerkleTx : public CTransaction
739 std::vector<uint256> vMerkleBranch;
743 mutable bool fMerkleVerified;
751 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
760 fMerkleVerified = false;
766 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
767 nVersion = this->nVersion;
768 READWRITE(hashBlock);
769 READWRITE(vMerkleBranch);
774 int SetMerkleBranch(const CBlock* pblock=NULL);
775 int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
776 int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
777 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
778 int GetBlocksToMaturity() const;
779 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
780 bool AcceptToMemoryPool();
786 /** A txdb record that contains the disk location of a transaction and the
787 * locations of transactions that spend its outputs. vSpent is really only
788 * used as a flag, but having the location is very helpful for debugging.
794 std::vector<CDiskTxPos> vSpent;
801 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
804 vSpent.resize(nOutputs);
809 if (!(nType & SER_GETHASH))
826 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
828 return (a.pos == b.pos &&
829 a.vSpent == b.vSpent);
832 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
836 int GetDepthInMainChain() const;
844 /** Nodes collect new transactions into a block, hash them into a hash tree,
845 * and scan through nonce values to make the block's hash satisfy proof-of-work
846 * requirements. When they solve the proof-of-work, they broadcast the block
847 * to everyone and the block is added to the block chain. The first transaction
848 * in the block is a special one that creates a new coin owned by the creator
851 * Blocks are appended to blk0001.dat files on disk. Their location on disk
852 * is indexed by CBlockIndex objects in memory.
859 uint256 hashPrevBlock;
860 uint256 hashMerkleRoot;
866 std::vector<CTransaction> vtx;
868 // ppcoin: block signature - signed by coin base txout[0]'s owner
869 std::vector<unsigned char> vchBlockSig;
872 mutable std::vector<uint256> vMerkleTree;
874 // Denial-of-service detection:
876 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
885 READWRITE(this->nVersion);
886 nVersion = this->nVersion;
887 READWRITE(hashPrevBlock);
888 READWRITE(hashMerkleRoot);
893 // ConnectBlock depends on vtx following header to generate CDiskTxPos
894 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
897 READWRITE(vchBlockSig);
901 const_cast<CBlock*>(this)->vtx.clear();
902 const_cast<CBlock*>(this)->vchBlockSig.clear();
925 uint256 GetHash() const
927 return Hash(BEGIN(nVersion), END(nNonce));
930 int64 GetBlockTime() const
935 void UpdateTime(const CBlockIndex* pindexPrev);
937 // ppcoin: two types of block: proof-of-work or proof-of-stake
938 bool IsProofOfStake() const
940 return (vtx.size() > 1 && vtx[1].IsCoinStake());
943 bool IsProofOfWork() const
945 return !IsProofOfStake();
948 std::pair<COutPoint, unsigned int> GetProofOfStake() const
950 return IsProofOfStake()? std::make_pair(vtx[1].vin[0].prevout, vtx[1].nTime) : std::make_pair(COutPoint(), (unsigned int)0);
953 // ppcoin: get max transaction timestamp
954 int64 GetMaxTransactionTime() const
956 int64 maxTransactionTime = 0;
957 BOOST_FOREACH(const CTransaction& tx, vtx)
958 maxTransactionTime = std::max(maxTransactionTime, (int64)tx.nTime);
959 return maxTransactionTime;
962 uint256 BuildMerkleTree() const
965 BOOST_FOREACH(const CTransaction& tx, vtx)
966 vMerkleTree.push_back(tx.GetHash());
968 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
970 for (int i = 0; i < nSize; i += 2)
972 int i2 = std::min(i+1, nSize-1);
973 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
974 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
978 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
981 std::vector<uint256> GetMerkleBranch(int nIndex) const
983 if (vMerkleTree.empty())
985 std::vector<uint256> vMerkleBranch;
987 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
989 int i = std::min(nIndex^1, nSize-1);
990 vMerkleBranch.push_back(vMerkleTree[j+i]);
994 return vMerkleBranch;
997 static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
1001 BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
1004 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
1006 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
1013 bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
1015 // Open history file to append
1016 CAutoFile fileout = CAutoFile(AppendBlockFile(nFileRet), SER_DISK, CLIENT_VERSION);
1018 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
1020 // Write index header
1021 unsigned int nSize = fileout.GetSerializeSize(*this);
1022 fileout << FLATDATA(pchMessageStart) << nSize;
1025 long fileOutPos = ftell(fileout);
1027 return error("CBlock::WriteToDisk() : ftell failed");
1028 nBlockPosRet = fileOutPos;
1031 // Flush stdio buffers and commit to disk before returning
1033 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
1036 _commit(_fileno(fileout));
1038 fsync(fileno(fileout));
1045 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
1049 // Open history file to read
1050 CAutoFile filein = CAutoFile(OpenBlockFile(nFile, nBlockPos, "rb"), SER_DISK, CLIENT_VERSION);
1052 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1053 if (!fReadTransactions)
1054 filein.nType |= SER_BLOCKHEADERONLY;
1060 catch (std::exception &e) {
1061 return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
1065 if (fReadTransactions && IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
1066 return error("CBlock::ReadFromDisk() : errors in block header");
1075 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d, vchBlockSig=%s)\n",
1076 GetHash().ToString().substr(0,20).c_str(),
1078 hashPrevBlock.ToString().substr(0,20).c_str(),
1079 hashMerkleRoot.ToString().substr(0,10).c_str(),
1080 nTime, nBits, nNonce,
1082 HexStr(vchBlockSig.begin(), vchBlockSig.end()).c_str());
1083 for (unsigned int i = 0; i < vtx.size(); i++)
1088 printf(" vMerkleTree: ");
1089 for (unsigned int i = 0; i < vMerkleTree.size(); i++)
1090 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1095 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1096 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1097 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1098 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1099 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1100 bool CheckBlock() const;
1102 bool GetCoinAge(uint64& nCoinAge) const; // ppcoin: calculate total coin age spent in block
1103 bool SignBlock(const CKeyStore& keystore);
1104 bool CheckBlockSignature() const;
1107 bool SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew);
1115 /** The block chain is a tree shaped structure starting with the
1116 * genesis block at the root, with each block potentially having multiple
1117 * candidates to be the next block. pprev and pnext link a path through the
1118 * main/longest chain. A blockindex may have multiple pprev pointing back
1119 * to it, but pnext will only point forward to the longest branch, or will
1120 * be null if the block is not part of the longest chain.
1125 const uint256* phashBlock;
1129 unsigned int nBlockPos;
1130 uint64 nChainTrust;// ppcoin: trust score of chain, in the unit of coin-days
1132 bool fProofOfStake; // ppcoin: is the block of proof-of-stake type
1133 COutPoint prevoutStake;
1134 unsigned int nStakeTime;
1138 uint256 hashMerkleRoot;
1141 unsigned int nNonce;
1153 fProofOfStake = true;
1154 prevoutStake.SetNull();
1164 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1170 nBlockPos = nBlockPosIn;
1173 fProofOfStake = block.IsProofOfStake();
1176 prevoutStake = block.vtx[1].vin[0].prevout;
1177 nStakeTime = block.vtx[1].nTime;
1181 prevoutStake.SetNull();
1185 nVersion = block.nVersion;
1186 hashMerkleRoot = block.hashMerkleRoot;
1187 nTime = block.nTime;
1188 nBits = block.nBits;
1189 nNonce = block.nNonce;
1192 CBlock GetBlockHeader() const
1195 block.nVersion = nVersion;
1197 block.hashPrevBlock = pprev->GetBlockHash();
1198 block.hashMerkleRoot = hashMerkleRoot;
1199 block.nTime = nTime;
1200 block.nBits = nBits;
1201 block.nNonce = nNonce;
1205 uint256 GetBlockHash() const
1210 int64 GetBlockTime() const
1212 return (int64)nTime;
1215 int64 GetBlockTrust() const
1217 return (nChainTrust - (pprev? pprev->nChainTrust : 0));
1220 bool IsInMainChain() const
1222 return (pnext || this == pindexBest);
1225 bool CheckIndex() const
1227 return IsProofOfWork() ? CheckProofOfWork(GetBlockHash(), nBits) : true;
1230 bool EraseBlockFromDisk()
1232 // Open history file
1233 CAutoFile fileout = CAutoFile(OpenBlockFile(nFile, nBlockPos, "rb+"), SER_DISK, CLIENT_VERSION);
1237 // Overwrite with empty null block
1245 enum { nMedianTimeSpan=11 };
1247 int64 GetMedianTimePast() const
1249 int64 pmedian[nMedianTimeSpan];
1250 int64* pbegin = &pmedian[nMedianTimeSpan];
1251 int64* pend = &pmedian[nMedianTimeSpan];
1253 const CBlockIndex* pindex = this;
1254 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1255 *(--pbegin) = pindex->GetBlockTime();
1257 std::sort(pbegin, pend);
1258 return pbegin[(pend - pbegin)/2];
1261 int64 GetMedianTime() const
1263 const CBlockIndex* pindex = this;
1264 for (int i = 0; i < nMedianTimeSpan/2; i++)
1267 return GetBlockTime();
1268 pindex = pindex->pnext;
1270 return pindex->GetMedianTimePast();
1273 bool IsProofOfWork() const
1275 return !fProofOfStake;
1278 bool IsProofOfStake() const
1280 return fProofOfStake;
1283 std::string ToString() const
1285 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)",
1286 pprev, pnext, nFile, nBlockPos, nChainTrust, nHeight,
1287 fProofOfStake, prevoutStake.ToString().c_str(), nStakeTime,
1288 hashMerkleRoot.ToString().substr(0,10).c_str(),
1289 GetBlockHash().ToString().substr(0,20).c_str());
1294 printf("%s\n", ToString().c_str());
1300 /** Used to marshal pointers into hashes for db storage. */
1301 class CDiskBlockIndex : public CBlockIndex
1313 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1315 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1316 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1321 if (!(nType & SER_GETHASH))
1322 READWRITE(nVersion);
1324 READWRITE(hashNext);
1326 READWRITE(nBlockPos);
1327 READWRITE(nChainTrust);
1329 READWRITE(fProofOfStake);
1332 READWRITE(prevoutStake);
1333 READWRITE(nStakeTime);
1337 const_cast<CDiskBlockIndex*>(this)->prevoutStake.SetNull();
1338 const_cast<CDiskBlockIndex*>(this)->nStakeTime = 0;
1342 READWRITE(this->nVersion);
1343 READWRITE(hashPrev);
1344 READWRITE(hashMerkleRoot);
1350 uint256 GetBlockHash() const
1353 block.nVersion = nVersion;
1354 block.hashPrevBlock = hashPrev;
1355 block.hashMerkleRoot = hashMerkleRoot;
1356 block.nTime = nTime;
1357 block.nBits = nBits;
1358 block.nNonce = nNonce;
1359 return block.GetHash();
1363 std::string ToString() const
1365 std::string str = "CDiskBlockIndex(";
1366 str += CBlockIndex::ToString();
1367 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1368 GetBlockHash().ToString().c_str(),
1369 hashPrev.ToString().substr(0,20).c_str(),
1370 hashNext.ToString().substr(0,20).c_str());
1376 printf("%s\n", ToString().c_str());
1387 /** Describes a place in the block chain to another node such that if the
1388 * other node doesn't have the same branch, it can find a recent common trunk.
1389 * The further back it is, the further before the fork it may be.
1394 std::vector<uint256> vHave;
1401 explicit CBlockLocator(const CBlockIndex* pindex)
1406 explicit CBlockLocator(uint256 hashBlock)
1408 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1409 if (mi != mapBlockIndex.end())
1413 CBlockLocator(const std::vector<uint256>& vHaveIn)
1420 if (!(nType & SER_GETHASH))
1421 READWRITE(nVersion);
1432 return vHave.empty();
1435 void Set(const CBlockIndex* pindex)
1441 vHave.push_back(pindex->GetBlockHash());
1443 // Exponentially larger steps back
1444 for (int i = 0; pindex && i < nStep; i++)
1445 pindex = pindex->pprev;
1446 if (vHave.size() > 10)
1449 vHave.push_back(hashGenesisBlock);
1452 int GetDistanceBack()
1454 // Retrace how far back it was in the sender's branch
1457 BOOST_FOREACH(const uint256& hash, vHave)
1459 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1460 if (mi != mapBlockIndex.end())
1462 CBlockIndex* pindex = (*mi).second;
1463 if (pindex->IsInMainChain())
1473 CBlockIndex* GetBlockIndex()
1475 // Find the first block the caller has in the main chain
1476 BOOST_FOREACH(const uint256& hash, vHave)
1478 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1479 if (mi != mapBlockIndex.end())
1481 CBlockIndex* pindex = (*mi).second;
1482 if (pindex->IsInMainChain())
1486 return pindexGenesisBlock;
1489 uint256 GetBlockHash()
1491 // Find the first block the caller has in the main chain
1492 BOOST_FOREACH(const uint256& hash, vHave)
1494 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1495 if (mi != mapBlockIndex.end())
1497 CBlockIndex* pindex = (*mi).second;
1498 if (pindex->IsInMainChain())
1502 return hashGenesisBlock;
1507 CBlockIndex* pindex = GetBlockIndex();
1510 return pindex->nHeight;
1522 /** Alerts are for notifying old versions if they become too obsolete and
1523 * need to upgrade. The message is displayed in the status bar.
1524 * Alert messages are broadcast as a vector of signed data. Unserializing may
1525 * not read the entire buffer if the alert is for a newer version, but older
1526 * versions can still relay the original data.
1528 class CUnsignedAlert
1532 int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
1536 std::set<int> setCancel;
1537 int nMinVer; // lowest version inclusive
1538 int nMaxVer; // highest version inclusive
1539 std::set<std::string> setSubVer; // empty matches all
1543 std::string strComment;
1544 std::string strStatusBar;
1545 std::string strReserved;
1549 READWRITE(this->nVersion);
1550 nVersion = this->nVersion;
1551 READWRITE(nRelayUntil);
1552 READWRITE(nExpiration);
1555 READWRITE(setCancel);
1558 READWRITE(setSubVer);
1559 READWRITE(nPriority);
1561 READWRITE(strComment);
1562 READWRITE(strStatusBar);
1563 READWRITE(strReserved);
1580 strStatusBar.clear();
1581 strReserved.clear();
1584 std::string ToString() const
1586 std::string strSetCancel;
1587 BOOST_FOREACH(int n, setCancel)
1588 strSetCancel += strprintf("%d ", n);
1589 std::string strSetSubVer;
1590 BOOST_FOREACH(std::string str, setSubVer)
1591 strSetSubVer += "\"" + str + "\" ";
1595 " nRelayUntil = %"PRI64d"\n"
1596 " nExpiration = %"PRI64d"\n"
1604 " strComment = \"%s\"\n"
1605 " strStatusBar = \"%s\"\n"
1612 strSetCancel.c_str(),
1615 strSetSubVer.c_str(),
1618 strStatusBar.c_str());
1623 printf("%s", ToString().c_str());
1627 /** An alert is a combination of a serialized CUnsignedAlert and a signature. */
1628 class CAlert : public CUnsignedAlert
1631 std::vector<unsigned char> vchMsg;
1632 std::vector<unsigned char> vchSig;
1647 CUnsignedAlert::SetNull();
1654 return (nExpiration == 0);
1657 uint256 GetHash() const
1659 return SerializeHash(*this);
1662 bool IsInEffect() const
1664 return (GetAdjustedTime() < nExpiration);
1667 bool Cancels(const CAlert& alert) const
1670 return false; // this was a no-op before 31403
1671 return (alert.nID <= nCancel || setCancel.count(alert.nID));
1674 bool AppliesTo(int nVersion, std::string strSubVerIn) const
1676 // TODO: rework for client-version-embedded-in-strSubVer ?
1677 return (IsInEffect() &&
1678 nMinVer <= nVersion && nVersion <= nMaxVer &&
1679 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1682 bool AppliesToMe() const
1684 return AppliesTo(PROTOCOL_VERSION, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<std::string>()));
1687 bool RelayTo(CNode* pnode) const
1691 // returns true if wasn't already contained in the set
1692 if (pnode->setKnown.insert(GetHash()).second)
1694 if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
1696 GetAdjustedTime() < nRelayUntil)
1698 pnode->PushMessage("alert", *this);
1705 bool CheckSignature()
1708 if (!key.SetPubKey(ParseHex("0487ca85b6ae9d311f996c7616d20d0c88a5b4f07d25e78f419019f35cce6522acf978b2d99f0e7a58db1f120439e5c1889266927854aa57c93956c2569188a539")))
1709 return error("CAlert::CheckSignature() : SetPubKey failed");
1710 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
1711 return error("CAlert::CheckSignature() : verify signature failed");
1713 // Now unserialize the data
1714 CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION);
1715 sMsg >> *(CUnsignedAlert*)this;
1719 bool ProcessAlert();
1725 mutable CCriticalSection cs;
1726 std::map<uint256, CTransaction> mapTx;
1727 std::map<COutPoint, CInPoint> mapNextTx;
1729 bool accept(CTxDB& txdb, CTransaction &tx,
1730 bool fCheckInputs, bool* pfMissingInputs);
1731 bool addUnchecked(CTransaction &tx);
1732 bool remove(CTransaction &tx);
1734 unsigned long size()
1737 return mapTx.size();
1740 bool exists(uint256 hash)
1742 return (mapTx.count(hash) != 0);
1745 CTransaction& lookup(uint256 hash)
1751 extern CTxMemPool mempool;