1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Copyright (c) 2011-2012 The PPCoin developers
4 // Copyright (c) 2012-2013 The NovaCoin developers
5 // Distributed under the MIT/X11 software license, see the accompanying
6 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
13 #include "scrypt_mine.h"
16 #include <io.h> /* for _commit */
30 class CRequestTracker;
33 static const unsigned int MAX_BLOCK_SIZE = 1000000;
34 static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/2;
35 static const unsigned int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
36 static const unsigned int MAX_ORPHAN_TRANSACTIONS = MAX_BLOCK_SIZE/100;
37 static const int64 MIN_TX_FEE = CENT;
38 static const int64 MIN_RELAY_TX_FEE = CENT;
39 static const int64 MAX_MONEY = 2000000000 * COIN;
40 static const int64 MAX_MINT_PROOF_OF_WORK = 100 * COIN;
41 static const int64 MIN_TXOUT_AMOUNT = MIN_TX_FEE;
42 inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
43 static const int COINBASE_MATURITY_PPC = 500;
44 // Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp.
45 static const int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC
47 static const int fHaveUPnP = true;
49 static const int fHaveUPnP = false;
52 static const uint256 hashGenesisBlockOfficial("0x00000a060336cbb72fe969666d337b87198b1add2abaa59cca226820b32933a4");
53 static const uint256 hashGenesisBlockTestNet("0x00000a060336cbb72fe969666d337b87198b1add2abaa59cca226820b32933a4");
55 static const int64 nMaxClockDrift = 2 * 60 * 60; // two hours
57 extern CScript COINBASE_FLAGS;
59 extern CCriticalSection cs_main;
60 extern std::map<uint256, CBlockIndex*> mapBlockIndex;
61 extern std::set<std::pair<COutPoint, unsigned int> > setStakeSeen;
62 extern uint256 hashGenesisBlock;
63 extern unsigned int nStakeMinAge;
64 extern int nCoinbaseMaturity;
65 extern CBlockIndex* pindexGenesisBlock;
66 extern int nBestHeight;
67 extern CBigNum bnBestChainTrust;
68 extern CBigNum bnBestInvalidTrust;
69 extern uint256 hashBestChain;
70 extern CBlockIndex* pindexBest;
71 extern unsigned int nTransactionsUpdated;
72 extern uint64 nLastBlockTx;
73 extern uint64 nLastBlockSize;
74 extern int64 nLastCoinStakeSearchInterval;
75 extern const std::string strMessageMagic;
76 extern double dHashesPerSec;
77 extern int64 nHPSTimerStart;
78 extern int64 nTimeBestReceived;
79 extern CCriticalSection cs_setpwalletRegistered;
80 extern std::set<CWallet*> setpwalletRegistered;
81 extern std::map<uint256, CBlock*> mapOrphanBlocks;
84 extern int64 nTransactionFee;
86 extern bool fGenerateBitcoins;
87 extern bool fLimitProcessors;
88 extern int nLimitProcessors;
94 void RegisterWallet(CWallet* pwalletIn);
95 void UnregisterWallet(CWallet* pwalletIn);
96 bool ProcessBlock(CNode* pfrom, CBlock* pblock);
97 bool CheckDiskSpace(uint64 nAdditionalBytes=0);
98 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
99 FILE* AppendBlockFile(unsigned int& nFileRet);
100 bool LoadBlockIndex(bool fAllowNew=true);
101 void PrintBlockTree();
102 bool ProcessMessages(CNode* pfrom);
103 bool SendMessages(CNode* pto, bool fSendTrickle);
104 void GenerateBitcoins(bool fGenerate, CWallet* pwallet);
105 CBlock* CreateNewBlock(CWallet* pwallet, bool fProofOfStake=false);
106 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce);
107 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
108 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey);
109 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
110 int64 GetProofOfWorkReward(unsigned int nBits);
111 int64 GetProofOfStakeReward(int64 nCoinAge);
112 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime);
113 int GetNumBlocksOfPeers();
114 bool IsInitialBlockDownload();
115 std::string GetWarnings(std::string strFor);
116 uint256 WantedByOrphan(const CBlock* pblockOrphan);
117 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake);
118 void BitcoinMiner(CWallet *pwallet, bool fProofOfStake);
130 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
132 /** Position on disk for a particular transaction. */
137 unsigned int nBlockPos;
145 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
148 nBlockPos = nBlockPosIn;
152 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
153 void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
154 bool IsNull() const { return (nFile == -1); }
156 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
158 return (a.nFile == b.nFile &&
159 a.nBlockPos == b.nBlockPos &&
160 a.nTxPos == b.nTxPos);
163 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
168 std::string ToString() const
173 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
178 printf("%s", ToString().c_str());
184 /** An inpoint - a combination of a transaction and an index n into its vin */
191 CInPoint() { SetNull(); }
192 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
193 void SetNull() { ptx = NULL; n = -1; }
194 bool IsNull() const { return (ptx == NULL && n == -1); }
199 /** An outpoint - a combination of a transaction hash and an index n into its vout */
206 COutPoint() { SetNull(); }
207 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
208 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
209 void SetNull() { hash = 0; n = -1; }
210 bool IsNull() const { return (hash == 0 && n == -1); }
212 friend bool operator<(const COutPoint& a, const COutPoint& b)
214 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
217 friend bool operator==(const COutPoint& a, const COutPoint& b)
219 return (a.hash == b.hash && a.n == b.n);
222 friend bool operator!=(const COutPoint& a, const COutPoint& b)
227 std::string ToString() const
229 return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,10).c_str(), n);
234 printf("%s\n", ToString().c_str());
241 /** An input of a transaction. It contains the location of the previous
242 * transaction's output that it claims and a signature that matches the
243 * output's public key.
250 unsigned int nSequence;
254 nSequence = std::numeric_limits<unsigned int>::max();
257 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
260 scriptSig = scriptSigIn;
261 nSequence = nSequenceIn;
264 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
266 prevout = COutPoint(hashPrevTx, nOut);
267 scriptSig = scriptSigIn;
268 nSequence = nSequenceIn;
274 READWRITE(scriptSig);
275 READWRITE(nSequence);
280 return (nSequence == std::numeric_limits<unsigned int>::max());
283 friend bool operator==(const CTxIn& a, const CTxIn& b)
285 return (a.prevout == b.prevout &&
286 a.scriptSig == b.scriptSig &&
287 a.nSequence == b.nSequence);
290 friend bool operator!=(const CTxIn& a, const CTxIn& b)
295 std::string ToStringShort() const
297 return strprintf(" %s %d", prevout.hash.ToString().c_str(), prevout.n);
300 std::string ToString() const
304 str += prevout.ToString();
305 if (prevout.IsNull())
306 str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
308 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
309 if (nSequence != std::numeric_limits<unsigned int>::max())
310 str += strprintf(", nSequence=%u", nSequence);
317 printf("%s\n", ToString().c_str());
324 /** An output of a transaction. It contains the public key that the next input
325 * must be able to sign with to claim it.
331 CScript scriptPubKey;
338 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
341 scriptPubKey = scriptPubKeyIn;
347 READWRITE(scriptPubKey);
353 scriptPubKey.clear();
358 return (nValue == -1);
364 scriptPubKey.clear();
369 return (nValue == 0 && scriptPubKey.empty());
372 uint256 GetHash() const
374 return SerializeHash(*this);
377 friend bool operator==(const CTxOut& a, const CTxOut& b)
379 return (a.nValue == b.nValue &&
380 a.scriptPubKey == b.scriptPubKey);
383 friend bool operator!=(const CTxOut& a, const CTxOut& b)
388 std::string ToStringShort() const
390 return strprintf(" out %s %s", FormatMoney(nValue).c_str(), scriptPubKey.ToString(true).c_str());
393 std::string ToString() const
395 if (IsEmpty()) return "CTxOut(empty)";
396 if (scriptPubKey.size() < 6)
397 return "CTxOut(error)";
398 return strprintf("CTxOut(nValue=%s, scriptPubKey=%s)", FormatMoney(nValue).c_str(), scriptPubKey.ToString().c_str());
403 printf("%s\n", ToString().c_str());
417 typedef std::map<uint256, std::pair<CTxIndex, CTransaction> > MapPrevTx;
419 /** The basic transaction that is broadcasted on the network and contained in
420 * blocks. A transaction can contain multiple inputs and outputs.
427 std::vector<CTxIn> vin;
428 std::vector<CTxOut> vout;
429 unsigned int nLockTime;
431 // Denial-of-service detection:
433 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
442 READWRITE(this->nVersion);
443 nVersion = this->nVersion;
447 READWRITE(nLockTime);
453 nTime = GetAdjustedTime();
457 nDoS = 0; // Denial-of-service prevention
462 return (vin.empty() && vout.empty());
465 uint256 GetHash() const
467 return SerializeHash(*this);
470 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
472 // Time based nLockTime implemented in 0.1.6
475 if (nBlockHeight == 0)
476 nBlockHeight = nBestHeight;
478 nBlockTime = GetAdjustedTime();
479 if ((int64)nLockTime < ((int64)nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
481 BOOST_FOREACH(const CTxIn& txin, vin)
487 bool IsNewerThan(const CTransaction& old) const
489 if (vin.size() != old.vin.size())
491 for (unsigned int i = 0; i < vin.size(); i++)
492 if (vin[i].prevout != old.vin[i].prevout)
496 unsigned int nLowest = std::numeric_limits<unsigned int>::max();
497 for (unsigned int i = 0; i < vin.size(); i++)
499 if (vin[i].nSequence != old.vin[i].nSequence)
501 if (vin[i].nSequence <= nLowest)
504 nLowest = vin[i].nSequence;
506 if (old.vin[i].nSequence < nLowest)
509 nLowest = old.vin[i].nSequence;
516 bool IsCoinBase() const
518 return (vin.size() == 1 && vin[0].prevout.IsNull() && vout.size() >= 1);
521 bool IsCoinStake() const
523 // ppcoin: the coin stake transaction is marked with the first output empty
524 return (vin.size() > 0 && (!vin[0].prevout.IsNull()) && vout.size() >= 2 && vout[0].IsEmpty());
527 /** Check for standard transaction types
528 @return True if all outputs (scriptPubKeys) use only standard transaction forms
530 bool IsStandard() const;
532 /** Check for standard transaction types
533 @param[in] mapInputs Map of previous transactions that have outputs we're spending
534 @return True if all inputs (scriptSigs) use only standard transaction forms
535 @see CTransaction::FetchInputs
537 bool AreInputsStandard(const MapPrevTx& mapInputs) const;
539 /** Count ECDSA signature operations the old-fashioned (pre-0.6) way
540 @return number of sigops this transaction's outputs will produce when spent
541 @see CTransaction::FetchInputs
543 unsigned int GetLegacySigOpCount() const;
545 /** Count ECDSA signature operations in pay-to-script-hash inputs.
547 @param[in] mapInputs Map of previous transactions that have outputs we're spending
548 @return maximum number of sigops required to validate this transaction's inputs
549 @see CTransaction::FetchInputs
551 unsigned int GetP2SHSigOpCount(const MapPrevTx& mapInputs) const;
553 /** Amount of bitcoins spent by this transaction.
554 @return sum of all outputs (note: does not include fees)
556 int64 GetValueOut() const
559 BOOST_FOREACH(const CTxOut& txout, vout)
561 nValueOut += txout.nValue;
562 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
563 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
568 /** Amount of bitcoins coming in to this transaction
569 Note that lightweight clients may not know anything besides the hash of previous transactions,
570 so may not be able to calculate this.
572 @param[in] mapInputs Map of previous transactions that have outputs we're spending
573 @return Sum of value of all inputs (scriptSigs)
574 @see CTransaction::FetchInputs
576 int64 GetValueIn(const MapPrevTx& mapInputs) const;
578 static bool AllowFree(double dPriority)
580 // Large (in bytes) low-priority (new, small-coin) transactions
582 return dPriority > COIN * 144 / 250;
585 int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=false, enum GetMinFee_mode mode=GMF_BLOCK) const
587 // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
588 int64 nBaseFee = (mode == GMF_RELAY) ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
590 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION);
591 unsigned int nNewBlockSize = nBlockSize + nBytes;
592 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
598 // Transactions under 10K are free
599 // (about 4500bc if made of 50bc inputs)
605 // Free transaction area
606 if (nNewBlockSize < 27000)
611 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
612 if (nMinFee < nBaseFee)
614 BOOST_FOREACH(const CTxOut& txout, vout)
615 if (txout.nValue < CENT)
619 // Raise the price as the block approaches full
620 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
622 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
624 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
627 if (!MoneyRange(nMinFee))
633 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
635 CAutoFile filein = CAutoFile(OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb"), SER_DISK, CLIENT_VERSION);
637 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
640 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
641 return error("CTransaction::ReadFromDisk() : fseek failed");
646 catch (std::exception &e) {
647 return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
650 // Return file pointer
653 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
654 return error("CTransaction::ReadFromDisk() : second fseek failed");
655 *pfileRet = filein.release();
660 friend bool operator==(const CTransaction& a, const CTransaction& b)
662 return (a.nVersion == b.nVersion &&
663 a.nTime == b.nTime &&
666 a.nLockTime == b.nLockTime);
669 friend bool operator!=(const CTransaction& a, const CTransaction& b)
675 std::string ToStringShort() const
678 str += strprintf("%s %s", GetHash().ToString().c_str(), IsCoinBase()? "base" : (IsCoinStake()? "stake" : "user"));
682 std::string ToString() const
685 str += IsCoinBase()? "Coinbase" : (IsCoinStake()? "Coinstake" : "CTransaction");
686 str += strprintf("(hash=%s, nTime=%d, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
687 GetHash().ToString().substr(0,10).c_str(),
693 for (unsigned int i = 0; i < vin.size(); i++)
694 str += " " + vin[i].ToString() + "\n";
695 for (unsigned int i = 0; i < vout.size(); i++)
696 str += " " + vout[i].ToString() + "\n";
702 printf("%s", ToString().c_str());
706 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
707 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
708 bool ReadFromDisk(COutPoint prevout);
709 bool DisconnectInputs(CTxDB& txdb);
711 /** Fetch from memory and/or disk. inputsRet keys are transaction hashes.
713 @param[in] txdb Transaction database
714 @param[in] mapTestPool List of pending changes to the transaction index database
715 @param[in] fBlock True if being called to add a new best-block to the chain
716 @param[in] fMiner True if being called by CreateNewBlock
717 @param[out] inputsRet Pointers to this transaction's inputs
718 @param[out] fInvalid returns true if transaction is invalid
719 @return Returns true if all inputs are in txdb or mapTestPool
721 bool FetchInputs(CTxDB& txdb, const std::map<uint256, CTxIndex>& mapTestPool,
722 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid);
724 /** Sanity check previous transactions, then, if all checks succeed,
725 mark them as spent by this transaction.
727 @param[in] inputs Previous transactions (from FetchInputs)
728 @param[out] mapTestPool Keeps track of inputs that need to be updated on disk
729 @param[in] posThisTx Position of this transaction on disk
730 @param[in] pindexBlock
731 @param[in] fBlock true if called from ConnectBlock
732 @param[in] fMiner true if called from CreateNewBlock
733 @param[in] fStrictPayToScriptHash true if fully validating p2sh transactions
734 @return Returns true if all checks succeed
736 bool ConnectInputs(CTxDB& txdb, MapPrevTx inputs,
737 std::map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
738 const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash=true);
739 bool ClientConnectInputs();
740 bool CheckTransaction() const;
741 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
742 bool GetCoinAge(CTxDB& txdb, uint64& nCoinAge) const; // ppcoin: get transaction coin age
743 bool CheckProofOfStake(unsigned int nBits) const;
746 const CTxOut& GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const;
753 /** A transaction with a merkle branch linking it to the block chain. */
754 class CMerkleTx : public CTransaction
758 std::vector<uint256> vMerkleBranch;
762 mutable bool fMerkleVerified;
770 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
779 fMerkleVerified = false;
785 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
786 nVersion = this->nVersion;
787 READWRITE(hashBlock);
788 READWRITE(vMerkleBranch);
793 int SetMerkleBranch(const CBlock* pblock=NULL);
794 int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
795 int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
796 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
797 int GetBlocksToMaturity() const;
798 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
799 bool AcceptToMemoryPool();
805 /** A txdb record that contains the disk location of a transaction and the
806 * locations of transactions that spend its outputs. vSpent is really only
807 * used as a flag, but having the location is very helpful for debugging.
813 std::vector<CDiskTxPos> vSpent;
820 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
823 vSpent.resize(nOutputs);
828 if (!(nType & SER_GETHASH))
845 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
847 return (a.pos == b.pos &&
848 a.vSpent == b.vSpent);
851 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
855 int GetDepthInMainChain() const;
863 /** Nodes collect new transactions into a block, hash them into a hash tree,
864 * and scan through nonce values to make the block's hash satisfy proof-of-work
865 * requirements. When they solve the proof-of-work, they broadcast the block
866 * to everyone and the block is added to the block chain. The first transaction
867 * in the block is a special one that creates a new coin owned by the creator
870 * Blocks are appended to blk0001.dat files on disk. Their location on disk
871 * is indexed by CBlockIndex objects in memory.
878 uint256 hashPrevBlock;
879 uint256 hashMerkleRoot;
885 std::vector<CTransaction> vtx;
887 // ppcoin: block signature - signed by coin base txout[0]'s owner
888 std::vector<unsigned char> vchBlockSig;
891 mutable std::vector<uint256> vMerkleTree;
893 // Denial-of-service detection:
895 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
904 READWRITE(this->nVersion);
905 nVersion = this->nVersion;
906 READWRITE(hashPrevBlock);
907 READWRITE(hashMerkleRoot);
912 // ConnectBlock depends on vtx following header to generate CDiskTxPos
913 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
916 READWRITE(vchBlockSig);
920 const_cast<CBlock*>(this)->vtx.clear();
921 const_cast<CBlock*>(this)->vchBlockSig.clear();
944 uint256 GetHash() const
947 void * scratchbuff = scrypt_buffer_alloc();
949 scrypt_hash(CVOIDBEGIN(nVersion), sizeof(block_header), UINTBEGIN(thash), scratchbuff);
951 scrypt_buffer_free(scratchbuff);
956 int64 GetBlockTime() const
961 void UpdateTime(const CBlockIndex* pindexPrev);
963 // ppcoin: two types of block: proof-of-work or proof-of-stake
964 bool IsProofOfStake() const
966 return (vtx.size() > 1 && vtx[1].IsCoinStake());
969 bool IsProofOfWork() const
971 return !IsProofOfStake();
974 std::pair<COutPoint, unsigned int> GetProofOfStake() const
976 return IsProofOfStake()? std::make_pair(vtx[1].vin[0].prevout, vtx[1].nTime) : std::make_pair(COutPoint(), (unsigned int)0);
979 // ppcoin: get max transaction timestamp
980 int64 GetMaxTransactionTime() const
982 int64 maxTransactionTime = 0;
983 BOOST_FOREACH(const CTransaction& tx, vtx)
984 maxTransactionTime = std::max(maxTransactionTime, (int64)tx.nTime);
985 return maxTransactionTime;
988 uint256 BuildMerkleTree() const
991 BOOST_FOREACH(const CTransaction& tx, vtx)
992 vMerkleTree.push_back(tx.GetHash());
994 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
996 for (int i = 0; i < nSize; i += 2)
998 int i2 = std::min(i+1, nSize-1);
999 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
1000 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
1004 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
1007 std::vector<uint256> GetMerkleBranch(int nIndex) const
1009 if (vMerkleTree.empty())
1011 std::vector<uint256> vMerkleBranch;
1013 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1015 int i = std::min(nIndex^1, nSize-1);
1016 vMerkleBranch.push_back(vMerkleTree[j+i]);
1020 return vMerkleBranch;
1023 static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
1027 BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
1030 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
1032 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
1039 bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
1041 // Open history file to append
1042 CAutoFile fileout = CAutoFile(AppendBlockFile(nFileRet), SER_DISK, CLIENT_VERSION);
1044 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
1046 // Write index header
1047 unsigned char pchMessageStart[4];
1048 GetMessageStart(pchMessageStart, true);
1049 unsigned int nSize = fileout.GetSerializeSize(*this);
1050 fileout << FLATDATA(pchMessageStart) << nSize;
1053 long fileOutPos = ftell(fileout);
1055 return error("CBlock::WriteToDisk() : ftell failed");
1056 nBlockPosRet = fileOutPos;
1059 // Flush stdio buffers and commit to disk before returning
1061 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
1064 _commit(_fileno(fileout));
1066 fsync(fileno(fileout));
1073 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
1077 // Open history file to read
1078 CAutoFile filein = CAutoFile(OpenBlockFile(nFile, nBlockPos, "rb"), SER_DISK, CLIENT_VERSION);
1080 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1081 if (!fReadTransactions)
1082 filein.nType |= SER_BLOCKHEADERONLY;
1088 catch (std::exception &e) {
1089 return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
1093 if (fReadTransactions && IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
1094 return error("CBlock::ReadFromDisk() : errors in block header");
1103 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d, vchBlockSig=%s)\n",
1104 GetHash().ToString().substr(0,20).c_str(),
1106 hashPrevBlock.ToString().substr(0,20).c_str(),
1107 hashMerkleRoot.ToString().substr(0,10).c_str(),
1108 nTime, nBits, nNonce,
1110 HexStr(vchBlockSig.begin(), vchBlockSig.end()).c_str());
1111 for (unsigned int i = 0; i < vtx.size(); i++)
1116 printf(" vMerkleTree: ");
1117 for (unsigned int i = 0; i < vMerkleTree.size(); i++)
1118 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1123 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1124 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1125 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1126 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1127 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1128 bool CheckBlock() const;
1130 bool GetCoinAge(uint64& nCoinAge) const; // ppcoin: calculate total coin age spent in block
1131 bool SignBlock(const CKeyStore& keystore);
1132 bool CheckBlockSignature() const;
1135 bool SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew);
1143 /** The block chain is a tree shaped structure starting with the
1144 * genesis block at the root, with each block potentially having multiple
1145 * candidates to be the next block. pprev and pnext link a path through the
1146 * main/longest chain. A blockindex may have multiple pprev pointing back
1147 * to it, but pnext will only point forward to the longest branch, or will
1148 * be null if the block is not part of the longest chain.
1153 const uint256* phashBlock;
1157 unsigned int nBlockPos;
1158 CBigNum bnChainTrust; // ppcoin: trust score of block chain
1162 bool fProofOfStake; // ppcoin: is the block of proof-of-stake type
1163 COutPoint prevoutStake;
1164 unsigned int nStakeTime;
1168 uint256 hashMerkleRoot;
1171 unsigned int nNonce;
1185 fProofOfStake = true;
1186 prevoutStake.SetNull();
1196 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1202 nBlockPos = nBlockPosIn;
1207 fProofOfStake = block.IsProofOfStake();
1210 prevoutStake = block.vtx[1].vin[0].prevout;
1211 nStakeTime = block.vtx[1].nTime;
1215 prevoutStake.SetNull();
1219 nVersion = block.nVersion;
1220 hashMerkleRoot = block.hashMerkleRoot;
1221 nTime = block.nTime;
1222 nBits = block.nBits;
1223 nNonce = block.nNonce;
1226 CBlock GetBlockHeader() const
1229 block.nVersion = nVersion;
1231 block.hashPrevBlock = pprev->GetBlockHash();
1232 block.hashMerkleRoot = hashMerkleRoot;
1233 block.nTime = nTime;
1234 block.nBits = nBits;
1235 block.nNonce = nNonce;
1239 uint256 GetBlockHash() const
1244 int64 GetBlockTime() const
1246 return (int64)nTime;
1249 CBigNum GetBlockTrust() const
1252 bnTarget.SetCompact(nBits);
1255 return (fProofOfStake? (CBigNum(1)<<256) / (bnTarget+1) : 1);
1258 bool IsInMainChain() const
1260 return (pnext || this == pindexBest);
1263 bool CheckIndex() const
1265 return IsProofOfWork() ? CheckProofOfWork(GetBlockHash(), nBits) : true;
1268 bool EraseBlockFromDisk()
1270 // Open history file
1271 CAutoFile fileout = CAutoFile(OpenBlockFile(nFile, nBlockPos, "rb+"), SER_DISK, CLIENT_VERSION);
1275 // Overwrite with empty null block
1283 enum { nMedianTimeSpan=11 };
1285 int64 GetMedianTimePast() const
1287 int64 pmedian[nMedianTimeSpan];
1288 int64* pbegin = &pmedian[nMedianTimeSpan];
1289 int64* pend = &pmedian[nMedianTimeSpan];
1291 const CBlockIndex* pindex = this;
1292 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1293 *(--pbegin) = pindex->GetBlockTime();
1295 std::sort(pbegin, pend);
1296 return pbegin[(pend - pbegin)/2];
1299 int64 GetMedianTime() const
1301 const CBlockIndex* pindex = this;
1302 for (int i = 0; i < nMedianTimeSpan/2; i++)
1305 return GetBlockTime();
1306 pindex = pindex->pnext;
1308 return pindex->GetMedianTimePast();
1311 bool IsProofOfWork() const
1313 return !fProofOfStake;
1316 bool IsProofOfStake() const
1318 return fProofOfStake;
1321 std::string ToString() const
1323 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)",
1324 pprev, pnext, nFile, nBlockPos, nHeight,
1325 FormatMoney(nMint).c_str(), FormatMoney(nMoneySupply).c_str(),
1326 fProofOfStake, prevoutStake.ToString().c_str(), nStakeTime,
1327 hashMerkleRoot.ToString().substr(0,10).c_str(),
1328 GetBlockHash().ToString().substr(0,20).c_str());
1333 printf("%s\n", ToString().c_str());
1339 /** Used to marshal pointers into hashes for db storage. */
1340 class CDiskBlockIndex : public CBlockIndex
1352 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1354 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1355 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1360 if (!(nType & SER_GETHASH))
1361 READWRITE(nVersion);
1363 READWRITE(hashNext);
1365 READWRITE(nBlockPos);
1368 READWRITE(nMoneySupply);
1369 READWRITE(fProofOfStake);
1372 READWRITE(prevoutStake);
1373 READWRITE(nStakeTime);
1377 const_cast<CDiskBlockIndex*>(this)->prevoutStake.SetNull();
1378 const_cast<CDiskBlockIndex*>(this)->nStakeTime = 0;
1382 READWRITE(this->nVersion);
1383 READWRITE(hashPrev);
1384 READWRITE(hashMerkleRoot);
1390 uint256 GetBlockHash() const
1393 block.nVersion = nVersion;
1394 block.hashPrevBlock = hashPrev;
1395 block.hashMerkleRoot = hashMerkleRoot;
1396 block.nTime = nTime;
1397 block.nBits = nBits;
1398 block.nNonce = nNonce;
1399 return block.GetHash();
1403 std::string ToString() const
1405 std::string str = "CDiskBlockIndex(";
1406 str += CBlockIndex::ToString();
1407 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1408 GetBlockHash().ToString().c_str(),
1409 hashPrev.ToString().substr(0,20).c_str(),
1410 hashNext.ToString().substr(0,20).c_str());
1416 printf("%s\n", ToString().c_str());
1427 /** Describes a place in the block chain to another node such that if the
1428 * other node doesn't have the same branch, it can find a recent common trunk.
1429 * The further back it is, the further before the fork it may be.
1434 std::vector<uint256> vHave;
1441 explicit CBlockLocator(const CBlockIndex* pindex)
1446 explicit CBlockLocator(uint256 hashBlock)
1448 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1449 if (mi != mapBlockIndex.end())
1453 CBlockLocator(const std::vector<uint256>& vHaveIn)
1460 if (!(nType & SER_GETHASH))
1461 READWRITE(nVersion);
1472 return vHave.empty();
1475 void Set(const CBlockIndex* pindex)
1481 vHave.push_back(pindex->GetBlockHash());
1483 // Exponentially larger steps back
1484 for (int i = 0; pindex && i < nStep; i++)
1485 pindex = pindex->pprev;
1486 if (vHave.size() > 10)
1489 vHave.push_back(hashGenesisBlock);
1492 int GetDistanceBack()
1494 // Retrace how far back it was in the sender's branch
1497 BOOST_FOREACH(const uint256& hash, vHave)
1499 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1500 if (mi != mapBlockIndex.end())
1502 CBlockIndex* pindex = (*mi).second;
1503 if (pindex->IsInMainChain())
1513 CBlockIndex* GetBlockIndex()
1515 // Find the first block the caller has in the main chain
1516 BOOST_FOREACH(const uint256& hash, vHave)
1518 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1519 if (mi != mapBlockIndex.end())
1521 CBlockIndex* pindex = (*mi).second;
1522 if (pindex->IsInMainChain())
1526 return pindexGenesisBlock;
1529 uint256 GetBlockHash()
1531 // Find the first block the caller has in the main chain
1532 BOOST_FOREACH(const uint256& hash, vHave)
1534 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1535 if (mi != mapBlockIndex.end())
1537 CBlockIndex* pindex = (*mi).second;
1538 if (pindex->IsInMainChain())
1542 return hashGenesisBlock;
1547 CBlockIndex* pindex = GetBlockIndex();
1550 return pindex->nHeight;
1562 /** Alerts are for notifying old versions if they become too obsolete and
1563 * need to upgrade. The message is displayed in the status bar.
1564 * Alert messages are broadcast as a vector of signed data. Unserializing may
1565 * not read the entire buffer if the alert is for a newer version, but older
1566 * versions can still relay the original data.
1568 class CUnsignedAlert
1572 int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
1576 std::set<int> setCancel;
1577 int nMinVer; // lowest version inclusive
1578 int nMaxVer; // highest version inclusive
1579 std::set<std::string> setSubVer; // empty matches all
1583 std::string strComment;
1584 std::string strStatusBar;
1585 std::string strReserved;
1589 READWRITE(this->nVersion);
1590 nVersion = this->nVersion;
1591 READWRITE(nRelayUntil);
1592 READWRITE(nExpiration);
1595 READWRITE(setCancel);
1598 READWRITE(setSubVer);
1599 READWRITE(nPriority);
1601 READWRITE(strComment);
1602 READWRITE(strStatusBar);
1603 READWRITE(strReserved);
1620 strStatusBar.clear();
1621 strReserved.clear();
1624 std::string ToString() const
1626 std::string strSetCancel;
1627 BOOST_FOREACH(int n, setCancel)
1628 strSetCancel += strprintf("%d ", n);
1629 std::string strSetSubVer;
1630 BOOST_FOREACH(std::string str, setSubVer)
1631 strSetSubVer += "\"" + str + "\" ";
1635 " nRelayUntil = %"PRI64d"\n"
1636 " nExpiration = %"PRI64d"\n"
1644 " strComment = \"%s\"\n"
1645 " strStatusBar = \"%s\"\n"
1652 strSetCancel.c_str(),
1655 strSetSubVer.c_str(),
1658 strStatusBar.c_str());
1663 printf("%s", ToString().c_str());
1667 /** An alert is a combination of a serialized CUnsignedAlert and a signature. */
1668 class CAlert : public CUnsignedAlert
1671 std::vector<unsigned char> vchMsg;
1672 std::vector<unsigned char> vchSig;
1687 CUnsignedAlert::SetNull();
1694 return (nExpiration == 0);
1697 uint256 GetHash() const
1699 return SerializeHash(*this);
1702 bool IsInEffect() const
1704 return (GetAdjustedTime() < nExpiration);
1707 bool Cancels(const CAlert& alert) const
1710 return false; // this was a no-op before 31403
1711 return (alert.nID <= nCancel || setCancel.count(alert.nID));
1714 bool AppliesTo(int nVersion, std::string strSubVerIn) const
1716 // TODO: rework for client-version-embedded-in-strSubVer ?
1717 return (IsInEffect() &&
1718 nMinVer <= nVersion && nVersion <= nMaxVer &&
1719 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1722 bool AppliesToMe() const
1724 return AppliesTo(PROTOCOL_VERSION, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<std::string>()));
1727 bool RelayTo(CNode* pnode) const
1731 // returns true if wasn't already contained in the set
1732 if (pnode->setKnown.insert(GetHash()).second)
1734 if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
1736 GetAdjustedTime() < nRelayUntil)
1738 pnode->PushMessage("alert", *this);
1745 bool CheckSignature()
1748 if (!key.SetPubKey(ParseHex("04a0a849dd49b113d3179a332dd77715c43be4d0076e2f19e66de23dd707e56630f792f298dfd209bf042bb3561f4af6983f3d81e439737ab0bf7f898fecd21aab")))
1749 return error("CAlert::CheckSignature() : SetPubKey failed");
1750 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
1751 return error("CAlert::CheckSignature() : verify signature failed");
1753 // Now unserialize the data
1754 CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION);
1755 sMsg >> *(CUnsignedAlert*)this;
1759 bool ProcessAlert();
1765 mutable CCriticalSection cs;
1766 std::map<uint256, CTransaction> mapTx;
1767 std::map<COutPoint, CInPoint> mapNextTx;
1769 bool accept(CTxDB& txdb, CTransaction &tx,
1770 bool fCheckInputs, bool* pfMissingInputs);
1771 bool addUnchecked(CTransaction &tx);
1772 bool remove(CTransaction &tx);
1774 unsigned long size()
1777 return mapTx.size();
1780 bool exists(uint256 hash)
1782 return (mapTx.count(hash) != 0);
1785 CTransaction& lookup(uint256 hash)
1791 extern CTxMemPool mempool;