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.
10 #include "timestamps.h"
16 #include "zerocoin/Zerocoin.h"
29 class CRequestTracker;
35 static unsigned int nStakeMinAge = 60 * 60 * 24 * 30; // 30 days as zero time weight
36 static unsigned int nStakeMaxAge = 60 * 60 * 24 * 90; // 90 days as full weight
37 static unsigned int nStakeTargetSpacing = 10 * 60; // 10-minute stakes spacing
38 static unsigned int nModifierInterval = 6 * 60 * 60; // time to elapse before new modifier is computed
40 static int nCoinbaseMaturity = 500;
43 static const unsigned int MAX_BLOCK_SIZE = 1000000;
44 static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/2;
45 static const unsigned int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
46 static const unsigned int MAX_ORPHAN_TRANSACTIONS = MAX_BLOCK_SIZE/100;
47 static const unsigned int MAX_INV_SZ = 50000;
49 static const int64 MIN_TX_FEE = CENT/10;
50 static const int64 MIN_RELAY_TX_FEE = CENT/50;
52 static const int64 MAX_MONEY = 2000000000 * COIN;
53 static const int64 MAX_MINT_PROOF_OF_WORK = 100 * COIN;
54 static const int64 MAX_MINT_PROOF_OF_STAKE = 1 * COIN;
55 static const int64 MIN_TXOUT_AMOUNT = CENT/100;
57 inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
58 // Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp.
59 static const unsigned int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC
60 // Maximum number of script-checking threads allowed
61 static const int MAX_SCRIPTCHECK_THREADS = 16;
64 static const int fHaveUPnP = true;
66 static const int fHaveUPnP = false;
69 static const uint256 hashGenesisBlock("0x00000a060336cbb72fe969666d337b87198b1add2abaa59cca226820b32933a4");
70 static const uint256 hashGenesisBlockTestNet("0x000c763e402f2436da9ed36c7286f62c3f6e5dbafce9ff289bd43d7459327eb");
72 inline int64 PastDrift(int64 nTime) { return nTime - 2 * 60 * 60; } // up to 2 hours from the past
73 inline int64 FutureDrift(int64 nTime) { return nTime + 2 * 60 * 60; } // up to 2 hours from the future
75 extern libzerocoin::Params* ZCParams;
76 extern CScript COINBASE_FLAGS;
77 extern CCriticalSection cs_main;
78 extern std::map<uint256, CBlockIndex*> mapBlockIndex;
79 extern std::set<std::pair<COutPoint, unsigned int> > setStakeSeen;
80 extern CBlockIndex* pindexGenesisBlock;
81 extern unsigned int nStakeMinAge;
82 extern unsigned int nNodeLifespan;
83 extern int nCoinbaseMaturity;
84 extern int nBestHeight;
85 extern uint256 nBestChainTrust;
86 extern uint256 nBestInvalidTrust;
87 extern uint256 hashBestChain;
88 extern CBlockIndex* pindexBest;
89 extern unsigned int nTransactionsUpdated;
90 extern uint64 nLastBlockTx;
91 extern uint64 nLastBlockSize;
92 extern int64 nLastCoinStakeSearchInterval;
93 extern const std::string strMessageMagic;
94 extern int64 nTimeBestReceived;
95 extern CCriticalSection cs_setpwalletRegistered;
96 extern std::set<CWallet*> setpwalletRegistered;
97 extern unsigned char pchMessageStart[4];
98 extern std::map<uint256, CBlock*> mapOrphanBlocks;
101 extern int64 nTransactionFee;
102 extern int64 nMinimumInputValue;
103 extern bool fUseFastIndex;
104 extern unsigned int nDerivationMethodIndex;
105 extern int nScriptCheckThreads;
107 // Minimum disk space required - used in CheckDiskSpace()
108 static const uint64 nMinDiskSpace = 52428800;
115 void RegisterWallet(CWallet* pwalletIn);
116 void UnregisterWallet(CWallet* pwalletIn);
117 void SyncWithWallets(const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false, bool fConnect = true);
118 bool ProcessBlock(CNode* pfrom, CBlock* pblock);
119 bool CheckDiskSpace(uint64 nAdditionalBytes=0);
120 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
121 FILE* AppendBlockFile(unsigned int& nFileRet);
122 bool LoadBlockIndex(bool fAllowNew=true);
123 void PrintBlockTree();
124 CBlockIndex* FindBlockByHeight(int nHeight);
125 bool ProcessMessages(CNode* pfrom);
126 bool SendMessages(CNode* pto, bool fSendTrickle);
127 bool LoadExternalBlockFile(FILE* fileIn);
129 // Run an instance of the script checking thread
130 void ThreadScriptCheck(void* parg);
131 // Stop the script checking threads
132 void ThreadScriptCheckQuit();
134 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
135 unsigned int GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake);
136 int64 GetProofOfWorkReward(unsigned int nBits, int64 nFees=0);
137 int64 GetProofOfStakeReward(int64 nCoinAge, unsigned int nBits, unsigned int nTime, bool bCoinYearOnly=false);
138 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime);
139 unsigned int ComputeMinStake(unsigned int nBase, int64 nTime, unsigned int nBlockTime);
140 int GetNumBlocksOfPeers();
141 bool IsInitialBlockDownload();
142 std::string GetWarnings(std::string strFor);
143 bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock);
144 uint256 WantedByOrphan(const CBlock* pblockOrphan);
145 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake);
146 void StakeMiner(CWallet *pwallet);
147 void ResendWalletTransactions();
149 bool VerifySignature(const CTransaction& txFrom, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType);
157 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
159 /** Position on disk for a particular transaction. */
164 unsigned int nBlockPos;
172 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
175 nBlockPos = nBlockPosIn;
179 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
180 void SetNull() { nFile = (unsigned int) -1; nBlockPos = 0; nTxPos = 0; }
181 bool IsNull() const { return (nFile == (unsigned int) -1); }
183 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
185 return (a.nFile == b.nFile &&
186 a.nBlockPos == b.nBlockPos &&
187 a.nTxPos == b.nTxPos);
190 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
196 std::string ToString() const
201 return strprintf("(nFile=%u, nBlockPos=%u, nTxPos=%u)", nFile, nBlockPos, nTxPos);
206 printf("%s", ToString().c_str());
212 /** An inpoint - a combination of a transaction and an index n into its vin */
219 CInPoint() { SetNull(); }
220 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
221 void SetNull() { ptx = NULL; n = (unsigned int) -1; }
222 bool IsNull() const { return (ptx == NULL && n == (unsigned int) -1); }
227 /** An outpoint - a combination of a transaction hash and an index n into its vout */
234 COutPoint() { SetNull(); }
235 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
236 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
237 void SetNull() { hash = 0; n = (unsigned int) -1; }
238 bool IsNull() const { return (hash == 0 && n == (unsigned int) -1); }
240 friend bool operator<(const COutPoint& a, const COutPoint& b)
242 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
245 friend bool operator==(const COutPoint& a, const COutPoint& b)
247 return (a.hash == b.hash && a.n == b.n);
250 friend bool operator!=(const COutPoint& a, const COutPoint& b)
255 std::string ToString() const
257 return strprintf("COutPoint(%s, %u)", hash.ToString().substr(0,10).c_str(), n);
262 printf("%s\n", ToString().c_str());
269 /** An input of a transaction. It contains the location of the previous
270 * transaction's output that it claims and a signature that matches the
271 * output's public key.
278 unsigned int nSequence;
282 nSequence = std::numeric_limits<unsigned int>::max();
285 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
288 scriptSig = scriptSigIn;
289 nSequence = nSequenceIn;
292 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
294 prevout = COutPoint(hashPrevTx, nOut);
295 scriptSig = scriptSigIn;
296 nSequence = nSequenceIn;
302 READWRITE(scriptSig);
303 READWRITE(nSequence);
308 return (nSequence == std::numeric_limits<unsigned int>::max());
311 friend bool operator==(const CTxIn& a, const CTxIn& b)
313 return (a.prevout == b.prevout &&
314 a.scriptSig == b.scriptSig &&
315 a.nSequence == b.nSequence);
318 friend bool operator!=(const CTxIn& a, const CTxIn& b)
323 std::string ToStringShort() const
325 return strprintf(" %s %d", prevout.hash.ToString().c_str(), prevout.n);
328 std::string ToString() const
332 str += prevout.ToString();
333 if (prevout.IsNull())
334 str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
336 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
337 if (nSequence != std::numeric_limits<unsigned int>::max())
338 str += strprintf(", nSequence=%u", nSequence);
345 printf("%s\n", ToString().c_str());
352 /** An output of a transaction. It contains the public key that the next input
353 * must be able to sign with to claim it.
359 CScript scriptPubKey;
366 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
369 scriptPubKey = scriptPubKeyIn;
375 READWRITE(scriptPubKey);
381 scriptPubKey.clear();
386 return (nValue == -1);
392 scriptPubKey.clear();
397 return (nValue == 0 && scriptPubKey.empty());
400 uint256 GetHash() const
402 return SerializeHash(*this);
405 friend bool operator==(const CTxOut& a, const CTxOut& b)
407 return (a.nValue == b.nValue &&
408 a.scriptPubKey == b.scriptPubKey);
411 friend bool operator!=(const CTxOut& a, const CTxOut& b)
416 std::string ToStringShort() const
418 return strprintf(" out %s %s", FormatMoney(nValue).c_str(), scriptPubKey.ToString(true).c_str());
421 std::string ToString() const
423 if (IsEmpty()) return "CTxOut(empty)";
424 if (scriptPubKey.size() < 6)
425 return "CTxOut(error)";
426 return strprintf("CTxOut(nValue=%s, scriptPubKey=%s)", FormatMoney(nValue).c_str(), scriptPubKey.ToString().c_str());
431 printf("%s\n", ToString().c_str());
445 typedef std::map<uint256, std::pair<CTxIndex, CTransaction> > MapPrevTx;
447 /** The basic transaction that is broadcasted on the network and contained in
448 * blocks. A transaction can contain multiple inputs and outputs.
453 static const int CURRENT_VERSION=1;
456 std::vector<CTxIn> vin;
457 std::vector<CTxOut> vout;
458 unsigned int nLockTime;
460 // Denial-of-service detection:
462 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
471 READWRITE(this->nVersion);
472 nVersion = this->nVersion;
476 READWRITE(nLockTime);
481 nVersion = CTransaction::CURRENT_VERSION;
482 nTime = GetAdjustedTime();
486 nDoS = 0; // Denial-of-service prevention
491 return (vin.empty() && vout.empty());
494 uint256 GetHash() const
496 return SerializeHash(*this);
499 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
501 // Time based nLockTime implemented in 0.1.6
504 if (nBlockHeight == 0)
505 nBlockHeight = nBestHeight;
507 nBlockTime = GetAdjustedTime();
508 if ((int64)nLockTime < ((int64)nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
510 BOOST_FOREACH(const CTxIn& txin, vin)
516 bool IsNewerThan(const CTransaction& old) const
518 if (vin.size() != old.vin.size())
520 for (unsigned int i = 0; i < vin.size(); i++)
521 if (vin[i].prevout != old.vin[i].prevout)
525 unsigned int nLowest = std::numeric_limits<unsigned int>::max();
526 for (unsigned int i = 0; i < vin.size(); i++)
528 if (vin[i].nSequence != old.vin[i].nSequence)
530 if (vin[i].nSequence <= nLowest)
533 nLowest = vin[i].nSequence;
535 if (old.vin[i].nSequence < nLowest)
538 nLowest = old.vin[i].nSequence;
545 bool IsCoinBase() const
547 return (vin.size() == 1 && vin[0].prevout.IsNull() && vout.size() >= 1);
550 bool IsCoinStake() const
552 // ppcoin: the coin stake transaction is marked with the first output empty
553 return (vin.size() > 0 && (!vin[0].prevout.IsNull()) && vout.size() >= 2 && vout[0].IsEmpty());
556 /** Check for standard transaction types
557 @return True if all outputs (scriptPubKeys) use only standard transaction forms
559 bool IsStandard() const;
561 /** Check for standard transaction types
562 @param[in] mapInputs Map of previous transactions that have outputs we're spending
563 @return True if all inputs (scriptSigs) use only standard transaction forms
564 @see CTransaction::FetchInputs
566 bool AreInputsStandard(const MapPrevTx& mapInputs) const;
568 /** Count ECDSA signature operations the old-fashioned (pre-0.6) way
569 @return number of sigops this transaction's outputs will produce when spent
570 @see CTransaction::FetchInputs
572 unsigned int GetLegacySigOpCount() const;
574 /** Count ECDSA signature operations in pay-to-script-hash inputs.
576 @param[in] mapInputs Map of previous transactions that have outputs we're spending
577 @return maximum number of sigops required to validate this transaction's inputs
578 @see CTransaction::FetchInputs
580 unsigned int GetP2SHSigOpCount(const MapPrevTx& mapInputs) const;
582 /** Amount of bitcoins spent by this transaction.
583 @return sum of all outputs (note: does not include fees)
585 int64 GetValueOut() const
588 BOOST_FOREACH(const CTxOut& txout, vout)
590 nValueOut += txout.nValue;
591 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
592 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
597 /** Amount of bitcoins coming in to this transaction
598 Note that lightweight clients may not know anything besides the hash of previous transactions,
599 so may not be able to calculate this.
601 @param[in] mapInputs Map of previous transactions that have outputs we're spending
602 @return Sum of value of all inputs (scriptSigs)
603 @see CTransaction::FetchInputs
605 int64 GetValueIn(const MapPrevTx& mapInputs) const;
607 static bool AllowFree(double dPriority)
609 // Large (in bytes) low-priority (new, small-coin) transactions
611 return dPriority > COIN * 144 / 250;
614 int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=false, enum GetMinFee_mode mode=GMF_BLOCK, unsigned int nBytes = 0) const;
616 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
618 CAutoFile filein = CAutoFile(OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb"), SER_DISK, CLIENT_VERSION);
620 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
623 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
624 return error("CTransaction::ReadFromDisk() : fseek failed");
629 catch (std::exception &e) {
630 return error("%s() : deserialize or I/O error", BOOST_CURRENT_FUNCTION);
633 // Return file pointer
636 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
637 return error("CTransaction::ReadFromDisk() : second fseek failed");
638 *pfileRet = filein.release();
643 friend bool operator==(const CTransaction& a, const CTransaction& b)
645 return (a.nVersion == b.nVersion &&
646 a.nTime == b.nTime &&
649 a.nLockTime == b.nLockTime);
652 friend bool operator!=(const CTransaction& a, const CTransaction& b)
657 std::string ToStringShort() const
660 str += strprintf("%s %s", GetHash().ToString().c_str(), IsCoinBase()? "base" : (IsCoinStake()? "stake" : "user"));
664 std::string ToString() const
667 str += IsCoinBase()? "Coinbase" : (IsCoinStake()? "Coinstake" : "CTransaction");
668 str += strprintf("(hash=%s, nTime=%d, ver=%d, vin.size=%"PRIszu", vout.size=%"PRIszu", nLockTime=%d)\n",
669 GetHash().ToString().substr(0,10).c_str(),
675 for (unsigned int i = 0; i < vin.size(); i++)
676 str += " " + vin[i].ToString() + "\n";
677 for (unsigned int i = 0; i < vout.size(); i++)
678 str += " " + vout[i].ToString() + "\n";
684 printf("%s", ToString().c_str());
688 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
689 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
690 bool ReadFromDisk(COutPoint prevout);
691 bool DisconnectInputs(CTxDB& txdb);
693 /** Fetch from memory and/or disk. inputsRet keys are transaction hashes.
695 @param[in] txdb Transaction database
696 @param[in] mapTestPool List of pending changes to the transaction index database
697 @param[in] fBlock True if being called to add a new best-block to the chain
698 @param[in] fMiner True if being called by CreateNewBlock
699 @param[out] inputsRet Pointers to this transaction's inputs
700 @param[out] fInvalid returns true if transaction is invalid
701 @return Returns true if all inputs are in txdb or mapTestPool
703 bool FetchInputs(CTxDB& txdb, const std::map<uint256, CTxIndex>& mapTestPool,
704 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid);
706 /** Sanity check previous transactions, then, if all checks succeed,
707 mark them as spent by this transaction.
709 @param[in] inputs Previous transactions (from FetchInputs)
710 @param[out] mapTestPool Keeps track of inputs that need to be updated on disk
711 @param[in] posThisTx Position of this transaction on disk
712 @param[in] pindexBlock
713 @param[in] fBlock true if called from ConnectBlock
714 @param[in] fMiner true if called from CreateNewBlock
715 @param[in] fScriptChecks enable scripts validation?
716 @param[in] flags STRICT_FLAGS script validation flags
717 @param[in] pvChecks NULL If pvChecks is not NULL, script checks are pushed onto it instead of being performed inline.
718 @return Returns true if all checks succeed
720 bool ConnectInputs(CTxDB& txdb, MapPrevTx inputs, std::map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx, const CBlockIndex* pindexBlock,
721 bool fBlock, bool fMiner, bool fScriptChecks=true,
722 unsigned int flags=STRICT_FLAGS, std::vector<CScriptCheck> *pvChecks = NULL);
723 bool ClientConnectInputs();
724 bool CheckTransaction() const;
725 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
726 bool GetCoinAge(CTxDB& txdb, uint64& nCoinAge) const; // ppcoin: get transaction coin age
729 const CTxOut& GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const;
732 /** Closure representing one script verification
733 * Note that this stores references to the spending transaction */
737 CScript scriptPubKey;
738 const CTransaction *ptxTo;
745 CScriptCheck(const CTransaction& txFromIn, const CTransaction& txToIn, unsigned int nInIn, unsigned int nFlagsIn, int nHashTypeIn) :
746 scriptPubKey(txFromIn.vout[txToIn.vin[nInIn].prevout.n].scriptPubKey),
747 ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn), nHashType(nHashTypeIn) { }
749 bool operator()() const;
751 void swap(CScriptCheck &check) {
752 scriptPubKey.swap(check.scriptPubKey);
753 std::swap(ptxTo, check.ptxTo);
754 std::swap(nIn, check.nIn);
755 std::swap(nFlags, check.nFlags);
756 std::swap(nHashType, check.nHashType);
763 /** A transaction with a merkle branch linking it to the block chain. */
764 class CMerkleTx : public CTransaction
768 std::vector<uint256> vMerkleBranch;
772 mutable bool fMerkleVerified;
780 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
789 fMerkleVerified = false;
795 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
796 nVersion = this->nVersion;
797 READWRITE(hashBlock);
798 READWRITE(vMerkleBranch);
803 int SetMerkleBranch(const CBlock* pblock=NULL);
804 int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
805 int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
806 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
807 int GetBlocksToMaturity() const;
808 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
809 bool AcceptToMemoryPool();
815 /** A txdb record that contains the disk location of a transaction and the
816 * locations of transactions that spend its outputs. vSpent is really only
817 * used as a flag, but having the location is very helpful for debugging.
823 std::vector<CDiskTxPos> vSpent;
830 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
833 vSpent.resize(nOutputs);
838 if (!(nType & SER_GETHASH))
855 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
857 return (a.pos == b.pos &&
858 a.vSpent == b.vSpent);
861 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
865 int GetDepthInMainChain() const;
873 /** Nodes collect new transactions into a block, hash them into a hash tree,
874 * and scan through nonce values to make the block's hash satisfy proof-of-work
875 * requirements. When they solve the proof-of-work, they broadcast the block
876 * to everyone and the block is added to the block chain. The first transaction
877 * in the block is a special one that creates a new coin owned by the creator
880 * Blocks are appended to blk0001.dat files on disk. Their location on disk
881 * is indexed by CBlockIndex objects in memory.
887 static const int CURRENT_VERSION=6;
889 uint256 hashPrevBlock;
890 uint256 hashMerkleRoot;
896 std::vector<CTransaction> vtx;
898 // ppcoin: block signature - signed by one of the coin base txout[N]'s owner
899 std::vector<unsigned char> vchBlockSig;
902 mutable std::vector<uint256> vMerkleTree;
904 // Denial-of-service detection:
906 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
915 READWRITE(this->nVersion);
916 nVersion = this->nVersion;
917 READWRITE(hashPrevBlock);
918 READWRITE(hashMerkleRoot);
923 // ConnectBlock depends on vtx following header to generate CDiskTxPos
924 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
927 READWRITE(vchBlockSig);
931 const_cast<CBlock*>(this)->vtx.clear();
932 const_cast<CBlock*>(this)->vchBlockSig.clear();
938 nVersion = CBlock::CURRENT_VERSION;
955 uint256 GetHash() const
957 return scrypt_blockhash(CVOIDBEGIN(nVersion));
960 int64 GetBlockTime() const
965 void UpdateTime(const CBlockIndex* pindexPrev);
967 // ppcoin: entropy bit for stake modifier if chosen by modifier
968 unsigned int GetStakeEntropyBit(unsigned int nTime) const
970 // Protocol switch to support p2pool at novacoin block #9689
971 if (nTime >= ENTROPY_SWITCH_TIME || fTestNet)
973 // Take last bit of block hash as entropy bit
974 unsigned int nEntropyBit = ((GetHash().Get64()) & 1ULL);
975 //unsigned int nEntropyBit = 1;
976 if (fDebug && GetBoolArg("-printstakemodifier"))
977 printf("GetStakeEntropyBit: nTime=%u hashBlock=%s nEntropyBit=%u\n", nTime, 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=%"PRI64d"\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 int nSize = fileout.GetSerializeSize(*this);
1075 fileout << FLATDATA(pchMessageStart) << nSize;
1078 long fileOutPos = ftell(fileout);
1080 return error("CBlock::WriteToDisk() : ftell failed");
1081 nBlockPosRet = fileOutPos;
1084 // Flush stdio buffers and commit to disk before returning
1086 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
1087 FileCommit(fileout);
1092 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
1096 // Open history file to read
1097 CAutoFile filein = CAutoFile(OpenBlockFile(nFile, nBlockPos, "rb"), SER_DISK, CLIENT_VERSION);
1099 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1100 if (!fReadTransactions)
1101 filein.nType |= SER_BLOCKHEADERONLY;
1107 catch (std::exception &e) {
1108 return error("%s() : deserialize or I/O error", BOOST_CURRENT_FUNCTION);
1112 if (fReadTransactions && IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
1113 return error("CBlock::ReadFromDisk() : errors in block header");
1122 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%"PRIszu", vchBlockSig=%s)\n",
1123 GetHash().ToString().c_str(),
1125 hashPrevBlock.ToString().c_str(),
1126 hashMerkleRoot.ToString().c_str(),
1127 nTime, nBits, nNonce,
1129 HexStr(vchBlockSig.begin(), vchBlockSig.end()).c_str());
1130 for (unsigned int i = 0; i < vtx.size(); i++)
1135 printf(" vMerkleTree: ");
1136 for (unsigned int i = 0; i < vMerkleTree.size(); i++)
1137 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1142 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1143 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck=false);
1144 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1145 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1146 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1147 bool CheckBlock(bool fCheckPOW=true, bool fCheckMerkleRoot=true, bool fCheckSig=true) const;
1149 bool GetCoinAge(uint64& nCoinAge) const; // ppcoin: calculate total coin age spent in block
1150 bool SignBlock(CWallet& keystore);
1151 bool CheckBlockSignature(bool fProofOfStake) const;
1154 bool SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew);
1162 /** The block chain is a tree shaped structure starting with the
1163 * genesis block at the root, with each block potentially having multiple
1164 * candidates to be the next block. pprev and pnext link a path through the
1165 * main/longest chain. A blockindex may have multiple pprev pointing back
1166 * to it, but pnext will only point forward to the longest branch, or will
1167 * be null if the block is not part of the longest chain.
1172 const uint256* phashBlock;
1176 unsigned int nBlockPos;
1177 uint256 nChainTrust; // 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;
1219 nStakeModifierChecksum = 0;
1220 hashProofOfStake = 0;
1221 prevoutStake.SetNull();
1231 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1237 nBlockPos = nBlockPosIn;
1244 nStakeModifierChecksum = 0;
1245 hashProofOfStake = 0;
1246 if (block.IsProofOfStake())
1249 prevoutStake = block.vtx[1].vin[0].prevout;
1250 nStakeTime = block.vtx[1].nTime;
1254 prevoutStake.SetNull();
1258 nVersion = block.nVersion;
1259 hashMerkleRoot = block.hashMerkleRoot;
1260 nTime = block.nTime;
1261 nBits = block.nBits;
1262 nNonce = block.nNonce;
1265 CBlock GetBlockHeader() const
1268 block.nVersion = nVersion;
1270 block.hashPrevBlock = pprev->GetBlockHash();
1271 block.hashMerkleRoot = hashMerkleRoot;
1272 block.nTime = nTime;
1273 block.nBits = nBits;
1274 block.nNonce = nNonce;
1278 uint256 GetBlockHash() const
1283 int64 GetBlockTime() const
1285 return (int64)nTime;
1288 uint256 GetBlockTrust() const;
1290 bool IsInMainChain() const
1292 return (pnext || this == pindexBest);
1295 bool CheckIndex() const
1300 enum { nMedianTimeSpan=11 };
1302 int64 GetMedianTimePast() const
1304 int64 pmedian[nMedianTimeSpan];
1305 int64* pbegin = &pmedian[nMedianTimeSpan];
1306 int64* pend = &pmedian[nMedianTimeSpan];
1308 const CBlockIndex* pindex = this;
1309 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1310 *(--pbegin) = pindex->GetBlockTime();
1312 std::sort(pbegin, pend);
1313 return pbegin[(pend - pbegin)/2];
1316 int64 GetMedianTime() const
1318 const CBlockIndex* pindex = this;
1319 for (int i = 0; i < nMedianTimeSpan/2; i++)
1322 return GetBlockTime();
1323 pindex = pindex->pnext;
1325 return pindex->GetMedianTimePast();
1329 * Returns true if there are nRequired or more blocks of minVersion or above
1330 * in the last nToCheck blocks, starting at pstart and going backwards.
1332 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart,
1333 unsigned int nRequired, unsigned int nToCheck);
1336 bool IsProofOfWork() const
1338 return !(nFlags & BLOCK_PROOF_OF_STAKE);
1341 bool IsProofOfStake() const
1343 return (nFlags & BLOCK_PROOF_OF_STAKE);
1346 void SetProofOfStake()
1348 nFlags |= BLOCK_PROOF_OF_STAKE;
1351 unsigned int GetStakeEntropyBit() const
1353 return ((nFlags & BLOCK_STAKE_ENTROPY) >> 1);
1356 bool SetStakeEntropyBit(unsigned int nEntropyBit)
1358 if (nEntropyBit > 1)
1360 nFlags |= (nEntropyBit? BLOCK_STAKE_ENTROPY : 0);
1364 bool GeneratedStakeModifier() const
1366 return (nFlags & BLOCK_STAKE_MODIFIER);
1369 void SetStakeModifier(uint64 nModifier, bool fGeneratedStakeModifier)
1371 nStakeModifier = nModifier;
1372 if (fGeneratedStakeModifier)
1373 nFlags |= BLOCK_STAKE_MODIFIER;
1376 std::string ToString() const
1378 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)",
1379 pprev, pnext, nFile, nBlockPos, nHeight,
1380 FormatMoney(nMint).c_str(), FormatMoney(nMoneySupply).c_str(),
1381 GeneratedStakeModifier() ? "MOD" : "-", GetStakeEntropyBit(), IsProofOfStake()? "PoS" : "PoW",
1382 nStakeModifier, nStakeModifierChecksum,
1383 hashProofOfStake.ToString().c_str(),
1384 prevoutStake.ToString().c_str(), nStakeTime,
1385 hashMerkleRoot.ToString().c_str(),
1386 GetBlockHash().ToString().c_str());
1391 printf("%s\n", ToString().c_str());
1397 /** Used to marshal pointers into hashes for db storage. */
1398 class CDiskBlockIndex : public CBlockIndex
1414 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1416 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1417 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1422 if (!(nType & SER_GETHASH))
1423 READWRITE(nVersion);
1425 READWRITE(hashNext);
1427 READWRITE(nBlockPos);
1430 READWRITE(nMoneySupply);
1432 READWRITE(nStakeModifier);
1433 if (IsProofOfStake())
1435 READWRITE(prevoutStake);
1436 READWRITE(nStakeTime);
1437 READWRITE(hashProofOfStake);
1441 const_cast<CDiskBlockIndex*>(this)->prevoutStake.SetNull();
1442 const_cast<CDiskBlockIndex*>(this)->nStakeTime = 0;
1443 const_cast<CDiskBlockIndex*>(this)->hashProofOfStake = 0;
1447 READWRITE(this->nVersion);
1448 READWRITE(hashPrev);
1449 READWRITE(hashMerkleRoot);
1453 READWRITE(blockHash);
1456 uint256 GetBlockHash() const
1458 if (fUseFastIndex && (nTime < GetAdjustedTime() - 24 * 60 * 60) && blockHash != 0)
1462 block.nVersion = nVersion;
1463 block.hashPrevBlock = hashPrev;
1464 block.hashMerkleRoot = hashMerkleRoot;
1465 block.nTime = nTime;
1466 block.nBits = nBits;
1467 block.nNonce = nNonce;
1469 const_cast<CDiskBlockIndex*>(this)->blockHash = block.GetHash();
1474 std::string ToString() const
1476 std::string str = "CDiskBlockIndex(";
1477 str += CBlockIndex::ToString();
1478 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1479 GetBlockHash().ToString().c_str(),
1480 hashPrev.ToString().c_str(),
1481 hashNext.ToString().c_str());
1487 printf("%s\n", ToString().c_str());
1498 /** Describes a place in the block chain to another node such that if the
1499 * other node doesn't have the same branch, it can find a recent common trunk.
1500 * The further back it is, the further before the fork it may be.
1505 std::vector<uint256> vHave;
1512 explicit CBlockLocator(const CBlockIndex* pindex)
1517 explicit CBlockLocator(uint256 hashBlock)
1519 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1520 if (mi != mapBlockIndex.end())
1524 CBlockLocator(const std::vector<uint256>& vHaveIn)
1531 if (!(nType & SER_GETHASH))
1532 READWRITE(nVersion);
1543 return vHave.empty();
1546 void Set(const CBlockIndex* pindex)
1552 vHave.push_back(pindex->GetBlockHash());
1554 // Exponentially larger steps back
1555 for (int i = 0; pindex && i < nStep; i++)
1556 pindex = pindex->pprev;
1557 if (vHave.size() > 10)
1560 vHave.push_back((!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
1563 int GetDistanceBack()
1565 // Retrace how far back it was in the sender's branch
1568 BOOST_FOREACH(const uint256& hash, vHave)
1570 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1571 if (mi != mapBlockIndex.end())
1573 CBlockIndex* pindex = (*mi).second;
1574 if (pindex->IsInMainChain())
1584 CBlockIndex* GetBlockIndex()
1586 // Find the first block the caller has in the main chain
1587 BOOST_FOREACH(const uint256& hash, vHave)
1589 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1590 if (mi != mapBlockIndex.end())
1592 CBlockIndex* pindex = (*mi).second;
1593 if (pindex->IsInMainChain())
1597 return pindexGenesisBlock;
1600 uint256 GetBlockHash()
1602 // Find the first block the caller has in the main chain
1603 BOOST_FOREACH(const uint256& hash, vHave)
1605 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1606 if (mi != mapBlockIndex.end())
1608 CBlockIndex* pindex = (*mi).second;
1609 if (pindex->IsInMainChain())
1613 return (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet);
1618 CBlockIndex* pindex = GetBlockIndex();
1621 return pindex->nHeight;
1635 mutable CCriticalSection cs;
1636 std::map<uint256, CTransaction> mapTx;
1637 std::map<COutPoint, CInPoint> mapNextTx;
1639 bool accept(CTxDB& txdb, CTransaction &tx,
1640 bool fCheckInputs, bool* pfMissingInputs);
1641 bool addUnchecked(const uint256& hash, CTransaction &tx);
1642 bool remove(CTransaction &tx);
1644 void queryHashes(std::vector<uint256>& vtxid);
1646 unsigned long size()
1649 return mapTx.size();
1652 bool exists(uint256 hash)
1654 return (mapTx.count(hash) != 0);
1657 CTransaction& lookup(uint256 hash)
1663 extern CTxMemPool mempool;