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 bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock);
125 uint256 WantedByOrphan(const CBlock* pblockOrphan);
126 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake);
127 void BitcoinMiner(CWallet *pwallet, bool fProofOfStake);
128 void ResendWalletTransactions();
136 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
138 /** Position on disk for a particular transaction. */
143 unsigned int nBlockPos;
151 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
154 nBlockPos = nBlockPosIn;
158 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
159 void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
160 bool IsNull() const { return (nFile == -1); }
162 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
164 return (a.nFile == b.nFile &&
165 a.nBlockPos == b.nBlockPos &&
166 a.nTxPos == b.nTxPos);
169 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
174 std::string ToString() const
179 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
184 printf("%s", ToString().c_str());
190 /** An inpoint - a combination of a transaction and an index n into its vin */
197 CInPoint() { SetNull(); }
198 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
199 void SetNull() { ptx = NULL; n = -1; }
200 bool IsNull() const { return (ptx == NULL && n == -1); }
205 /** An outpoint - a combination of a transaction hash and an index n into its vout */
212 COutPoint() { SetNull(); }
213 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
214 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
215 void SetNull() { hash = 0; n = -1; }
216 bool IsNull() const { return (hash == 0 && n == -1); }
218 friend bool operator<(const COutPoint& a, const COutPoint& b)
220 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
223 friend bool operator==(const COutPoint& a, const COutPoint& b)
225 return (a.hash == b.hash && a.n == b.n);
228 friend bool operator!=(const COutPoint& a, const COutPoint& b)
233 std::string ToString() const
235 return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,10).c_str(), n);
240 printf("%s\n", ToString().c_str());
247 /** An input of a transaction. It contains the location of the previous
248 * transaction's output that it claims and a signature that matches the
249 * output's public key.
256 unsigned int nSequence;
260 nSequence = std::numeric_limits<unsigned int>::max();
263 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
266 scriptSig = scriptSigIn;
267 nSequence = nSequenceIn;
270 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
272 prevout = COutPoint(hashPrevTx, nOut);
273 scriptSig = scriptSigIn;
274 nSequence = nSequenceIn;
280 READWRITE(scriptSig);
281 READWRITE(nSequence);
286 return (nSequence == std::numeric_limits<unsigned int>::max());
289 friend bool operator==(const CTxIn& a, const CTxIn& b)
291 return (a.prevout == b.prevout &&
292 a.scriptSig == b.scriptSig &&
293 a.nSequence == b.nSequence);
296 friend bool operator!=(const CTxIn& a, const CTxIn& b)
301 std::string ToStringShort() const
303 return strprintf(" %s %d", prevout.hash.ToString().c_str(), prevout.n);
306 std::string ToString() const
310 str += prevout.ToString();
311 if (prevout.IsNull())
312 str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
314 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
315 if (nSequence != std::numeric_limits<unsigned int>::max())
316 str += strprintf(", nSequence=%u", nSequence);
323 printf("%s\n", ToString().c_str());
330 /** An output of a transaction. It contains the public key that the next input
331 * must be able to sign with to claim it.
337 CScript scriptPubKey;
344 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
347 scriptPubKey = scriptPubKeyIn;
353 READWRITE(scriptPubKey);
359 scriptPubKey.clear();
364 return (nValue == -1);
370 scriptPubKey.clear();
375 return (nValue == 0 && scriptPubKey.empty());
378 uint256 GetHash() const
380 return SerializeHash(*this);
383 friend bool operator==(const CTxOut& a, const CTxOut& b)
385 return (a.nValue == b.nValue &&
386 a.scriptPubKey == b.scriptPubKey);
389 friend bool operator!=(const CTxOut& a, const CTxOut& b)
394 std::string ToStringShort() const
396 return strprintf(" out %s %s", FormatMoney(nValue).c_str(), scriptPubKey.ToString(true).c_str());
399 std::string ToString() const
401 if (IsEmpty()) return "CTxOut(empty)";
402 if (scriptPubKey.size() < 6)
403 return "CTxOut(error)";
404 return strprintf("CTxOut(nValue=%s, scriptPubKey=%s)", FormatMoney(nValue).c_str(), scriptPubKey.ToString().c_str());
409 printf("%s\n", ToString().c_str());
423 typedef std::map<uint256, std::pair<CTxIndex, CTransaction> > MapPrevTx;
425 /** The basic transaction that is broadcasted on the network and contained in
426 * blocks. A transaction can contain multiple inputs and outputs.
433 std::vector<CTxIn> vin;
434 std::vector<CTxOut> vout;
435 unsigned int nLockTime;
437 // Denial-of-service detection:
439 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
448 READWRITE(this->nVersion);
449 nVersion = this->nVersion;
453 READWRITE(nLockTime);
459 nTime = GetAdjustedTime();
463 nDoS = 0; // Denial-of-service prevention
468 return (vin.empty() && vout.empty());
471 uint256 GetHash() const
473 return SerializeHash(*this);
476 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
478 // Time based nLockTime implemented in 0.1.6
481 if (nBlockHeight == 0)
482 nBlockHeight = nBestHeight;
484 nBlockTime = GetAdjustedTime();
485 if ((int64)nLockTime < ((int64)nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
487 BOOST_FOREACH(const CTxIn& txin, vin)
493 bool IsNewerThan(const CTransaction& old) const
495 if (vin.size() != old.vin.size())
497 for (unsigned int i = 0; i < vin.size(); i++)
498 if (vin[i].prevout != old.vin[i].prevout)
502 unsigned int nLowest = std::numeric_limits<unsigned int>::max();
503 for (unsigned int i = 0; i < vin.size(); i++)
505 if (vin[i].nSequence != old.vin[i].nSequence)
507 if (vin[i].nSequence <= nLowest)
510 nLowest = vin[i].nSequence;
512 if (old.vin[i].nSequence < nLowest)
515 nLowest = old.vin[i].nSequence;
522 bool IsCoinBase() const
524 return (vin.size() == 1 && vin[0].prevout.IsNull() && vout.size() >= 1);
527 bool IsCoinStake() const
529 // ppcoin: the coin stake transaction is marked with the first output empty
530 return (vin.size() > 0 && (!vin[0].prevout.IsNull()) && vout.size() >= 2 && vout[0].IsEmpty());
533 /** Check for standard transaction types
534 @return True if all outputs (scriptPubKeys) use only standard transaction forms
536 bool IsStandard() const;
538 /** Check for standard transaction types
539 @param[in] mapInputs Map of previous transactions that have outputs we're spending
540 @return True if all inputs (scriptSigs) use only standard transaction forms
541 @see CTransaction::FetchInputs
543 bool AreInputsStandard(const MapPrevTx& mapInputs) const;
545 /** Count ECDSA signature operations the old-fashioned (pre-0.6) way
546 @return number of sigops this transaction's outputs will produce when spent
547 @see CTransaction::FetchInputs
549 unsigned int GetLegacySigOpCount() const;
551 /** Count ECDSA signature operations in pay-to-script-hash inputs.
553 @param[in] mapInputs Map of previous transactions that have outputs we're spending
554 @return maximum number of sigops required to validate this transaction's inputs
555 @see CTransaction::FetchInputs
557 unsigned int GetP2SHSigOpCount(const MapPrevTx& mapInputs) const;
559 /** Amount of bitcoins spent by this transaction.
560 @return sum of all outputs (note: does not include fees)
562 int64 GetValueOut() const
565 BOOST_FOREACH(const CTxOut& txout, vout)
567 nValueOut += txout.nValue;
568 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
569 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
574 /** Amount of bitcoins coming in to this transaction
575 Note that lightweight clients may not know anything besides the hash of previous transactions,
576 so may not be able to calculate this.
578 @param[in] mapInputs Map of previous transactions that have outputs we're spending
579 @return Sum of value of all inputs (scriptSigs)
580 @see CTransaction::FetchInputs
582 int64 GetValueIn(const MapPrevTx& mapInputs) const;
584 static bool AllowFree(double dPriority)
586 // Large (in bytes) low-priority (new, small-coin) transactions
588 return dPriority > COIN * 144 / 250;
591 int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=false, enum GetMinFee_mode mode=GMF_BLOCK) const
593 // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
594 int64 nBaseFee = (mode == GMF_RELAY) ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
596 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION);
597 unsigned int nNewBlockSize = nBlockSize + nBytes;
598 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
604 // Transactions under 10K are free
605 // (about 4500bc if made of 50bc inputs)
611 // Free transaction area
612 if (nNewBlockSize < 27000)
617 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
618 if (nMinFee < nBaseFee)
620 BOOST_FOREACH(const CTxOut& txout, vout)
621 if (txout.nValue < CENT)
625 // Raise the price as the block approaches full
626 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
628 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
630 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
633 if (!MoneyRange(nMinFee))
639 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
641 CAutoFile filein = CAutoFile(OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb"), SER_DISK, CLIENT_VERSION);
643 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
646 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
647 return error("CTransaction::ReadFromDisk() : fseek failed");
652 catch (std::exception &e) {
653 return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
656 // Return file pointer
659 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
660 return error("CTransaction::ReadFromDisk() : second fseek failed");
661 *pfileRet = filein.release();
666 friend bool operator==(const CTransaction& a, const CTransaction& b)
668 return (a.nVersion == b.nVersion &&
669 a.nTime == b.nTime &&
672 a.nLockTime == b.nLockTime);
675 friend bool operator!=(const CTransaction& a, const CTransaction& b)
681 std::string ToStringShort() const
684 str += strprintf("%s %s", GetHash().ToString().c_str(), IsCoinBase()? "base" : (IsCoinStake()? "stake" : "user"));
688 std::string ToString() const
691 str += IsCoinBase()? "Coinbase" : (IsCoinStake()? "Coinstake" : "CTransaction");
692 str += strprintf("(hash=%s, nTime=%d, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
693 GetHash().ToString().substr(0,10).c_str(),
699 for (unsigned int i = 0; i < vin.size(); i++)
700 str += " " + vin[i].ToString() + "\n";
701 for (unsigned int i = 0; i < vout.size(); i++)
702 str += " " + vout[i].ToString() + "\n";
708 printf("%s", ToString().c_str());
712 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
713 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
714 bool ReadFromDisk(COutPoint prevout);
715 bool DisconnectInputs(CTxDB& txdb);
717 /** Fetch from memory and/or disk. inputsRet keys are transaction hashes.
719 @param[in] txdb Transaction database
720 @param[in] mapTestPool List of pending changes to the transaction index database
721 @param[in] fBlock True if being called to add a new best-block to the chain
722 @param[in] fMiner True if being called by CreateNewBlock
723 @param[out] inputsRet Pointers to this transaction's inputs
724 @param[out] fInvalid returns true if transaction is invalid
725 @return Returns true if all inputs are in txdb or mapTestPool
727 bool FetchInputs(CTxDB& txdb, const std::map<uint256, CTxIndex>& mapTestPool,
728 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid);
730 /** Sanity check previous transactions, then, if all checks succeed,
731 mark them as spent by this transaction.
733 @param[in] inputs Previous transactions (from FetchInputs)
734 @param[out] mapTestPool Keeps track of inputs that need to be updated on disk
735 @param[in] posThisTx Position of this transaction on disk
736 @param[in] pindexBlock
737 @param[in] fBlock true if called from ConnectBlock
738 @param[in] fMiner true if called from CreateNewBlock
739 @param[in] fStrictPayToScriptHash true if fully validating p2sh transactions
740 @return Returns true if all checks succeed
742 bool ConnectInputs(CTxDB& txdb, MapPrevTx inputs,
743 std::map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
744 const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash=true);
745 bool ClientConnectInputs();
746 bool CheckTransaction() const;
747 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
748 bool GetCoinAge(CTxDB& txdb, uint64& nCoinAge) const; // ppcoin: get transaction coin age
751 const CTxOut& GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const;
758 /** A transaction with a merkle branch linking it to the block chain. */
759 class CMerkleTx : public CTransaction
763 std::vector<uint256> vMerkleBranch;
767 mutable bool fMerkleVerified;
775 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
784 fMerkleVerified = false;
790 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
791 nVersion = this->nVersion;
792 READWRITE(hashBlock);
793 READWRITE(vMerkleBranch);
798 int SetMerkleBranch(const CBlock* pblock=NULL);
799 int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
800 int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
801 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
802 int GetBlocksToMaturity() const;
803 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
804 bool AcceptToMemoryPool();
810 /** A txdb record that contains the disk location of a transaction and the
811 * locations of transactions that spend its outputs. vSpent is really only
812 * used as a flag, but having the location is very helpful for debugging.
818 std::vector<CDiskTxPos> vSpent;
825 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
828 vSpent.resize(nOutputs);
833 if (!(nType & SER_GETHASH))
850 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
852 return (a.pos == b.pos &&
853 a.vSpent == b.vSpent);
856 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
860 int GetDepthInMainChain() const;
867 /** Nodes collect new transactions into a block, hash them into a hash tree,
868 * and scan through nonce values to make the block's hash satisfy proof-of-work
869 * requirements. When they solve the proof-of-work, they broadcast the block
870 * to everyone and the block is added to the block chain. The first transaction
871 * in the block is a special one that creates a new coin owned by the creator
874 * Blocks are appended to blk0001.dat files on disk. Their location on disk
875 * is indexed by CBlockIndex objects in memory.
882 uint256 hashPrevBlock;
883 uint256 hashMerkleRoot;
889 std::vector<CTransaction> vtx;
891 // ppcoin: block signature - signed by one of the coin base txout[N]'s owner
892 std::vector<unsigned char> vchBlockSig;
895 mutable std::vector<uint256> vMerkleTree;
897 // Denial-of-service detection:
899 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
908 READWRITE(this->nVersion);
909 nVersion = this->nVersion;
910 READWRITE(hashPrevBlock);
911 READWRITE(hashMerkleRoot);
916 // ConnectBlock depends on vtx following header to generate CDiskTxPos
917 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
920 READWRITE(vchBlockSig);
924 const_cast<CBlock*>(this)->vtx.clear();
925 const_cast<CBlock*>(this)->vchBlockSig.clear();
948 uint256 GetHash() const
951 void * scratchbuff = scrypt_buffer_alloc();
953 scrypt_hash(CVOIDBEGIN(nVersion), sizeof(block_header), UINTBEGIN(thash), scratchbuff);
955 scrypt_buffer_free(scratchbuff);
961 int64 GetBlockTime() const
966 void UpdateTime(const CBlockIndex* pindexPrev);
968 // ppcoin: entropy bit for stake modifier if chosen by modifier
969 unsigned int GetStakeEntropyBit(unsigned int nHeight) const
971 // Protocol switch to support p2pool at novacoin block #9689
974 // Take last bit of block hash as entropy bit
975 unsigned int nEntropyBit = ((GetHash().Get64()) & 1llu);
976 if (fDebug && GetBoolArg("-printstakemodifier"))
977 printf("GetStakeEntropyBit: nHeight=%u hashBlock=%s nEntropyBit=%u\n", nHeight, GetHash().ToString().c_str(), nEntropyBit);
980 // Before novacoin block #9689 - old protocol
981 uint160 hashSig = Hash160(vchBlockSig);
982 if (fDebug && GetBoolArg("-printstakemodifier"))
983 printf("GetStakeEntropyBit: hashSig=%s", hashSig.ToString().c_str());
984 hashSig >>= 159; // take the first bit of the hash
985 if (fDebug && GetBoolArg("-printstakemodifier"))
986 printf(" entropybit=%d\n", hashSig.Get64());
987 return hashSig.Get64();
990 // ppcoin: two types of block: proof-of-work or proof-of-stake
991 bool IsProofOfStake() const
993 return (vtx.size() > 1 && vtx[1].IsCoinStake());
996 bool IsProofOfWork() const
998 return !IsProofOfStake();
1001 std::pair<COutPoint, unsigned int> GetProofOfStake() const
1003 return IsProofOfStake()? std::make_pair(vtx[1].vin[0].prevout, vtx[1].nTime) : std::make_pair(COutPoint(), (unsigned int)0);
1006 // ppcoin: get max transaction timestamp
1007 int64 GetMaxTransactionTime() const
1009 int64 maxTransactionTime = 0;
1010 BOOST_FOREACH(const CTransaction& tx, vtx)
1011 maxTransactionTime = std::max(maxTransactionTime, (int64)tx.nTime);
1012 return maxTransactionTime;
1015 uint256 BuildMerkleTree() const
1017 vMerkleTree.clear();
1018 BOOST_FOREACH(const CTransaction& tx, vtx)
1019 vMerkleTree.push_back(tx.GetHash());
1021 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1023 for (int i = 0; i < nSize; i += 2)
1025 int i2 = std::min(i+1, nSize-1);
1026 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
1027 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
1031 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
1034 std::vector<uint256> GetMerkleBranch(int nIndex) const
1036 if (vMerkleTree.empty())
1038 std::vector<uint256> vMerkleBranch;
1040 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1042 int i = std::min(nIndex^1, nSize-1);
1043 vMerkleBranch.push_back(vMerkleTree[j+i]);
1047 return vMerkleBranch;
1050 static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
1054 BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
1057 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
1059 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
1066 bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
1068 // Open history file to append
1069 CAutoFile fileout = CAutoFile(AppendBlockFile(nFileRet), SER_DISK, CLIENT_VERSION);
1071 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
1073 // Write index header
1074 unsigned char pchMessageStart[4];
1075 GetMessageStart(pchMessageStart, true);
1076 unsigned int nSize = fileout.GetSerializeSize(*this);
1077 fileout << FLATDATA(pchMessageStart) << nSize;
1080 long fileOutPos = ftell(fileout);
1082 return error("CBlock::WriteToDisk() : ftell failed");
1083 nBlockPosRet = fileOutPos;
1086 // Flush stdio buffers and commit to disk before returning
1088 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
1091 _commit(_fileno(fileout));
1093 fsync(fileno(fileout));
1100 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
1104 // Open history file to read
1105 CAutoFile filein = CAutoFile(OpenBlockFile(nFile, nBlockPos, "rb"), SER_DISK, CLIENT_VERSION);
1107 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1108 if (!fReadTransactions)
1109 filein.nType |= SER_BLOCKHEADERONLY;
1115 catch (std::exception &e) {
1116 return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
1120 if (fReadTransactions && IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
1121 return error("CBlock::ReadFromDisk() : errors in block header");
1130 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d, vchBlockSig=%s)\n",
1131 GetHash().ToString().substr(0,20).c_str(),
1133 hashPrevBlock.ToString().substr(0,20).c_str(),
1134 hashMerkleRoot.ToString().substr(0,10).c_str(),
1135 nTime, nBits, nNonce,
1137 HexStr(vchBlockSig.begin(), vchBlockSig.end()).c_str());
1138 for (unsigned int i = 0; i < vtx.size(); i++)
1143 printf(" vMerkleTree: ");
1144 for (unsigned int i = 0; i < vMerkleTree.size(); i++)
1145 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1150 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1151 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1152 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1153 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1154 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1155 bool CheckBlock() const;
1157 bool GetCoinAge(uint64& nCoinAge) const; // ppcoin: calculate total coin age spent in block
1158 bool SignBlock(const CKeyStore& keystore);
1159 bool CheckBlockSignature() const;
1162 bool SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew);
1170 /** The block chain is a tree shaped structure starting with the
1171 * genesis block at the root, with each block potentially having multiple
1172 * candidates to be the next block. pprev and pnext link a path through the
1173 * main/longest chain. A blockindex may have multiple pprev pointing back
1174 * to it, but pnext will only point forward to the longest branch, or will
1175 * be null if the block is not part of the longest chain.
1180 const uint256* phashBlock;
1184 unsigned int nBlockPos;
1185 CBigNum bnChainTrust; // ppcoin: trust score of block chain
1190 unsigned int nFlags; // ppcoin: block index flags
1193 BLOCK_PROOF_OF_STAKE = (1 << 0), // is proof-of-stake block
1194 BLOCK_STAKE_ENTROPY = (1 << 1), // entropy bit for stake modifier
1195 BLOCK_STAKE_MODIFIER = (1 << 2), // regenerated stake modifier
1198 uint64 nStakeModifier; // hash modifier for proof-of-stake
1199 unsigned int nStakeModifierChecksum; // checksum of index; in-memeory only
1201 // proof-of-stake specific fields
1202 COutPoint prevoutStake;
1203 unsigned int nStakeTime;
1204 uint256 hashProofOfStake;
1208 uint256 hashMerkleRoot;
1211 unsigned int nNonce;
1227 nStakeModifierChecksum = 0;
1228 hashProofOfStake = 0;
1229 prevoutStake.SetNull();
1239 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1245 nBlockPos = nBlockPosIn;
1252 nStakeModifierChecksum = 0;
1253 hashProofOfStake = 0;
1254 if (block.IsProofOfStake())
1257 prevoutStake = block.vtx[1].vin[0].prevout;
1258 nStakeTime = block.vtx[1].nTime;
1262 prevoutStake.SetNull();
1266 nVersion = block.nVersion;
1267 hashMerkleRoot = block.hashMerkleRoot;
1268 nTime = block.nTime;
1269 nBits = block.nBits;
1270 nNonce = block.nNonce;
1273 CBlock GetBlockHeader() const
1276 block.nVersion = nVersion;
1278 block.hashPrevBlock = pprev->GetBlockHash();
1279 block.hashMerkleRoot = hashMerkleRoot;
1280 block.nTime = nTime;
1281 block.nBits = nBits;
1282 block.nNonce = nNonce;
1286 uint256 GetBlockHash() const
1291 int64 GetBlockTime() const
1293 return (int64)nTime;
1296 CBigNum GetBlockTrust() const
1299 bnTarget.SetCompact(nBits);
1302 return (IsProofOfStake()? (CBigNum(1)<<256) / (bnTarget+1) : 1);
1305 bool IsInMainChain() const
1307 return (pnext || this == pindexBest);
1310 bool CheckIndex() const
1315 bool EraseBlockFromDisk()
1317 // Open history file
1318 CAutoFile fileout = CAutoFile(OpenBlockFile(nFile, nBlockPos, "rb+"), SER_DISK, CLIENT_VERSION);
1322 // Overwrite with empty null block
1330 enum { nMedianTimeSpan=11 };
1332 int64 GetMedianTimePast() const
1334 int64 pmedian[nMedianTimeSpan];
1335 int64* pbegin = &pmedian[nMedianTimeSpan];
1336 int64* pend = &pmedian[nMedianTimeSpan];
1338 const CBlockIndex* pindex = this;
1339 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1340 *(--pbegin) = pindex->GetBlockTime();
1342 std::sort(pbegin, pend);
1343 return pbegin[(pend - pbegin)/2];
1346 int64 GetMedianTime() const
1348 const CBlockIndex* pindex = this;
1349 for (int i = 0; i < nMedianTimeSpan/2; i++)
1352 return GetBlockTime();
1353 pindex = pindex->pnext;
1355 return pindex->GetMedianTimePast();
1358 bool IsProofOfWork() const
1360 return !(nFlags & BLOCK_PROOF_OF_STAKE);
1363 bool IsProofOfStake() const
1365 return (nFlags & BLOCK_PROOF_OF_STAKE);
1368 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired, unsigned int nToCheck)
1370 unsigned int nFound = 0;
1371 for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++)
1373 if (pstart->nVersion >= minVersion)
1375 pstart = pstart->pprev;
1377 return (nFound >= nRequired);
1380 void SetProofOfStake()
1382 nFlags |= BLOCK_PROOF_OF_STAKE;
1385 unsigned int GetStakeEntropyBit() const
1387 return ((nFlags & BLOCK_STAKE_ENTROPY) >> 1);
1390 bool SetStakeEntropyBit(unsigned int nEntropyBit)
1392 if (nEntropyBit > 1)
1394 nFlags |= (nEntropyBit? BLOCK_STAKE_ENTROPY : 0);
1398 bool GeneratedStakeModifier() const
1400 return (nFlags & BLOCK_STAKE_MODIFIER);
1403 void SetStakeModifier(uint64 nModifier, bool fGeneratedStakeModifier)
1405 nStakeModifier = nModifier;
1406 if (fGeneratedStakeModifier)
1407 nFlags |= BLOCK_STAKE_MODIFIER;
1410 std::string ToString() const
1412 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)",
1413 pprev, pnext, nFile, nBlockPos, nHeight,
1414 FormatMoney(nMint).c_str(), FormatMoney(nMoneySupply).c_str(),
1415 GeneratedStakeModifier() ? "MOD" : "-", GetStakeEntropyBit(), IsProofOfStake()? "PoS" : "PoW",
1416 nStakeModifier, nStakeModifierChecksum,
1417 hashProofOfStake.ToString().c_str(),
1418 prevoutStake.ToString().c_str(), nStakeTime,
1419 hashMerkleRoot.ToString().substr(0,10).c_str(),
1420 GetBlockHash().ToString().substr(0,20).c_str());
1425 printf("%s\n", ToString().c_str());
1431 /** Used to marshal pointers into hashes for db storage. */
1432 class CDiskBlockIndex : public CBlockIndex
1437 int nProtocolVersion;
1443 nProtocolVersion = PROTOCOL_VERSION;
1446 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1448 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1449 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1454 if (!(nType & SER_GETHASH))
1455 READWRITE(nVersion);
1457 READWRITE(hashNext);
1459 READWRITE(nBlockPos);
1462 READWRITE(nMoneySupply);
1464 READWRITE(nStakeModifier);
1465 READWRITE(nProtocolVersion);
1466 if (IsProofOfStake())
1468 READWRITE(prevoutStake);
1469 READWRITE(nStakeTime);
1470 READWRITE(hashProofOfStake);
1474 const_cast<CDiskBlockIndex*>(this)->prevoutStake.SetNull();
1475 const_cast<CDiskBlockIndex*>(this)->nStakeTime = 0;
1476 const_cast<CDiskBlockIndex*>(this)->hashProofOfStake = 0;
1480 READWRITE(this->nVersion);
1481 READWRITE(hashPrev);
1482 READWRITE(hashMerkleRoot);
1488 uint256 GetBlockHash() const
1491 block.nVersion = nVersion;
1492 block.hashPrevBlock = hashPrev;
1493 block.hashMerkleRoot = hashMerkleRoot;
1494 block.nTime = nTime;
1495 block.nBits = nBits;
1496 block.nNonce = nNonce;
1497 return block.GetHash();
1501 std::string ToString() const
1503 std::string str = "CDiskBlockIndex(";
1504 str += CBlockIndex::ToString();
1505 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1506 GetBlockHash().ToString().c_str(),
1507 hashPrev.ToString().substr(0,20).c_str(),
1508 hashNext.ToString().substr(0,20).c_str());
1514 printf("%s\n", ToString().c_str());
1525 /** Describes a place in the block chain to another node such that if the
1526 * other node doesn't have the same branch, it can find a recent common trunk.
1527 * The further back it is, the further before the fork it may be.
1532 std::vector<uint256> vHave;
1539 explicit CBlockLocator(const CBlockIndex* pindex)
1544 explicit CBlockLocator(uint256 hashBlock)
1546 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1547 if (mi != mapBlockIndex.end())
1551 CBlockLocator(const std::vector<uint256>& vHaveIn)
1558 if (!(nType & SER_GETHASH))
1559 READWRITE(nVersion);
1570 return vHave.empty();
1573 void Set(const CBlockIndex* pindex)
1579 vHave.push_back(pindex->GetBlockHash());
1581 // Exponentially larger steps back
1582 for (int i = 0; pindex && i < nStep; i++)
1583 pindex = pindex->pprev;
1584 if (vHave.size() > 10)
1587 vHave.push_back(hashGenesisBlock);
1590 int GetDistanceBack()
1592 // Retrace how far back it was in the sender's branch
1595 BOOST_FOREACH(const uint256& hash, vHave)
1597 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1598 if (mi != mapBlockIndex.end())
1600 CBlockIndex* pindex = (*mi).second;
1601 if (pindex->IsInMainChain())
1611 CBlockIndex* GetBlockIndex()
1613 // Find the first block the caller has in the main chain
1614 BOOST_FOREACH(const uint256& hash, vHave)
1616 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1617 if (mi != mapBlockIndex.end())
1619 CBlockIndex* pindex = (*mi).second;
1620 if (pindex->IsInMainChain())
1624 return pindexGenesisBlock;
1627 uint256 GetBlockHash()
1629 // Find the first block the caller has in the main chain
1630 BOOST_FOREACH(const uint256& hash, vHave)
1632 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1633 if (mi != mapBlockIndex.end())
1635 CBlockIndex* pindex = (*mi).second;
1636 if (pindex->IsInMainChain())
1640 return hashGenesisBlock;
1645 CBlockIndex* pindex = GetBlockIndex();
1648 return pindex->nHeight;
1660 /** Alerts are for notifying old versions if they become too obsolete and
1661 * need to upgrade. The message is displayed in the status bar.
1662 * Alert messages are broadcast as a vector of signed data. Unserializing may
1663 * not read the entire buffer if the alert is for a newer version, but older
1664 * versions can still relay the original data.
1666 class CUnsignedAlert
1670 int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
1674 std::set<int> setCancel;
1675 int nMinVer; // lowest version inclusive
1676 int nMaxVer; // highest version inclusive
1677 std::set<std::string> setSubVer; // empty matches all
1681 std::string strComment;
1682 std::string strStatusBar;
1683 std::string strReserved;
1687 READWRITE(this->nVersion);
1688 nVersion = this->nVersion;
1689 READWRITE(nRelayUntil);
1690 READWRITE(nExpiration);
1693 READWRITE(setCancel);
1696 READWRITE(setSubVer);
1697 READWRITE(nPriority);
1699 READWRITE(strComment);
1700 READWRITE(strStatusBar);
1701 READWRITE(strReserved);
1718 strStatusBar.clear();
1719 strReserved.clear();
1722 std::string ToString() const
1724 std::string strSetCancel;
1725 BOOST_FOREACH(int n, setCancel)
1726 strSetCancel += strprintf("%d ", n);
1727 std::string strSetSubVer;
1728 BOOST_FOREACH(std::string str, setSubVer)
1729 strSetSubVer += "\"" + str + "\" ";
1733 " nRelayUntil = %"PRI64d"\n"
1734 " nExpiration = %"PRI64d"\n"
1742 " strComment = \"%s\"\n"
1743 " strStatusBar = \"%s\"\n"
1750 strSetCancel.c_str(),
1753 strSetSubVer.c_str(),
1756 strStatusBar.c_str());
1761 printf("%s", ToString().c_str());
1765 /** An alert is a combination of a serialized CUnsignedAlert and a signature. */
1766 class CAlert : public CUnsignedAlert
1769 std::vector<unsigned char> vchMsg;
1770 std::vector<unsigned char> vchSig;
1785 CUnsignedAlert::SetNull();
1792 return (nExpiration == 0);
1795 uint256 GetHash() const
1797 return SerializeHash(*this);
1800 bool IsInEffect() const
1802 return (GetAdjustedTime() < nExpiration);
1805 bool Cancels(const CAlert& alert) const
1808 return false; // this was a no-op before 31403
1809 return (alert.nID <= nCancel || setCancel.count(alert.nID));
1812 bool AppliesTo(int nVersion, std::string strSubVerIn) const
1814 // TODO: rework for client-version-embedded-in-strSubVer ?
1815 return (IsInEffect() &&
1816 nMinVer <= nVersion && nVersion <= nMaxVer &&
1817 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1820 bool AppliesToMe() const
1822 return AppliesTo(PROTOCOL_VERSION, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<std::string>()));
1825 bool RelayTo(CNode* pnode) const
1829 // returns true if wasn't already contained in the set
1830 if (pnode->setKnown.insert(GetHash()).second)
1832 if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
1834 GetAdjustedTime() < nRelayUntil)
1836 pnode->PushMessage("alert", *this);
1843 bool CheckSignature()
1846 if (!key.SetPubKey(ParseHex("043fa441fd4203d03f5df2b75ea14e36f20d39f43e7a61aa7552ab9bcd7ecb0e77a3be4585b13fcdaa22ef6e51f1ff6f2929bec2494385b086fb86610e33193195")))
1847 return error("CAlert::CheckSignature() : SetPubKey failed");
1848 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
1849 return error("CAlert::CheckSignature() : verify signature failed");
1851 // Now unserialize the data
1852 CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION);
1853 sMsg >> *(CUnsignedAlert*)this;
1857 bool ProcessAlert();
1863 mutable CCriticalSection cs;
1864 std::map<uint256, CTransaction> mapTx;
1865 std::map<COutPoint, CInPoint> mapNextTx;
1867 bool accept(CTxDB& txdb, CTransaction &tx,
1868 bool fCheckInputs, bool* pfMissingInputs);
1869 bool addUnchecked(CTransaction &tx);
1870 bool remove(CTransaction &tx);
1872 unsigned long size()
1875 return mapTx.size();
1878 bool exists(uint256 hash)
1880 return (mapTx.count(hash) != 0);
1883 CTransaction& lookup(uint256 hash)
1889 extern CTxMemPool mempool;