1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
8 #include "timestamps.h"
14 #include "zerocoin/Zerocoin.h"
27 class CRequestTracker;
30 static const unsigned int MAX_BLOCK_SIZE = 1000000;
31 static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/2;
32 static const unsigned int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
33 static const unsigned int MAX_ORPHAN_TRANSACTIONS = MAX_BLOCK_SIZE/100;
34 static const unsigned int MAX_INV_SZ = 50000;
36 static const int64 MIN_TX_FEE = CENT/10;
37 static const int64 MIN_RELAY_TX_FEE = CENT/50;
39 static const int64 MAX_MONEY = 2000000000 * COIN;
40 static const int64 MAX_MINT_PROOF_OF_WORK = 100 * COIN;
41 static const int64 MAX_MINT_PROOF_OF_STAKE = 1 * COIN;
42 static const int64 MIN_TXOUT_AMOUNT = CENT/100;
44 inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
45 // Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp.
46 static const unsigned int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC
49 static const int fHaveUPnP = true;
51 static const int fHaveUPnP = false;
54 static const uint256 hashGenesisBlock("0x00000a060336cbb72fe969666d337b87198b1add2abaa59cca226820b32933a4");
55 static const uint256 hashGenesisBlockTestNet("0x000c763e402f2436da9ed36c7286f62c3f6e5dbafce9ff289bd43d7459327eb");
57 inline int64 PastDrift(int64 nTime) { return nTime - 2 * 60 * 60; } // up to 2 hours from the past
58 inline int64 FutureDrift(int64 nTime) { return nTime + 2 * 60 * 60; } // up to 2 hours from the future
60 extern libzerocoin::Params* ZCParams;
61 extern CScript COINBASE_FLAGS;
62 extern CCriticalSection cs_main;
63 extern std::map<uint256, CBlockIndex*> mapBlockIndex;
64 extern std::set<std::pair<COutPoint, unsigned int> > setStakeSeen;
65 extern CBlockIndex* pindexGenesisBlock;
66 extern unsigned int nStakeMinAge;
67 extern unsigned int nNodeLifespan;
68 extern int nCoinbaseMaturity;
69 extern int nBestHeight;
70 extern uint256 nBestChainTrust;
71 extern uint256 nBestInvalidTrust;
72 extern uint256 hashBestChain;
73 extern CBlockIndex* pindexBest;
74 extern unsigned int nTransactionsUpdated;
75 extern uint64 nLastBlockTx;
76 extern uint64 nLastBlockSize;
77 extern int64 nLastCoinStakeSearchInterval;
78 extern const std::string strMessageMagic;
79 extern int64 nTimeBestReceived;
80 extern CCriticalSection cs_setpwalletRegistered;
81 extern std::set<CWallet*> setpwalletRegistered;
82 extern unsigned char pchMessageStart[4];
83 extern std::map<uint256, CBlock*> mapOrphanBlocks;
86 extern int64 nTransactionFee;
87 extern int64 nMinimumInputValue;
88 extern bool fUseFastIndex;
89 extern unsigned int nDerivationMethodIndex;
91 // Minimum disk space required - used in CheckDiskSpace()
92 static const uint64 nMinDiskSpace = 52428800;
98 void RegisterWallet(CWallet* pwalletIn);
99 void UnregisterWallet(CWallet* pwalletIn);
100 void SyncWithWallets(const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false, bool fConnect = true);
101 bool ProcessBlock(CNode* pfrom, CBlock* pblock);
102 bool CheckDiskSpace(uint64 nAdditionalBytes=0);
103 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
104 FILE* AppendBlockFile(unsigned int& nFileRet);
105 bool LoadBlockIndex(bool fAllowNew=true);
106 void PrintBlockTree();
107 CBlockIndex* FindBlockByHeight(int nHeight);
108 bool ProcessMessages(CNode* pfrom);
109 bool SendMessages(CNode* pto, bool fSendTrickle);
110 bool LoadExternalBlockFile(FILE* fileIn);
112 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
113 unsigned int GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake);
114 int64 GetProofOfWorkReward(unsigned int nBits, int64 nFees=0);
115 int64 GetProofOfStakeReward(int64 nCoinAge, unsigned int nBits, unsigned int nTime, bool bCoinYearOnly=false);
116 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime);
117 unsigned int ComputeMinStake(unsigned int nBase, int64 nTime, unsigned int nBlockTime);
118 int GetNumBlocksOfPeers();
119 bool IsInitialBlockDownload();
120 std::string GetWarnings(std::string strFor);
121 bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock);
122 uint256 WantedByOrphan(const CBlock* pblockOrphan);
123 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake);
124 void StakeMiner(CWallet *pwallet);
125 void ResendWalletTransactions();
127 bool VerifySignature(const CTransaction& txFrom, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType);
135 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
137 /** Position on disk for a particular transaction. */
142 unsigned int nBlockPos;
150 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
153 nBlockPos = nBlockPosIn;
157 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
158 void SetNull() { nFile = (unsigned int) -1; nBlockPos = 0; nTxPos = 0; }
159 bool IsNull() const { return (nFile == (unsigned int) -1); }
161 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
163 return (a.nFile == b.nFile &&
164 a.nBlockPos == b.nBlockPos &&
165 a.nTxPos == b.nTxPos);
168 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
174 std::string ToString() const
179 return strprintf("(nFile=%u, nBlockPos=%u, nTxPos=%u)", 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 = (unsigned int) -1; }
200 bool IsNull() const { return (ptx == NULL && n == (unsigned int) -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 = (unsigned int) -1; }
216 bool IsNull() const { return (hash == 0 && n == (unsigned int) -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, %u)", 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.
431 static const int CURRENT_VERSION=1;
434 std::vector<CTxIn> vin;
435 std::vector<CTxOut> vout;
436 unsigned int nLockTime;
438 // Denial-of-service detection:
440 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
449 READWRITE(this->nVersion);
450 nVersion = this->nVersion;
454 READWRITE(nLockTime);
459 nVersion = CTransaction::CURRENT_VERSION;
460 nTime = GetAdjustedTime();
464 nDoS = 0; // Denial-of-service prevention
469 return (vin.empty() && vout.empty());
472 uint256 GetHash() const
474 return SerializeHash(*this);
477 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
479 // Time based nLockTime implemented in 0.1.6
482 if (nBlockHeight == 0)
483 nBlockHeight = nBestHeight;
485 nBlockTime = GetAdjustedTime();
486 if ((int64)nLockTime < ((int64)nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
488 BOOST_FOREACH(const CTxIn& txin, vin)
494 bool IsNewerThan(const CTransaction& old) const
496 if (vin.size() != old.vin.size())
498 for (unsigned int i = 0; i < vin.size(); i++)
499 if (vin[i].prevout != old.vin[i].prevout)
503 unsigned int nLowest = std::numeric_limits<unsigned int>::max();
504 for (unsigned int i = 0; i < vin.size(); i++)
506 if (vin[i].nSequence != old.vin[i].nSequence)
508 if (vin[i].nSequence <= nLowest)
511 nLowest = vin[i].nSequence;
513 if (old.vin[i].nSequence < nLowest)
516 nLowest = old.vin[i].nSequence;
523 bool IsCoinBase() const
525 return (vin.size() == 1 && vin[0].prevout.IsNull() && vout.size() >= 1);
528 bool IsCoinStake() const
530 // ppcoin: the coin stake transaction is marked with the first output empty
531 return (vin.size() > 0 && (!vin[0].prevout.IsNull()) && vout.size() >= 2 && vout[0].IsEmpty());
534 /** Check for standard transaction types
535 @return True if all outputs (scriptPubKeys) use only standard transaction forms
537 bool IsStandard() const;
539 /** Check for standard transaction types
540 @param[in] mapInputs Map of previous transactions that have outputs we're spending
541 @return True if all inputs (scriptSigs) use only standard transaction forms
542 @see CTransaction::FetchInputs
544 bool AreInputsStandard(const MapPrevTx& mapInputs) const;
546 /** Count ECDSA signature operations the old-fashioned (pre-0.6) way
547 @return number of sigops this transaction's outputs will produce when spent
548 @see CTransaction::FetchInputs
550 unsigned int GetLegacySigOpCount() const;
552 /** Count ECDSA signature operations in pay-to-script-hash inputs.
554 @param[in] mapInputs Map of previous transactions that have outputs we're spending
555 @return maximum number of sigops required to validate this transaction's inputs
556 @see CTransaction::FetchInputs
558 unsigned int GetP2SHSigOpCount(const MapPrevTx& mapInputs) const;
560 /** Amount of bitcoins spent by this transaction.
561 @return sum of all outputs (note: does not include fees)
563 int64 GetValueOut() const
566 BOOST_FOREACH(const CTxOut& txout, vout)
568 nValueOut += txout.nValue;
569 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
570 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
575 /** Amount of bitcoins coming in to this transaction
576 Note that lightweight clients may not know anything besides the hash of previous transactions,
577 so may not be able to calculate this.
579 @param[in] mapInputs Map of previous transactions that have outputs we're spending
580 @return Sum of value of all inputs (scriptSigs)
581 @see CTransaction::FetchInputs
583 int64 GetValueIn(const MapPrevTx& mapInputs) const;
585 static bool AllowFree(double dPriority)
587 // Large (in bytes) low-priority (new, small-coin) transactions
589 return dPriority > COIN * 144 / 250;
592 int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=false, enum GetMinFee_mode mode=GMF_BLOCK, unsigned int nBytes = 0) const;
594 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
596 CAutoFile filein = CAutoFile(OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb"), SER_DISK, CLIENT_VERSION);
598 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
601 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
602 return error("CTransaction::ReadFromDisk() : fseek failed");
607 catch (std::exception &e) {
608 return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
611 // Return file pointer
614 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
615 return error("CTransaction::ReadFromDisk() : second fseek failed");
616 *pfileRet = filein.release();
621 friend bool operator==(const CTransaction& a, const CTransaction& b)
623 return (a.nVersion == b.nVersion &&
624 a.nTime == b.nTime &&
627 a.nLockTime == b.nLockTime);
630 friend bool operator!=(const CTransaction& a, const CTransaction& b)
635 std::string ToStringShort() const
638 str += strprintf("%s %s", GetHash().ToString().c_str(), IsCoinBase()? "base" : (IsCoinStake()? "stake" : "user"));
642 std::string ToString() const
645 str += IsCoinBase()? "Coinbase" : (IsCoinStake()? "Coinstake" : "CTransaction");
646 str += strprintf("(hash=%s, nTime=%d, ver=%d, vin.size=%"PRIszu", vout.size=%"PRIszu", nLockTime=%d)\n",
647 GetHash().ToString().substr(0,10).c_str(),
653 for (unsigned int i = 0; i < vin.size(); i++)
654 str += " " + vin[i].ToString() + "\n";
655 for (unsigned int i = 0; i < vout.size(); i++)
656 str += " " + vout[i].ToString() + "\n";
662 printf("%s", ToString().c_str());
666 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
667 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
668 bool ReadFromDisk(COutPoint prevout);
669 bool DisconnectInputs(CTxDB& txdb);
671 /** Fetch from memory and/or disk. inputsRet keys are transaction hashes.
673 @param[in] txdb Transaction database
674 @param[in] mapTestPool List of pending changes to the transaction index database
675 @param[in] fBlock True if being called to add a new best-block to the chain
676 @param[in] fMiner True if being called by CreateNewBlock
677 @param[out] inputsRet Pointers to this transaction's inputs
678 @param[out] fInvalid returns true if transaction is invalid
679 @return Returns true if all inputs are in txdb or mapTestPool
681 bool FetchInputs(CTxDB& txdb, const std::map<uint256, CTxIndex>& mapTestPool,
682 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid);
684 /** Sanity check previous transactions, then, if all checks succeed,
685 mark them as spent by this transaction.
687 @param[in] inputs Previous transactions (from FetchInputs)
688 @param[out] mapTestPool Keeps track of inputs that need to be updated on disk
689 @param[in] posThisTx Position of this transaction on disk
690 @param[in] pindexBlock
691 @param[in] fBlock true if called from ConnectBlock
692 @param[in] fMiner true if called from CreateNewBlock
693 @param[in] fStrictPayToScriptHash true if fully validating p2sh transactions
694 @return Returns true if all checks succeed
696 bool ConnectInputs(CTxDB& txdb, MapPrevTx inputs,
697 std::map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
698 const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, unsigned int flags=STANDARD_SCRIPT_VERIFY_FLAGS);
699 bool ClientConnectInputs();
700 bool CheckTransaction() const;
701 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
702 bool GetCoinAge(CTxDB& txdb, uint64& nCoinAge) const; // ppcoin: get transaction coin age
705 const CTxOut& GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const;
708 /** Closure representing one script verification
709 * Note that this stores references to the spending transaction */
713 CScript scriptPubKey;
714 const CTransaction *ptxTo;
721 CScriptCheck(const CTransaction& txFromIn, const CTransaction& txToIn, unsigned int nInIn, unsigned int nFlagsIn, int nHashTypeIn) :
722 scriptPubKey(txFromIn.vout[txToIn.vin[nInIn].prevout.n].scriptPubKey),
723 ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn), nHashType(nHashTypeIn) { }
725 bool operator()() const;
727 void swap(CScriptCheck &check) {
728 scriptPubKey.swap(check.scriptPubKey);
729 std::swap(ptxTo, check.ptxTo);
730 std::swap(nIn, check.nIn);
731 std::swap(nFlags, check.nFlags);
732 std::swap(nHashType, check.nHashType);
739 /** A transaction with a merkle branch linking it to the block chain. */
740 class CMerkleTx : public CTransaction
744 std::vector<uint256> vMerkleBranch;
748 mutable bool fMerkleVerified;
756 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
765 fMerkleVerified = false;
771 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
772 nVersion = this->nVersion;
773 READWRITE(hashBlock);
774 READWRITE(vMerkleBranch);
779 int SetMerkleBranch(const CBlock* pblock=NULL);
780 int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
781 int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
782 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
783 int GetBlocksToMaturity() const;
784 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
785 bool AcceptToMemoryPool();
791 /** A txdb record that contains the disk location of a transaction and the
792 * locations of transactions that spend its outputs. vSpent is really only
793 * used as a flag, but having the location is very helpful for debugging.
799 std::vector<CDiskTxPos> vSpent;
806 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
809 vSpent.resize(nOutputs);
814 if (!(nType & SER_GETHASH))
831 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
833 return (a.pos == b.pos &&
834 a.vSpent == b.vSpent);
837 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
841 int GetDepthInMainChain() const;
849 /** Nodes collect new transactions into a block, hash them into a hash tree,
850 * and scan through nonce values to make the block's hash satisfy proof-of-work
851 * requirements. When they solve the proof-of-work, they broadcast the block
852 * to everyone and the block is added to the block chain. The first transaction
853 * in the block is a special one that creates a new coin owned by the creator
856 * Blocks are appended to blk0001.dat files on disk. Their location on disk
857 * is indexed by CBlockIndex objects in memory.
863 static const int CURRENT_VERSION=6;
865 uint256 hashPrevBlock;
866 uint256 hashMerkleRoot;
872 std::vector<CTransaction> vtx;
874 // ppcoin: block signature - signed by one of the coin base txout[N]'s owner
875 std::vector<unsigned char> vchBlockSig;
878 mutable std::vector<uint256> vMerkleTree;
880 // Denial-of-service detection:
882 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
891 READWRITE(this->nVersion);
892 nVersion = this->nVersion;
893 READWRITE(hashPrevBlock);
894 READWRITE(hashMerkleRoot);
899 // ConnectBlock depends on vtx following header to generate CDiskTxPos
900 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
903 READWRITE(vchBlockSig);
907 const_cast<CBlock*>(this)->vtx.clear();
908 const_cast<CBlock*>(this)->vchBlockSig.clear();
914 nVersion = CBlock::CURRENT_VERSION;
931 uint256 GetHash() const
933 return scrypt_blockhash(CVOIDBEGIN(nVersion));
936 int64 GetBlockTime() const
941 void UpdateTime(const CBlockIndex* pindexPrev);
943 // ppcoin: entropy bit for stake modifier if chosen by modifier
944 unsigned int GetStakeEntropyBit(unsigned int nTime) const
946 // Protocol switch to support p2pool at novacoin block #9689
947 if (nTime >= ENTROPY_SWITCH_TIME || fTestNet)
949 // Take last bit of block hash as entropy bit
950 unsigned int nEntropyBit = ((GetHash().Get64()) & 1llu);
951 if (fDebug && GetBoolArg("-printstakemodifier"))
952 printf("GetStakeEntropyBit: nTime=%u hashBlock=%s nEntropyBit=%u\n", nTime, GetHash().ToString().c_str(), nEntropyBit);
955 // Before novacoin block #9689 - old protocol
956 uint160 hashSig = Hash160(vchBlockSig);
957 if (fDebug && GetBoolArg("-printstakemodifier"))
958 printf("GetStakeEntropyBit: hashSig=%s", hashSig.ToString().c_str());
959 hashSig >>= 159; // take the first bit of the hash
960 if (fDebug && GetBoolArg("-printstakemodifier"))
961 printf(" entropybit=%"PRI64d"\n", hashSig.Get64());
962 return hashSig.Get64();
965 // ppcoin: two types of block: proof-of-work or proof-of-stake
966 bool IsProofOfStake() const
968 return (vtx.size() > 1 && vtx[1].IsCoinStake());
971 bool IsProofOfWork() const
973 return !IsProofOfStake();
976 std::pair<COutPoint, unsigned int> GetProofOfStake() const
978 return IsProofOfStake()? std::make_pair(vtx[1].vin[0].prevout, vtx[1].nTime) : std::make_pair(COutPoint(), (unsigned int)0);
981 // ppcoin: get max transaction timestamp
982 int64 GetMaxTransactionTime() const
984 int64 maxTransactionTime = 0;
985 BOOST_FOREACH(const CTransaction& tx, vtx)
986 maxTransactionTime = std::max(maxTransactionTime, (int64)tx.nTime);
987 return maxTransactionTime;
990 uint256 BuildMerkleTree() const
993 BOOST_FOREACH(const CTransaction& tx, vtx)
994 vMerkleTree.push_back(tx.GetHash());
996 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
998 for (int i = 0; i < nSize; i += 2)
1000 int i2 = std::min(i+1, nSize-1);
1001 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
1002 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
1006 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
1009 std::vector<uint256> GetMerkleBranch(int nIndex) const
1011 if (vMerkleTree.empty())
1013 std::vector<uint256> vMerkleBranch;
1015 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1017 int i = std::min(nIndex^1, nSize-1);
1018 vMerkleBranch.push_back(vMerkleTree[j+i]);
1022 return vMerkleBranch;
1025 static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
1029 BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
1032 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
1034 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
1041 bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
1043 // Open history file to append
1044 CAutoFile fileout = CAutoFile(AppendBlockFile(nFileRet), SER_DISK, CLIENT_VERSION);
1046 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
1048 // Write index header
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)
1062 FileCommit(fileout);
1067 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
1071 // Open history file to read
1072 CAutoFile filein = CAutoFile(OpenBlockFile(nFile, nBlockPos, "rb"), SER_DISK, CLIENT_VERSION);
1074 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1075 if (!fReadTransactions)
1076 filein.nType |= SER_BLOCKHEADERONLY;
1082 catch (std::exception &e) {
1083 return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
1087 if (fReadTransactions && IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
1088 return error("CBlock::ReadFromDisk() : errors in block header");
1097 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%"PRIszu", vchBlockSig=%s)\n",
1098 GetHash().ToString().c_str(),
1100 hashPrevBlock.ToString().c_str(),
1101 hashMerkleRoot.ToString().c_str(),
1102 nTime, nBits, nNonce,
1104 HexStr(vchBlockSig.begin(), vchBlockSig.end()).c_str());
1105 for (unsigned int i = 0; i < vtx.size(); i++)
1110 printf(" vMerkleTree: ");
1111 for (unsigned int i = 0; i < vMerkleTree.size(); i++)
1112 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1117 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1118 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck=false);
1119 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1120 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1121 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1122 bool CheckBlock(bool fCheckPOW=true, bool fCheckMerkleRoot=true, bool fCheckSig=true) const;
1124 bool GetCoinAge(uint64& nCoinAge) const; // ppcoin: calculate total coin age spent in block
1125 bool SignBlock(CWallet& keystore);
1126 bool CheckBlockSignature(bool fProofOfStake) const;
1129 bool SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew);
1137 /** The block chain is a tree shaped structure starting with the
1138 * genesis block at the root, with each block potentially having multiple
1139 * candidates to be the next block. pprev and pnext link a path through the
1140 * main/longest chain. A blockindex may have multiple pprev pointing back
1141 * to it, but pnext will only point forward to the longest branch, or will
1142 * be null if the block is not part of the longest chain.
1147 const uint256* phashBlock;
1151 unsigned int nBlockPos;
1152 uint256 nChainTrust; // ppcoin: trust score of block chain
1158 unsigned int nFlags; // ppcoin: block index flags
1161 BLOCK_PROOF_OF_STAKE = (1 << 0), // is proof-of-stake block
1162 BLOCK_STAKE_ENTROPY = (1 << 1), // entropy bit for stake modifier
1163 BLOCK_STAKE_MODIFIER = (1 << 2), // regenerated stake modifier
1166 uint64 nStakeModifier; // hash modifier for proof-of-stake
1167 unsigned int nStakeModifierChecksum; // checksum of index; in-memeory only
1169 // proof-of-stake specific fields
1170 COutPoint prevoutStake;
1171 unsigned int nStakeTime;
1172 uint256 hashProofOfStake;
1176 uint256 hashMerkleRoot;
1179 unsigned int nNonce;
1194 nStakeModifierChecksum = 0;
1195 hashProofOfStake = 0;
1196 prevoutStake.SetNull();
1206 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1212 nBlockPos = nBlockPosIn;
1219 nStakeModifierChecksum = 0;
1220 hashProofOfStake = 0;
1221 if (block.IsProofOfStake())
1224 prevoutStake = block.vtx[1].vin[0].prevout;
1225 nStakeTime = block.vtx[1].nTime;
1229 prevoutStake.SetNull();
1233 nVersion = block.nVersion;
1234 hashMerkleRoot = block.hashMerkleRoot;
1235 nTime = block.nTime;
1236 nBits = block.nBits;
1237 nNonce = block.nNonce;
1240 CBlock GetBlockHeader() const
1243 block.nVersion = nVersion;
1245 block.hashPrevBlock = pprev->GetBlockHash();
1246 block.hashMerkleRoot = hashMerkleRoot;
1247 block.nTime = nTime;
1248 block.nBits = nBits;
1249 block.nNonce = nNonce;
1253 uint256 GetBlockHash() const
1258 int64 GetBlockTime() const
1260 return (int64)nTime;
1263 uint256 GetBlockTrust() const;
1265 bool IsInMainChain() const
1267 return (pnext || this == pindexBest);
1270 bool CheckIndex() const
1275 enum { nMedianTimeSpan=11 };
1277 int64 GetMedianTimePast() const
1279 int64 pmedian[nMedianTimeSpan];
1280 int64* pbegin = &pmedian[nMedianTimeSpan];
1281 int64* pend = &pmedian[nMedianTimeSpan];
1283 const CBlockIndex* pindex = this;
1284 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1285 *(--pbegin) = pindex->GetBlockTime();
1287 std::sort(pbegin, pend);
1288 return pbegin[(pend - pbegin)/2];
1291 int64 GetMedianTime() const
1293 const CBlockIndex* pindex = this;
1294 for (int i = 0; i < nMedianTimeSpan/2; i++)
1297 return GetBlockTime();
1298 pindex = pindex->pnext;
1300 return pindex->GetMedianTimePast();
1304 * Returns true if there are nRequired or more blocks of minVersion or above
1305 * in the last nToCheck blocks, starting at pstart and going backwards.
1307 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart,
1308 unsigned int nRequired, unsigned int nToCheck);
1311 bool IsProofOfWork() const
1313 return !(nFlags & BLOCK_PROOF_OF_STAKE);
1316 bool IsProofOfStake() const
1318 return (nFlags & BLOCK_PROOF_OF_STAKE);
1321 void SetProofOfStake()
1323 nFlags |= BLOCK_PROOF_OF_STAKE;
1326 unsigned int GetStakeEntropyBit() const
1328 return ((nFlags & BLOCK_STAKE_ENTROPY) >> 1);
1331 bool SetStakeEntropyBit(unsigned int nEntropyBit)
1333 if (nEntropyBit > 1)
1335 nFlags |= (nEntropyBit? BLOCK_STAKE_ENTROPY : 0);
1339 bool GeneratedStakeModifier() const
1341 return (nFlags & BLOCK_STAKE_MODIFIER);
1344 void SetStakeModifier(uint64 nModifier, bool fGeneratedStakeModifier)
1346 nStakeModifier = nModifier;
1347 if (fGeneratedStakeModifier)
1348 nFlags |= BLOCK_STAKE_MODIFIER;
1351 std::string ToString() const
1353 return strprintf("CBlockIndex(nprev=%p, pnext=%p, nFile=%u, 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)",
1354 pprev, pnext, nFile, nBlockPos, nHeight,
1355 FormatMoney(nMint).c_str(), FormatMoney(nMoneySupply).c_str(),
1356 GeneratedStakeModifier() ? "MOD" : "-", GetStakeEntropyBit(), IsProofOfStake()? "PoS" : "PoW",
1357 nStakeModifier, nStakeModifierChecksum,
1358 hashProofOfStake.ToString().c_str(),
1359 prevoutStake.ToString().c_str(), nStakeTime,
1360 hashMerkleRoot.ToString().c_str(),
1361 GetBlockHash().ToString().c_str());
1366 printf("%s\n", ToString().c_str());
1372 /** Used to marshal pointers into hashes for db storage. */
1373 class CDiskBlockIndex : public CBlockIndex
1389 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1391 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1392 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1397 if (!(nType & SER_GETHASH))
1398 READWRITE(nVersion);
1400 READWRITE(hashNext);
1402 READWRITE(nBlockPos);
1405 READWRITE(nMoneySupply);
1407 READWRITE(nStakeModifier);
1408 if (IsProofOfStake())
1410 READWRITE(prevoutStake);
1411 READWRITE(nStakeTime);
1412 READWRITE(hashProofOfStake);
1416 const_cast<CDiskBlockIndex*>(this)->prevoutStake.SetNull();
1417 const_cast<CDiskBlockIndex*>(this)->nStakeTime = 0;
1418 const_cast<CDiskBlockIndex*>(this)->hashProofOfStake = 0;
1422 READWRITE(this->nVersion);
1423 READWRITE(hashPrev);
1424 READWRITE(hashMerkleRoot);
1428 READWRITE(blockHash);
1431 uint256 GetBlockHash() const
1433 if (fUseFastIndex && (nTime < GetAdjustedTime() - 24 * 60 * 60) && blockHash != 0)
1437 block.nVersion = nVersion;
1438 block.hashPrevBlock = hashPrev;
1439 block.hashMerkleRoot = hashMerkleRoot;
1440 block.nTime = nTime;
1441 block.nBits = nBits;
1442 block.nNonce = nNonce;
1444 const_cast<CDiskBlockIndex*>(this)->blockHash = block.GetHash();
1449 std::string ToString() const
1451 std::string str = "CDiskBlockIndex(";
1452 str += CBlockIndex::ToString();
1453 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1454 GetBlockHash().ToString().c_str(),
1455 hashPrev.ToString().c_str(),
1456 hashNext.ToString().c_str());
1462 printf("%s\n", ToString().c_str());
1473 /** Describes a place in the block chain to another node such that if the
1474 * other node doesn't have the same branch, it can find a recent common trunk.
1475 * The further back it is, the further before the fork it may be.
1480 std::vector<uint256> vHave;
1487 explicit CBlockLocator(const CBlockIndex* pindex)
1492 explicit CBlockLocator(uint256 hashBlock)
1494 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1495 if (mi != mapBlockIndex.end())
1499 CBlockLocator(const std::vector<uint256>& vHaveIn)
1506 if (!(nType & SER_GETHASH))
1507 READWRITE(nVersion);
1518 return vHave.empty();
1521 void Set(const CBlockIndex* pindex)
1527 vHave.push_back(pindex->GetBlockHash());
1529 // Exponentially larger steps back
1530 for (int i = 0; pindex && i < nStep; i++)
1531 pindex = pindex->pprev;
1532 if (vHave.size() > 10)
1535 vHave.push_back((!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
1538 int GetDistanceBack()
1540 // Retrace how far back it was in the sender's branch
1543 BOOST_FOREACH(const uint256& hash, vHave)
1545 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1546 if (mi != mapBlockIndex.end())
1548 CBlockIndex* pindex = (*mi).second;
1549 if (pindex->IsInMainChain())
1559 CBlockIndex* GetBlockIndex()
1561 // Find the first block the caller has in the main chain
1562 BOOST_FOREACH(const uint256& hash, vHave)
1564 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1565 if (mi != mapBlockIndex.end())
1567 CBlockIndex* pindex = (*mi).second;
1568 if (pindex->IsInMainChain())
1572 return pindexGenesisBlock;
1575 uint256 GetBlockHash()
1577 // Find the first block the caller has in the main chain
1578 BOOST_FOREACH(const uint256& hash, vHave)
1580 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1581 if (mi != mapBlockIndex.end())
1583 CBlockIndex* pindex = (*mi).second;
1584 if (pindex->IsInMainChain())
1588 return (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet);
1593 CBlockIndex* pindex = GetBlockIndex();
1596 return pindex->nHeight;
1610 mutable CCriticalSection cs;
1611 std::map<uint256, CTransaction> mapTx;
1612 std::map<COutPoint, CInPoint> mapNextTx;
1614 bool accept(CTxDB& txdb, CTransaction &tx,
1615 bool fCheckInputs, bool* pfMissingInputs);
1616 bool addUnchecked(const uint256& hash, CTransaction &tx);
1617 bool remove(CTransaction &tx);
1619 void queryHashes(std::vector<uint256>& vtxid);
1621 unsigned long size()
1624 return mapTx.size();
1627 bool exists(uint256 hash)
1629 return (mapTx.count(hash) != 0);
1632 CTransaction& lookup(uint256 hash)
1638 extern CTxMemPool mempool;