1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Copyright (c) 2011-2013 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.
12 #include "scrypt_mine.h"
15 #include <io.h> /* for _commit */
29 class CRequestTracker;
32 static const unsigned int MAX_BLOCK_SIZE = 1000000;
33 static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/2;
34 static const unsigned int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
35 static const unsigned int MAX_ORPHAN_TRANSACTIONS = MAX_BLOCK_SIZE/100;
36 static const int64 MIN_TX_FEE = CENT;
37 static const int64 MIN_RELAY_TX_FEE = CENT;
38 static const int64 MAX_MONEY = 2000000000 * COIN;
39 static const int64 MAX_MINT_PROOF_OF_WORK = 100 * COIN;
40 static const int64 MIN_TXOUT_AMOUNT = MIN_TX_FEE;
41 inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
42 static const int COINBASE_MATURITY_PPC = 500;
43 // Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp.
44 static const int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC
45 static const int STAKE_TARGET_SPACING = 10 * 60; // 10-minute block spacing
46 static const int STAKE_MIN_AGE = 60 * 60 * 24 * 30; // minimum age for coin age
47 static const int STAKE_MAX_AGE = 60 * 60 * 24 * 90; // stake age of full weight
50 static const int fHaveUPnP = true;
52 static const int fHaveUPnP = false;
55 static const uint256 hashGenesisBlockOfficial("0x00000a060336cbb72fe969666d337b87198b1add2abaa59cca226820b32933a4");
56 static const uint256 hashGenesisBlockTestNet("0x00000a060336cbb72fe969666d337b87198b1add2abaa59cca226820b32933a4");
58 static const int64 nMaxClockDrift = 2 * 60 * 60; // two hours
60 extern CScript COINBASE_FLAGS;
67 extern CCriticalSection cs_main;
68 extern std::map<uint256, CBlockIndex*> mapBlockIndex;
69 extern std::set<std::pair<COutPoint, unsigned int> > setStakeSeen;
70 extern uint256 hashGenesisBlock;
71 extern unsigned int nStakeMinAge;
72 extern int nCoinbaseMaturity;
73 extern CBlockIndex* pindexGenesisBlock;
74 extern int nBestHeight;
75 extern CBigNum bnBestChainTrust;
76 extern CBigNum bnBestInvalidTrust;
77 extern uint256 hashBestChain;
78 extern CBlockIndex* pindexBest;
79 extern unsigned int nTransactionsUpdated;
80 extern uint64 nLastBlockTx;
81 extern uint64 nLastBlockSize;
82 extern int64 nLastCoinStakeSearchInterval;
83 extern const std::string strMessageMagic;
84 extern double dHashesPerSec;
85 extern int64 nHPSTimerStart;
86 extern int64 nTimeBestReceived;
87 extern CCriticalSection cs_setpwalletRegistered;
88 extern std::set<CWallet*> setpwalletRegistered;
89 extern std::map<uint256, CBlock*> mapOrphanBlocks;
92 extern int64 nTransactionFee;
102 void RegisterWallet(CWallet* pwalletIn);
103 void UnregisterWallet(CWallet* pwalletIn);
104 bool ProcessBlock(CNode* pfrom, CBlock* pblock);
105 bool CheckDiskSpace(uint64 nAdditionalBytes=0);
106 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
107 FILE* AppendBlockFile(unsigned int& nFileRet);
108 bool LoadBlockIndex(bool fAllowNew=true);
109 void PrintBlockTree();
110 bool ProcessMessages(CNode* pfrom);
111 bool SendMessages(CNode* pto, bool fSendTrickle);
112 void GenerateBitcoins(bool fGenerate, CWallet* pwallet);
113 CBlock* CreateNewBlock(CWallet* pwallet, bool fProofOfStake=false);
114 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce);
115 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
116 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey);
117 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
118 int64 GetProofOfWorkReward(unsigned int nBits);
119 int64 GetProofOfStakeReward(int64 nCoinAge);
120 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime);
121 int GetNumBlocksOfPeers();
122 bool IsInitialBlockDownload();
123 std::string GetWarnings(std::string strFor);
124 uint256 WantedByOrphan(const CBlock* pblockOrphan);
125 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake);
126 void BitcoinMiner(CWallet *pwallet, bool fProofOfStake);
138 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
140 /** Position on disk for a particular transaction. */
145 unsigned int nBlockPos;
153 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
156 nBlockPos = nBlockPosIn;
160 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
161 void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
162 bool IsNull() const { return (nFile == -1); }
164 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
166 return (a.nFile == b.nFile &&
167 a.nBlockPos == b.nBlockPos &&
168 a.nTxPos == b.nTxPos);
171 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
176 std::string ToString() const
181 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
186 printf("%s", ToString().c_str());
192 /** An inpoint - a combination of a transaction and an index n into its vin */
199 CInPoint() { SetNull(); }
200 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
201 void SetNull() { ptx = NULL; n = -1; }
202 bool IsNull() const { return (ptx == NULL && n == -1); }
207 /** An outpoint - a combination of a transaction hash and an index n into its vout */
214 COutPoint() { SetNull(); }
215 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
216 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
217 void SetNull() { hash = 0; n = -1; }
218 bool IsNull() const { return (hash == 0 && n == -1); }
220 friend bool operator<(const COutPoint& a, const COutPoint& b)
222 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
225 friend bool operator==(const COutPoint& a, const COutPoint& b)
227 return (a.hash == b.hash && a.n == b.n);
230 friend bool operator!=(const COutPoint& a, const COutPoint& b)
235 std::string ToString() const
237 return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,10).c_str(), n);
242 printf("%s\n", ToString().c_str());
249 /** An input of a transaction. It contains the location of the previous
250 * transaction's output that it claims and a signature that matches the
251 * output's public key.
258 unsigned int nSequence;
262 nSequence = std::numeric_limits<unsigned int>::max();
265 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
268 scriptSig = scriptSigIn;
269 nSequence = nSequenceIn;
272 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
274 prevout = COutPoint(hashPrevTx, nOut);
275 scriptSig = scriptSigIn;
276 nSequence = nSequenceIn;
282 READWRITE(scriptSig);
283 READWRITE(nSequence);
288 return (nSequence == std::numeric_limits<unsigned int>::max());
291 friend bool operator==(const CTxIn& a, const CTxIn& b)
293 return (a.prevout == b.prevout &&
294 a.scriptSig == b.scriptSig &&
295 a.nSequence == b.nSequence);
298 friend bool operator!=(const CTxIn& a, const CTxIn& b)
303 std::string ToStringShort() const
305 return strprintf(" %s %d", prevout.hash.ToString().c_str(), prevout.n);
308 std::string ToString() const
312 str += prevout.ToString();
313 if (prevout.IsNull())
314 str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
316 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
317 if (nSequence != std::numeric_limits<unsigned int>::max())
318 str += strprintf(", nSequence=%u", nSequence);
325 printf("%s\n", ToString().c_str());
332 /** An output of a transaction. It contains the public key that the next input
333 * must be able to sign with to claim it.
339 CScript scriptPubKey;
346 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
349 scriptPubKey = scriptPubKeyIn;
355 READWRITE(scriptPubKey);
361 scriptPubKey.clear();
366 return (nValue == -1);
372 scriptPubKey.clear();
377 return (nValue == 0 && scriptPubKey.empty());
380 uint256 GetHash() const
382 return SerializeHash(*this);
385 friend bool operator==(const CTxOut& a, const CTxOut& b)
387 return (a.nValue == b.nValue &&
388 a.scriptPubKey == b.scriptPubKey);
391 friend bool operator!=(const CTxOut& a, const CTxOut& b)
396 std::string ToStringShort() const
398 return strprintf(" out %s %s", FormatMoney(nValue).c_str(), scriptPubKey.ToString(true).c_str());
401 std::string ToString() const
403 if (IsEmpty()) return "CTxOut(empty)";
404 if (scriptPubKey.size() < 6)
405 return "CTxOut(error)";
406 return strprintf("CTxOut(nValue=%s, scriptPubKey=%s)", FormatMoney(nValue).c_str(), scriptPubKey.ToString().c_str());
411 printf("%s\n", ToString().c_str());
425 typedef std::map<uint256, std::pair<CTxIndex, CTransaction> > MapPrevTx;
427 /** The basic transaction that is broadcasted on the network and contained in
428 * blocks. A transaction can contain multiple inputs and outputs.
435 std::vector<CTxIn> vin;
436 std::vector<CTxOut> vout;
437 unsigned int nLockTime;
439 // Denial-of-service detection:
441 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
450 READWRITE(this->nVersion);
451 nVersion = this->nVersion;
455 READWRITE(nLockTime);
461 nTime = GetAdjustedTime();
465 nDoS = 0; // Denial-of-service prevention
470 return (vin.empty() && vout.empty());
473 uint256 GetHash() const
475 return SerializeHash(*this);
478 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
480 // Time based nLockTime implemented in 0.1.6
483 if (nBlockHeight == 0)
484 nBlockHeight = nBestHeight;
486 nBlockTime = GetAdjustedTime();
487 if ((int64)nLockTime < ((int64)nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
489 BOOST_FOREACH(const CTxIn& txin, vin)
495 bool IsNewerThan(const CTransaction& old) const
497 if (vin.size() != old.vin.size())
499 for (unsigned int i = 0; i < vin.size(); i++)
500 if (vin[i].prevout != old.vin[i].prevout)
504 unsigned int nLowest = std::numeric_limits<unsigned int>::max();
505 for (unsigned int i = 0; i < vin.size(); i++)
507 if (vin[i].nSequence != old.vin[i].nSequence)
509 if (vin[i].nSequence <= nLowest)
512 nLowest = vin[i].nSequence;
514 if (old.vin[i].nSequence < nLowest)
517 nLowest = old.vin[i].nSequence;
524 bool IsCoinBase() const
526 return (vin.size() == 1 && vin[0].prevout.IsNull() && vout.size() >= 1);
529 bool IsCoinStake() const
531 // ppcoin: the coin stake transaction is marked with the first output empty
532 return (vin.size() > 0 && (!vin[0].prevout.IsNull()) && vout.size() >= 2 && vout[0].IsEmpty());
535 /** Check for standard transaction types
536 @return True if all outputs (scriptPubKeys) use only standard transaction forms
538 bool IsStandard() const;
540 /** Check for standard transaction types
541 @param[in] mapInputs Map of previous transactions that have outputs we're spending
542 @return True if all inputs (scriptSigs) use only standard transaction forms
543 @see CTransaction::FetchInputs
545 bool AreInputsStandard(const MapPrevTx& mapInputs) const;
547 /** Count ECDSA signature operations the old-fashioned (pre-0.6) way
548 @return number of sigops this transaction's outputs will produce when spent
549 @see CTransaction::FetchInputs
551 unsigned int GetLegacySigOpCount() const;
553 /** Count ECDSA signature operations in pay-to-script-hash inputs.
555 @param[in] mapInputs Map of previous transactions that have outputs we're spending
556 @return maximum number of sigops required to validate this transaction's inputs
557 @see CTransaction::FetchInputs
559 unsigned int GetP2SHSigOpCount(const MapPrevTx& mapInputs) const;
561 /** Amount of bitcoins spent by this transaction.
562 @return sum of all outputs (note: does not include fees)
564 int64 GetValueOut() const
567 BOOST_FOREACH(const CTxOut& txout, vout)
569 nValueOut += txout.nValue;
570 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
571 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
576 /** Amount of bitcoins coming in to this transaction
577 Note that lightweight clients may not know anything besides the hash of previous transactions,
578 so may not be able to calculate this.
580 @param[in] mapInputs Map of previous transactions that have outputs we're spending
581 @return Sum of value of all inputs (scriptSigs)
582 @see CTransaction::FetchInputs
584 int64 GetValueIn(const MapPrevTx& mapInputs) const;
586 static bool AllowFree(double dPriority)
588 // Large (in bytes) low-priority (new, small-coin) transactions
590 return dPriority > COIN * 144 / 250;
593 int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=false, enum GetMinFee_mode mode=GMF_BLOCK) const
595 // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
596 int64 nBaseFee = (mode == GMF_RELAY) ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
598 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION);
599 unsigned int nNewBlockSize = nBlockSize + nBytes;
600 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
606 // Transactions under 10K are free
607 // (about 4500bc if made of 50bc inputs)
613 // Free transaction area
614 if (nNewBlockSize < 27000)
619 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
620 if (nMinFee < nBaseFee)
622 BOOST_FOREACH(const CTxOut& txout, vout)
623 if (txout.nValue < CENT)
627 // Raise the price as the block approaches full
628 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
630 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
632 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
635 if (!MoneyRange(nMinFee))
641 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
643 CAutoFile filein = CAutoFile(OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb"), SER_DISK, CLIENT_VERSION);
645 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
648 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
649 return error("CTransaction::ReadFromDisk() : fseek failed");
654 catch (std::exception &e) {
655 return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
658 // Return file pointer
661 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
662 return error("CTransaction::ReadFromDisk() : second fseek failed");
663 *pfileRet = filein.release();
668 friend bool operator==(const CTransaction& a, const CTransaction& b)
670 return (a.nVersion == b.nVersion &&
671 a.nTime == b.nTime &&
674 a.nLockTime == b.nLockTime);
677 friend bool operator!=(const CTransaction& a, const CTransaction& b)
683 std::string ToStringShort() const
686 str += strprintf("%s %s", GetHash().ToString().c_str(), IsCoinBase()? "base" : (IsCoinStake()? "stake" : "user"));
690 std::string ToString() const
693 str += IsCoinBase()? "Coinbase" : (IsCoinStake()? "Coinstake" : "CTransaction");
694 str += strprintf("(hash=%s, nTime=%d, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
695 GetHash().ToString().substr(0,10).c_str(),
701 for (unsigned int i = 0; i < vin.size(); i++)
702 str += " " + vin[i].ToString() + "\n";
703 for (unsigned int i = 0; i < vout.size(); i++)
704 str += " " + vout[i].ToString() + "\n";
710 printf("%s", ToString().c_str());
714 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
715 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
716 bool ReadFromDisk(COutPoint prevout);
717 bool DisconnectInputs(CTxDB& txdb);
719 /** Fetch from memory and/or disk. inputsRet keys are transaction hashes.
721 @param[in] txdb Transaction database
722 @param[in] mapTestPool List of pending changes to the transaction index database
723 @param[in] fBlock True if being called to add a new best-block to the chain
724 @param[in] fMiner True if being called by CreateNewBlock
725 @param[out] inputsRet Pointers to this transaction's inputs
726 @param[out] fInvalid returns true if transaction is invalid
727 @return Returns true if all inputs are in txdb or mapTestPool
729 bool FetchInputs(CTxDB& txdb, const std::map<uint256, CTxIndex>& mapTestPool,
730 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid);
732 /** Sanity check previous transactions, then, if all checks succeed,
733 mark them as spent by this transaction.
735 @param[in] inputs Previous transactions (from FetchInputs)
736 @param[out] mapTestPool Keeps track of inputs that need to be updated on disk
737 @param[in] posThisTx Position of this transaction on disk
738 @param[in] pindexBlock
739 @param[in] fBlock true if called from ConnectBlock
740 @param[in] fMiner true if called from CreateNewBlock
741 @param[in] fStrictPayToScriptHash true if fully validating p2sh transactions
742 @return Returns true if all checks succeed
744 bool ConnectInputs(CTxDB& txdb, MapPrevTx inputs,
745 std::map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
746 const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash=true);
747 bool ClientConnectInputs();
748 bool CheckTransaction() const;
749 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
750 bool GetCoinAge(CTxDB& txdb, uint64& nCoinAge) const; // ppcoin: get transaction coin age
753 const CTxOut& GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const;
760 /** A transaction with a merkle branch linking it to the block chain. */
761 class CMerkleTx : public CTransaction
765 std::vector<uint256> vMerkleBranch;
769 mutable bool fMerkleVerified;
777 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
786 fMerkleVerified = false;
792 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
793 nVersion = this->nVersion;
794 READWRITE(hashBlock);
795 READWRITE(vMerkleBranch);
800 int SetMerkleBranch(const CBlock* pblock=NULL);
801 int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
802 int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
803 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
804 int GetBlocksToMaturity() const;
805 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
806 bool AcceptToMemoryPool();
812 /** A txdb record that contains the disk location of a transaction and the
813 * locations of transactions that spend its outputs. vSpent is really only
814 * used as a flag, but having the location is very helpful for debugging.
820 std::vector<CDiskTxPos> vSpent;
827 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
830 vSpent.resize(nOutputs);
835 if (!(nType & SER_GETHASH))
852 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
854 return (a.pos == b.pos &&
855 a.vSpent == b.vSpent);
858 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
862 int GetDepthInMainChain() const;
870 /** Nodes collect new transactions into a block, hash them into a hash tree,
871 * and scan through nonce values to make the block's hash satisfy proof-of-work
872 * requirements. When they solve the proof-of-work, they broadcast the block
873 * to everyone and the block is added to the block chain. The first transaction
874 * in the block is a special one that creates a new coin owned by the creator
877 * Blocks are appended to blk0001.dat files on disk. Their location on disk
878 * is indexed by CBlockIndex objects in memory.
885 uint256 hashPrevBlock;
886 uint256 hashMerkleRoot;
892 std::vector<CTransaction> vtx;
894 // ppcoin: block signature - signed by one of the coin base txout[N]'s owner
895 std::vector<unsigned char> vchBlockSig;
898 mutable std::vector<uint256> vMerkleTree;
900 // Denial-of-service detection:
902 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
911 READWRITE(this->nVersion);
912 nVersion = this->nVersion;
913 READWRITE(hashPrevBlock);
914 READWRITE(hashMerkleRoot);
919 // ConnectBlock depends on vtx following header to generate CDiskTxPos
920 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
923 READWRITE(vchBlockSig);
927 const_cast<CBlock*>(this)->vtx.clear();
928 const_cast<CBlock*>(this)->vchBlockSig.clear();
951 uint256 GetHash() const
954 void * scratchbuff = scrypt_buffer_alloc();
956 scrypt_hash(CVOIDBEGIN(nVersion), sizeof(block_header), UINTBEGIN(thash), scratchbuff);
958 scrypt_buffer_free(scratchbuff);
964 int64 GetBlockTime() const
969 void UpdateTime(const CBlockIndex* pindexPrev);
971 // ppcoin: entropy bit for stake modifier if chosen by modifier
972 unsigned int GetStakeEntropyBit() const
974 uint160 hashSig = Hash160(vchBlockSig);
975 if (fDebug && GetBoolArg("-printstakemodifier"))
976 printf("GetStakeEntropyBit: hashSig=%s", hashSig.ToString().c_str());
977 hashSig >>= 159; // take the first bit of the hash
978 if (fDebug && GetBoolArg("-printstakemodifier"))
979 printf(" entropybit=%d\n", hashSig.Get64());
980 return hashSig.Get64();
983 // ppcoin: two types of block: proof-of-work or proof-of-stake
984 bool IsProofOfStake() const
986 return (vtx.size() > 1 && vtx[1].IsCoinStake());
989 bool IsProofOfWork() const
991 return !IsProofOfStake();
994 std::pair<COutPoint, unsigned int> GetProofOfStake() const
996 return IsProofOfStake()? std::make_pair(vtx[1].vin[0].prevout, vtx[1].nTime) : std::make_pair(COutPoint(), (unsigned int)0);
999 // ppcoin: get max transaction timestamp
1000 int64 GetMaxTransactionTime() const
1002 int64 maxTransactionTime = 0;
1003 BOOST_FOREACH(const CTransaction& tx, vtx)
1004 maxTransactionTime = std::max(maxTransactionTime, (int64)tx.nTime);
1005 return maxTransactionTime;
1008 uint256 BuildMerkleTree() const
1010 vMerkleTree.clear();
1011 BOOST_FOREACH(const CTransaction& tx, vtx)
1012 vMerkleTree.push_back(tx.GetHash());
1014 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1016 for (int i = 0; i < nSize; i += 2)
1018 int i2 = std::min(i+1, nSize-1);
1019 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
1020 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
1024 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
1027 std::vector<uint256> GetMerkleBranch(int nIndex) const
1029 if (vMerkleTree.empty())
1031 std::vector<uint256> vMerkleBranch;
1033 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1035 int i = std::min(nIndex^1, nSize-1);
1036 vMerkleBranch.push_back(vMerkleTree[j+i]);
1040 return vMerkleBranch;
1043 static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
1047 BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
1050 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
1052 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
1059 bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
1061 // Open history file to append
1062 CAutoFile fileout = CAutoFile(AppendBlockFile(nFileRet), SER_DISK, CLIENT_VERSION);
1064 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
1066 // Write index header
1067 unsigned char pchMessageStart[4];
1068 GetMessageStart(pchMessageStart, true);
1069 unsigned int nSize = fileout.GetSerializeSize(*this);
1070 fileout << FLATDATA(pchMessageStart) << nSize;
1073 long fileOutPos = ftell(fileout);
1075 return error("CBlock::WriteToDisk() : ftell failed");
1076 nBlockPosRet = fileOutPos;
1079 // Flush stdio buffers and commit to disk before returning
1081 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
1084 _commit(_fileno(fileout));
1086 fsync(fileno(fileout));
1093 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
1097 // Open history file to read
1098 CAutoFile filein = CAutoFile(OpenBlockFile(nFile, nBlockPos, "rb"), SER_DISK, CLIENT_VERSION);
1100 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1101 if (!fReadTransactions)
1102 filein.nType |= SER_BLOCKHEADERONLY;
1108 catch (std::exception &e) {
1109 return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
1113 if (fReadTransactions && IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
1114 return error("CBlock::ReadFromDisk() : errors in block header");
1123 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d, vchBlockSig=%s)\n",
1124 GetHash().ToString().substr(0,20).c_str(),
1126 hashPrevBlock.ToString().substr(0,20).c_str(),
1127 hashMerkleRoot.ToString().substr(0,10).c_str(),
1128 nTime, nBits, nNonce,
1130 HexStr(vchBlockSig.begin(), vchBlockSig.end()).c_str());
1131 for (unsigned int i = 0; i < vtx.size(); i++)
1136 printf(" vMerkleTree: ");
1137 for (unsigned int i = 0; i < vMerkleTree.size(); i++)
1138 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1143 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1144 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1145 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1146 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1147 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1148 bool CheckBlock() const;
1150 bool GetCoinAge(uint64& nCoinAge) const; // ppcoin: calculate total coin age spent in block
1151 bool SignBlock(const CKeyStore& keystore);
1152 bool CheckBlockSignature() const;
1155 bool SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew);
1163 /** The block chain is a tree shaped structure starting with the
1164 * genesis block at the root, with each block potentially having multiple
1165 * candidates to be the next block. pprev and pnext link a path through the
1166 * main/longest chain. A blockindex may have multiple pprev pointing back
1167 * to it, but pnext will only point forward to the longest branch, or will
1168 * be null if the block is not part of the longest chain.
1173 const uint256* phashBlock;
1177 unsigned int nBlockPos;
1178 CBigNum bnChainTrust; // ppcoin: trust score of block chain
1183 unsigned int nFlags; // ppcoin: block index flags
1186 BLOCK_PROOF_OF_STAKE = (1 << 0), // is proof-of-stake block
1187 BLOCK_STAKE_ENTROPY = (1 << 1), // entropy bit for stake modifier
1188 BLOCK_STAKE_MODIFIER = (1 << 2), // regenerated stake modifier
1191 uint64 nStakeModifier; // hash modifier for proof-of-stake
1192 unsigned int nStakeModifierChecksum; // checksum of index; in-memeory only
1194 // proof-of-stake specific fields
1195 COutPoint prevoutStake;
1196 unsigned int nStakeTime;
1197 uint256 hashProofOfStake;
1201 uint256 hashMerkleRoot;
1204 unsigned int nNonce;
1220 nStakeModifierChecksum = 0;
1221 hashProofOfStake = 0;
1222 prevoutStake.SetNull();
1232 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1238 nBlockPos = nBlockPosIn;
1245 nStakeModifierChecksum = 0;
1246 hashProofOfStake = 0;
1247 if (block.IsProofOfStake())
1250 prevoutStake = block.vtx[1].vin[0].prevout;
1251 nStakeTime = block.vtx[1].nTime;
1255 prevoutStake.SetNull();
1259 nVersion = block.nVersion;
1260 hashMerkleRoot = block.hashMerkleRoot;
1261 nTime = block.nTime;
1262 nBits = block.nBits;
1263 nNonce = block.nNonce;
1266 CBlock GetBlockHeader() const
1269 block.nVersion = nVersion;
1271 block.hashPrevBlock = pprev->GetBlockHash();
1272 block.hashMerkleRoot = hashMerkleRoot;
1273 block.nTime = nTime;
1274 block.nBits = nBits;
1275 block.nNonce = nNonce;
1279 uint256 GetBlockHash() const
1284 int64 GetBlockTime() const
1286 return (int64)nTime;
1289 CBigNum GetBlockTrust() const
1292 bnTarget.SetCompact(nBits);
1295 return (IsProofOfStake()? (CBigNum(1)<<256) / (bnTarget+1) : 1);
1298 bool IsInMainChain() const
1300 return (pnext || this == pindexBest);
1303 bool CheckIndex() const
1308 bool EraseBlockFromDisk()
1310 // Open history file
1311 CAutoFile fileout = CAutoFile(OpenBlockFile(nFile, nBlockPos, "rb+"), SER_DISK, CLIENT_VERSION);
1315 // Overwrite with empty null block
1323 enum { nMedianTimeSpan=11 };
1325 int64 GetMedianTimePast() const
1327 int64 pmedian[nMedianTimeSpan];
1328 int64* pbegin = &pmedian[nMedianTimeSpan];
1329 int64* pend = &pmedian[nMedianTimeSpan];
1331 const CBlockIndex* pindex = this;
1332 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1333 *(--pbegin) = pindex->GetBlockTime();
1335 std::sort(pbegin, pend);
1336 return pbegin[(pend - pbegin)/2];
1339 int64 GetMedianTime() const
1341 const CBlockIndex* pindex = this;
1342 for (int i = 0; i < nMedianTimeSpan/2; i++)
1345 return GetBlockTime();
1346 pindex = pindex->pnext;
1348 return pindex->GetMedianTimePast();
1351 bool IsProofOfWork() const
1353 return !(nFlags & BLOCK_PROOF_OF_STAKE);
1356 bool IsProofOfStake() const
1358 return (nFlags & BLOCK_PROOF_OF_STAKE);
1361 void SetProofOfStake()
1363 nFlags |= BLOCK_PROOF_OF_STAKE;
1366 unsigned int GetStakeEntropyBit() const
1368 return ((nFlags & BLOCK_STAKE_ENTROPY) >> 1);
1371 bool SetStakeEntropyBit(unsigned int nEntropyBit)
1373 if (nEntropyBit > 1)
1375 nFlags |= (nEntropyBit? BLOCK_STAKE_ENTROPY : 0);
1379 bool GeneratedStakeModifier() const
1381 return (nFlags & BLOCK_STAKE_MODIFIER);
1384 void SetStakeModifier(uint64 nModifier, bool fGeneratedStakeModifier)
1386 nStakeModifier = nModifier;
1387 if (fGeneratedStakeModifier)
1388 nFlags |= BLOCK_STAKE_MODIFIER;
1391 std::string ToString() const
1393 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, nMint=%s, nMoneySupply=%s, nFlags=(%s)(%d)(%s), nStakeModifier=%016"PRI64x", nStakeModifierChecksum=%08x, hashProofOfStake=%s, prevoutStake=(%s), nStakeTime=%d merkle=%s, hashBlock=%s)",
1394 pprev, pnext, nFile, nBlockPos, nHeight,
1395 FormatMoney(nMint).c_str(), FormatMoney(nMoneySupply).c_str(),
1396 GeneratedStakeModifier() ? "MOD" : "-", GetStakeEntropyBit(), IsProofOfStake()? "PoS" : "PoW",
1397 nStakeModifier, nStakeModifierChecksum,
1398 hashProofOfStake.ToString().c_str(),
1399 prevoutStake.ToString().c_str(), nStakeTime,
1400 hashMerkleRoot.ToString().substr(0,10).c_str(),
1401 GetBlockHash().ToString().substr(0,20).c_str());
1406 printf("%s\n", ToString().c_str());
1412 /** Used to marshal pointers into hashes for db storage. */
1413 class CDiskBlockIndex : public CBlockIndex
1425 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1427 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1428 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1433 if (!(nType & SER_GETHASH))
1434 READWRITE(nVersion);
1436 READWRITE(hashNext);
1438 READWRITE(nBlockPos);
1441 READWRITE(nMoneySupply);
1443 READWRITE(nStakeModifier);
1444 if (IsProofOfStake())
1446 READWRITE(prevoutStake);
1447 READWRITE(nStakeTime);
1448 READWRITE(hashProofOfStake);
1452 const_cast<CDiskBlockIndex*>(this)->prevoutStake.SetNull();
1453 const_cast<CDiskBlockIndex*>(this)->nStakeTime = 0;
1454 const_cast<CDiskBlockIndex*>(this)->hashProofOfStake = 0;
1458 READWRITE(this->nVersion);
1459 READWRITE(hashPrev);
1460 READWRITE(hashMerkleRoot);
1466 uint256 GetBlockHash() const
1469 block.nVersion = nVersion;
1470 block.hashPrevBlock = hashPrev;
1471 block.hashMerkleRoot = hashMerkleRoot;
1472 block.nTime = nTime;
1473 block.nBits = nBits;
1474 block.nNonce = nNonce;
1475 return block.GetHash();
1479 std::string ToString() const
1481 std::string str = "CDiskBlockIndex(";
1482 str += CBlockIndex::ToString();
1483 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1484 GetBlockHash().ToString().c_str(),
1485 hashPrev.ToString().substr(0,20).c_str(),
1486 hashNext.ToString().substr(0,20).c_str());
1492 printf("%s\n", ToString().c_str());
1503 /** Describes a place in the block chain to another node such that if the
1504 * other node doesn't have the same branch, it can find a recent common trunk.
1505 * The further back it is, the further before the fork it may be.
1510 std::vector<uint256> vHave;
1517 explicit CBlockLocator(const CBlockIndex* pindex)
1522 explicit CBlockLocator(uint256 hashBlock)
1524 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1525 if (mi != mapBlockIndex.end())
1529 CBlockLocator(const std::vector<uint256>& vHaveIn)
1536 if (!(nType & SER_GETHASH))
1537 READWRITE(nVersion);
1548 return vHave.empty();
1551 void Set(const CBlockIndex* pindex)
1557 vHave.push_back(pindex->GetBlockHash());
1559 // Exponentially larger steps back
1560 for (int i = 0; pindex && i < nStep; i++)
1561 pindex = pindex->pprev;
1562 if (vHave.size() > 10)
1565 vHave.push_back(hashGenesisBlock);
1568 int GetDistanceBack()
1570 // Retrace how far back it was in the sender's branch
1573 BOOST_FOREACH(const uint256& hash, vHave)
1575 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1576 if (mi != mapBlockIndex.end())
1578 CBlockIndex* pindex = (*mi).second;
1579 if (pindex->IsInMainChain())
1589 CBlockIndex* GetBlockIndex()
1591 // Find the first block the caller has in the main chain
1592 BOOST_FOREACH(const uint256& hash, vHave)
1594 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1595 if (mi != mapBlockIndex.end())
1597 CBlockIndex* pindex = (*mi).second;
1598 if (pindex->IsInMainChain())
1602 return pindexGenesisBlock;
1605 uint256 GetBlockHash()
1607 // Find the first block the caller has in the main chain
1608 BOOST_FOREACH(const uint256& hash, vHave)
1610 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1611 if (mi != mapBlockIndex.end())
1613 CBlockIndex* pindex = (*mi).second;
1614 if (pindex->IsInMainChain())
1618 return hashGenesisBlock;
1623 CBlockIndex* pindex = GetBlockIndex();
1626 return pindex->nHeight;
1638 /** Alerts are for notifying old versions if they become too obsolete and
1639 * need to upgrade. The message is displayed in the status bar.
1640 * Alert messages are broadcast as a vector of signed data. Unserializing may
1641 * not read the entire buffer if the alert is for a newer version, but older
1642 * versions can still relay the original data.
1644 class CUnsignedAlert
1648 int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
1652 std::set<int> setCancel;
1653 int nMinVer; // lowest version inclusive
1654 int nMaxVer; // highest version inclusive
1655 std::set<std::string> setSubVer; // empty matches all
1659 std::string strComment;
1660 std::string strStatusBar;
1661 std::string strReserved;
1665 READWRITE(this->nVersion);
1666 nVersion = this->nVersion;
1667 READWRITE(nRelayUntil);
1668 READWRITE(nExpiration);
1671 READWRITE(setCancel);
1674 READWRITE(setSubVer);
1675 READWRITE(nPriority);
1677 READWRITE(strComment);
1678 READWRITE(strStatusBar);
1679 READWRITE(strReserved);
1696 strStatusBar.clear();
1697 strReserved.clear();
1700 std::string ToString() const
1702 std::string strSetCancel;
1703 BOOST_FOREACH(int n, setCancel)
1704 strSetCancel += strprintf("%d ", n);
1705 std::string strSetSubVer;
1706 BOOST_FOREACH(std::string str, setSubVer)
1707 strSetSubVer += "\"" + str + "\" ";
1711 " nRelayUntil = %"PRI64d"\n"
1712 " nExpiration = %"PRI64d"\n"
1720 " strComment = \"%s\"\n"
1721 " strStatusBar = \"%s\"\n"
1728 strSetCancel.c_str(),
1731 strSetSubVer.c_str(),
1734 strStatusBar.c_str());
1739 printf("%s", ToString().c_str());
1743 /** An alert is a combination of a serialized CUnsignedAlert and a signature. */
1744 class CAlert : public CUnsignedAlert
1747 std::vector<unsigned char> vchMsg;
1748 std::vector<unsigned char> vchSig;
1763 CUnsignedAlert::SetNull();
1770 return (nExpiration == 0);
1773 uint256 GetHash() const
1775 return SerializeHash(*this);
1778 bool IsInEffect() const
1780 return (GetAdjustedTime() < nExpiration);
1783 bool Cancels(const CAlert& alert) const
1786 return false; // this was a no-op before 31403
1787 return (alert.nID <= nCancel || setCancel.count(alert.nID));
1790 bool AppliesTo(int nVersion, std::string strSubVerIn) const
1792 // TODO: rework for client-version-embedded-in-strSubVer ?
1793 return (IsInEffect() &&
1794 nMinVer <= nVersion && nVersion <= nMaxVer &&
1795 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1798 bool AppliesToMe() const
1800 return AppliesTo(PROTOCOL_VERSION, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<std::string>()));
1803 bool RelayTo(CNode* pnode) const
1807 // returns true if wasn't already contained in the set
1808 if (pnode->setKnown.insert(GetHash()).second)
1810 if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
1812 GetAdjustedTime() < nRelayUntil)
1814 pnode->PushMessage("alert", *this);
1821 bool CheckSignature()
1824 if (!key.SetPubKey(ParseHex("043fa441fd4203d03f5df2b75ea14e36f20d39f43e7a61aa7552ab9bcd7ecb0e77a3be4585b13fcdaa22ef6e51f1ff6f2929bec2494385b086fb86610e33193195")))
1825 return error("CAlert::CheckSignature() : SetPubKey failed");
1826 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
1827 return error("CAlert::CheckSignature() : verify signature failed");
1829 // Now unserialize the data
1830 CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION);
1831 sMsg >> *(CUnsignedAlert*)this;
1835 bool ProcessAlert();
1841 mutable CCriticalSection cs;
1842 std::map<uint256, CTransaction> mapTx;
1843 std::map<COutPoint, CInPoint> mapNextTx;
1845 bool accept(CTxDB& txdb, CTransaction &tx,
1846 bool fCheckInputs, bool* pfMissingInputs);
1847 bool addUnchecked(CTransaction &tx);
1848 bool remove(CTransaction &tx);
1850 unsigned long size()
1853 return mapTx.size();
1856 bool exists(uint256 hash)
1858 return (mapTx.count(hash) != 0);
1861 CTransaction& lookup(uint256 hash)
1867 extern CTxMemPool mempool;