1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2011 The Bitcoin developers
3 // Copyright (c) 2011-2012 The PPCoin developers
4 // Distributed under the MIT/X11 software license, see the accompanying
5 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
27 class CRequestTracker;
31 static const unsigned int MAX_BLOCK_SIZE = 1000000;
32 static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/2;
33 static const int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
34 static const int64 COIN = 1000000;
35 static const int64 CENT = 10000;
36 static const int64 MIN_TX_FEE = 10000;
37 static const int64 MIN_RELAY_TX_FEE = 10000;
38 static const int64 MAX_MONEY = 2000000000 * COIN;
39 inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
40 static const int COINBASE_MATURITY = 100;
41 // Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp.
42 static const int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC
44 static const int fHaveUPnP = true;
46 static const int fHaveUPnP = false;
54 extern CCriticalSection cs_main;
55 extern std::map<uint256, CBlockIndex*> mapBlockIndex;
56 extern std::set<std::pair<COutPoint, unsigned int> > setStakeSeen;
57 extern uint256 hashGenesisBlock;
58 extern CBlockIndex* pindexGenesisBlock;
59 extern int nBestHeight;
60 extern uint64 nBestChainTrust;
61 extern uint64 nBestInvalidTrust;
62 extern uint256 hashBestChain;
63 extern CBlockIndex* pindexBest;
64 extern unsigned int nTransactionsUpdated;
65 extern double dHashesPerSec;
66 extern int64 nHPSTimerStart;
67 extern int64 nTimeBestReceived;
68 extern CCriticalSection cs_setpwalletRegistered;
69 extern std::set<CWallet*> setpwalletRegistered;
72 extern int fGenerateBitcoins;
73 extern int64 nTransactionFee;
74 extern int fLimitProcessors;
75 extern int nLimitProcessors;
76 extern int fMinimizeToTray;
77 extern int fMinimizeOnClose;
79 extern int64 nBalanceReserve;
89 void RegisterWallet(CWallet* pwalletIn);
90 void UnregisterWallet(CWallet* pwalletIn);
91 bool ProcessBlock(CNode* pfrom, CBlock* pblock);
92 bool CheckDiskSpace(uint64 nAdditionalBytes=0);
93 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
94 FILE* AppendBlockFile(unsigned int& nFileRet);
95 bool LoadBlockIndex(bool fAllowNew=true);
96 void PrintBlockTree();
97 bool ProcessMessages(CNode* pfrom);
98 bool SendMessages(CNode* pto, bool fSendTrickle);
99 void GenerateBitcoins(bool fGenerate, CWallet* pwallet);
100 CBlock* CreateNewBlock(CWallet* pwallet);
101 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce);
102 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
103 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey);
104 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
105 int64 GetProofOfStakeReward(int64 nCoinAge);
106 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime);
107 int GetNumBlocksOfPeers();
108 bool IsInitialBlockDownload();
109 std::string GetWarnings(std::string strFor);
110 bool Reorganize(CTxDB& txdb, CBlockIndex* pindexNew);
123 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
126 bool WriteSetting(const std::string& strKey, const T& value)
129 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
131 std::string strWalletFile;
132 if (!GetWalletFile(pwallet, strWalletFile))
134 fOk |= CWalletDB(strWalletFile).WriteSetting(strKey, value);
144 unsigned int nBlockPos;
152 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
155 nBlockPos = nBlockPosIn;
159 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
160 void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
161 bool IsNull() const { return (nFile == -1); }
163 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
165 return (a.nFile == b.nFile &&
166 a.nBlockPos == b.nBlockPos &&
167 a.nTxPos == b.nTxPos);
170 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
175 std::string ToString() const
178 return strprintf("null");
180 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
185 printf("%s", ToString().c_str());
198 CInPoint() { SetNull(); }
199 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
200 void SetNull() { ptx = NULL; n = -1; }
201 bool IsNull() const { return (ptx == NULL && n == -1); }
213 COutPoint() { SetNull(); }
214 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
215 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
216 void SetNull() { hash = 0; n = -1; }
217 bool IsNull() const { return (hash == 0 && n == -1); }
219 friend bool operator<(const COutPoint& a, const COutPoint& b)
221 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
224 friend bool operator==(const COutPoint& a, const COutPoint& b)
226 return (a.hash == b.hash && a.n == b.n);
229 friend bool operator!=(const COutPoint& a, const COutPoint& b)
234 std::string ToString() const
236 return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,10).c_str(), n);
241 printf("%s\n", ToString().c_str());
249 // An input of a transaction. It contains the location of the previous
250 // transaction's output that it claims and a signature that matches the
251 // output's public key.
258 unsigned int nSequence;
262 nSequence = UINT_MAX;
265 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
268 scriptSig = scriptSigIn;
269 nSequence = nSequenceIn;
272 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
274 prevout = COutPoint(hashPrevTx, nOut);
275 scriptSig = scriptSigIn;
276 nSequence = nSequenceIn;
282 READWRITE(scriptSig);
283 READWRITE(nSequence);
288 return (nSequence == UINT_MAX);
291 friend bool operator==(const CTxIn& a, const CTxIn& b)
293 return (a.prevout == b.prevout &&
294 a.scriptSig == b.scriptSig &&
295 a.nSequence == b.nSequence);
298 friend bool operator!=(const CTxIn& a, const CTxIn& b)
303 std::string ToString() const
306 str += strprintf("CTxIn(");
307 str += prevout.ToString();
308 if (prevout.IsNull())
309 str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
311 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
312 if (nSequence != UINT_MAX)
313 str += strprintf(", nSequence=%u", nSequence);
320 printf("%s\n", ToString().c_str());
328 // An output of a transaction. It contains the public key that the next input
329 // must be able to sign with to claim it.
335 CScript scriptPubKey;
342 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
345 scriptPubKey = scriptPubKeyIn;
351 READWRITE(scriptPubKey);
357 scriptPubKey.clear();
362 return (nValue == -1);
368 scriptPubKey.clear();
373 return (nValue == 0 && scriptPubKey.empty());
376 uint256 GetHash() const
378 return SerializeHash(*this);
381 friend bool operator==(const CTxOut& a, const CTxOut& b)
383 return (a.nValue == b.nValue &&
384 a.scriptPubKey == b.scriptPubKey);
387 friend bool operator!=(const CTxOut& a, const CTxOut& b)
392 std::string ToString() const
394 if (IsEmpty()) return "CTxOut(empty)";
395 if (scriptPubKey.size() < 6)
396 return "CTxOut(error)";
397 return strprintf("CTxOut(nValue=%s, scriptPubKey=%s)", FormatMoney(nValue).c_str(), scriptPubKey.ToString().substr(0,30).c_str());
402 printf("%s\n", ToString().c_str());
410 // The basic transaction that is broadcasted on the network and contained in
411 // blocks. A transaction can contain multiple inputs and outputs.
418 std::vector<CTxIn> vin;
419 std::vector<CTxOut> vout;
420 unsigned int nLockTime;
422 // Denial-of-service detection:
424 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
433 READWRITE(this->nVersion);
434 nVersion = this->nVersion;
438 READWRITE(nLockTime);
444 nTime = GetAdjustedTime();
448 nDoS = 0; // Denial-of-service prevention
453 return (vin.empty() && vout.empty());
456 uint256 GetHash() const
458 return SerializeHash(*this);
461 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
463 // Time based nLockTime implemented in 0.1.6
466 if (nBlockHeight == 0)
467 nBlockHeight = nBestHeight;
469 nBlockTime = GetAdjustedTime();
470 if ((int64)nLockTime < (nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
472 BOOST_FOREACH(const CTxIn& txin, vin)
478 bool IsNewerThan(const CTransaction& old) const
480 if (vin.size() != old.vin.size())
482 for (int i = 0; i < vin.size(); i++)
483 if (vin[i].prevout != old.vin[i].prevout)
487 unsigned int nLowest = UINT_MAX;
488 for (int i = 0; i < vin.size(); i++)
490 if (vin[i].nSequence != old.vin[i].nSequence)
492 if (vin[i].nSequence <= nLowest)
495 nLowest = vin[i].nSequence;
497 if (old.vin[i].nSequence < nLowest)
500 nLowest = old.vin[i].nSequence;
507 bool IsCoinBase() const
509 return (vin.size() == 1 && vin[0].prevout.IsNull() && vout.size() == 1);
512 bool IsCoinStake() const
514 // ppcoin: the coin stake transaction is marked with the first output empty
515 return (vin.size() > 0 && vout.size() == 2 && vout[0].IsEmpty());
518 int GetSigOpCount() const
521 BOOST_FOREACH(const CTxIn& txin, vin)
522 n += txin.scriptSig.GetSigOpCount();
523 BOOST_FOREACH(const CTxOut& txout, vout)
524 n += txout.scriptPubKey.GetSigOpCount();
528 bool IsStandard() const
530 BOOST_FOREACH(const CTxIn& txin, vin)
531 if (!txin.scriptSig.IsPushOnly())
532 return error("nonstandard txin: %s", txin.scriptSig.ToString().c_str());
533 BOOST_FOREACH(const CTxOut& txout, vout)
534 if (!::IsStandard(txout.scriptPubKey))
535 return error("nonstandard txout: %s", txout.scriptPubKey.ToString().c_str());
539 int64 GetValueOut() const
542 BOOST_FOREACH(const CTxOut& txout, vout)
544 nValueOut += txout.nValue;
545 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
546 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
551 static bool AllowFree(double dPriority)
553 // Large (in bytes) low-priority (new, small-coin) transactions
555 return dPriority > COIN * 144 / 250;
558 int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=false, bool fForRelay=false) const
560 // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
561 int64 nBaseFee = fForRelay ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
563 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);
564 unsigned int nNewBlockSize = nBlockSize + nBytes;
565 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
571 // Transactions under 10K are free
572 // (about 4500bc if made of 50bc inputs)
578 // Free transaction area
579 if (nNewBlockSize < 27000)
584 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
585 if (nMinFee < nBaseFee)
586 BOOST_FOREACH(const CTxOut& txout, vout)
587 if (txout.nValue < CENT)
590 // Raise the price as the block approaches full
591 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
593 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
595 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
598 if (!MoneyRange(nMinFee))
604 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
606 CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");
608 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
611 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
612 return error("CTransaction::ReadFromDisk() : fseek failed");
615 // Return file pointer
618 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
619 return error("CTransaction::ReadFromDisk() : second fseek failed");
620 *pfileRet = filein.release();
625 friend bool operator==(const CTransaction& a, const CTransaction& b)
627 return (a.nVersion == b.nVersion &&
628 a.nTime == b.nTime &&
631 a.nLockTime == b.nLockTime);
634 friend bool operator!=(const CTransaction& a, const CTransaction& b)
640 std::string ToString() const
643 str += IsCoinBase()? "Coinbase" : (IsCoinStake()? "Coinstake" : "CTransaction");
644 str += strprintf("(hash=%s, nTime=%d, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
645 GetHash().ToString().substr(0,10).c_str(),
651 for (int i = 0; i < vin.size(); i++)
652 str += " " + vin[i].ToString() + "\n";
653 for (int i = 0; i < vout.size(); i++)
654 str += " " + vout[i].ToString() + "\n";
660 printf("%s", ToString().c_str());
664 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
665 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
666 bool ReadFromDisk(COutPoint prevout);
667 bool DisconnectInputs(CTxDB& txdb);
668 bool ConnectInputs(CTxDB& txdb, std::map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
669 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee=0);
670 bool ClientConnectInputs();
671 bool CheckTransaction() const;
672 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
673 bool AcceptToMemoryPool(bool fCheckInputs=true, bool* pfMissingInputs=NULL);
675 bool AddToMemoryPoolUnchecked();
677 bool RemoveFromMemoryPool();
678 bool GetCoinAge(CTxDB& txdb, uint64& nCoinAge) const; // ppcoin: get transaction coin age
679 bool CheckProofOfStake(unsigned int nBits) const;
687 // A transaction with a merkle branch linking it to the block chain
689 class CMerkleTx : public CTransaction
693 std::vector<uint256> vMerkleBranch;
697 mutable char fMerkleVerified;
705 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
714 fMerkleVerified = false;
720 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
721 nVersion = this->nVersion;
722 READWRITE(hashBlock);
723 READWRITE(vMerkleBranch);
728 int SetMerkleBranch(const CBlock* pblock=NULL);
729 int GetDepthInMainChain(int& nHeightRet) const;
730 int GetDepthInMainChain() const { int nHeight; return GetDepthInMainChain(nHeight); }
731 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
732 int GetBlocksToMaturity() const;
733 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
734 bool AcceptToMemoryPool();
741 // A txdb record that contains the disk location of a transaction and the
742 // locations of transactions that spend its outputs. vSpent is really only
743 // used as a flag, but having the location is very helpful for debugging.
749 std::vector<CDiskTxPos> vSpent;
756 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
759 vSpent.resize(nOutputs);
764 if (!(nType & SER_GETHASH))
781 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
783 return (a.pos == b.pos &&
784 a.vSpent == b.vSpent);
787 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
791 int GetDepthInMainChain() const;
799 // Nodes collect new transactions into a block, hash them into a hash tree,
800 // and scan through nonce values to make the block's hash satisfy proof-of-work
801 // requirements. When they solve the proof-of-work, they broadcast the block
802 // to everyone and the block is added to the block chain. The first transaction
803 // in the block is a special one that creates a new coin owned by the creator
806 // Blocks are appended to blk0001.dat files on disk. Their location on disk
807 // is indexed by CBlockIndex objects in memory.
814 uint256 hashPrevBlock;
815 uint256 hashMerkleRoot;
821 std::vector<CTransaction> vtx;
823 // ppcoin: block signature - signed by coin base txout[0]'s owner
824 std::vector<unsigned char> vchBlockSig;
827 mutable std::vector<uint256> vMerkleTree;
829 // Denial-of-service detection:
831 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
840 READWRITE(this->nVersion);
841 nVersion = this->nVersion;
842 READWRITE(hashPrevBlock);
843 READWRITE(hashMerkleRoot);
848 // ConnectBlock depends on vtx following header to generate CDiskTxPos
849 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
852 READWRITE(vchBlockSig);
856 const_cast<CBlock*>(this)->vtx.clear();
857 const_cast<CBlock*>(this)->vchBlockSig.clear();
880 uint256 GetHash() const
882 return Hash(BEGIN(nVersion), END(nNonce));
885 int64 GetBlockTime() const
890 // ppcoin: two types of block: proof-of-work or proof-of-stake
891 bool IsProofOfStake() const
893 return (vtx.size() > 1 && vtx[1].IsCoinStake());
896 bool IsProofOfWork() const
898 return !IsProofOfStake();
901 std::pair<COutPoint, unsigned int> GetProofOfStake() const
903 return IsProofOfStake()? std::make_pair(vtx[1].vin[0].prevout, vtx[1].nTime) : std::make_pair(COutPoint(), (unsigned int)0);
906 // ppcoin: get max transaction timestamp
907 int64 GetMaxTransactionTime() const
909 int64 maxTransactionTime = 0;
910 BOOST_FOREACH(const CTransaction& tx, vtx)
911 maxTransactionTime = std::max(maxTransactionTime, (int64)tx.nTime);
912 return maxTransactionTime;
915 int GetSigOpCount() const
918 BOOST_FOREACH(const CTransaction& tx, vtx)
919 n += tx.GetSigOpCount();
924 uint256 BuildMerkleTree() const
927 BOOST_FOREACH(const CTransaction& tx, vtx)
928 vMerkleTree.push_back(tx.GetHash());
930 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
932 for (int i = 0; i < nSize; i += 2)
934 int i2 = std::min(i+1, nSize-1);
935 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
936 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
940 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
943 std::vector<uint256> GetMerkleBranch(int nIndex) const
945 if (vMerkleTree.empty())
947 std::vector<uint256> vMerkleBranch;
949 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
951 int i = std::min(nIndex^1, nSize-1);
952 vMerkleBranch.push_back(vMerkleTree[j+i]);
956 return vMerkleBranch;
959 static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
963 BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
966 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
968 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
975 bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
977 // Open history file to append
978 CAutoFile fileout = AppendBlockFile(nFileRet);
980 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
982 // Write index header
983 unsigned int nSize = fileout.GetSerializeSize(*this);
984 fileout << FLATDATA(pchMessageStart) << nSize;
987 nBlockPosRet = ftell(fileout);
988 if (nBlockPosRet == -1)
989 return error("CBlock::WriteToDisk() : ftell failed");
992 // Flush stdio buffers and commit to disk before returning
994 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
997 _commit(_fileno(fileout));
999 fsync(fileno(fileout));
1006 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
1010 // Open history file to read
1011 CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");
1013 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1014 if (!fReadTransactions)
1015 filein.nType |= SER_BLOCKHEADERONLY;
1021 if (fReadTransactions && IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
1022 return error("CBlock::ReadFromDisk() : errors in block header");
1031 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d, vchBlockSig=%s)\n",
1032 GetHash().ToString().substr(0,20).c_str(),
1034 hashPrevBlock.ToString().substr(0,20).c_str(),
1035 hashMerkleRoot.ToString().substr(0,10).c_str(),
1036 nTime, nBits, nNonce,
1038 HexStr(vchBlockSig.begin(), vchBlockSig.end()).c_str());
1039 for (int i = 0; i < vtx.size(); i++)
1044 printf(" vMerkleTree: ");
1045 for (int i = 0; i < vMerkleTree.size(); i++)
1046 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1051 bool SignBlock(const CKeyStore& keystore)
1053 std::vector<std::pair<opcodetype, valtype> > vSolution;
1054 const CTxOut& txout = IsProofOfStake()? vtx[1].vout[1] : vtx[0].vout[0];
1056 if (!Solver(txout.scriptPubKey, vSolution))
1058 BOOST_FOREACH(PAIRTYPE(opcodetype, valtype)& item, vSolution)
1060 if (item.first == OP_PUBKEY)
1063 const valtype& vchPubKey = item.second;
1065 if (!keystore.GetKey(Hash160(vchPubKey), key))
1067 if (key.GetPubKey() != vchPubKey)
1069 return key.Sign(GetHash(), vchBlockSig);
1075 bool CheckBlockSignature() const
1077 if (GetHash() == hashGenesisBlock)
1078 return vchBlockSig.empty();
1080 std::vector<std::pair<opcodetype, valtype> > vSolution;
1081 const CTxOut& txout = IsProofOfStake()? vtx[1].vout[1] : vtx[0].vout[0];
1083 if (!Solver(txout.scriptPubKey, vSolution))
1085 BOOST_FOREACH(PAIRTYPE(opcodetype, valtype)& item, vSolution)
1087 if (item.first == OP_PUBKEY)
1089 const valtype& vchPubKey = item.second;
1091 if (!key.SetPubKey(vchPubKey))
1093 if (vchBlockSig.empty())
1095 return key.Verify(GetHash(), vchBlockSig);
1101 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1102 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1103 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1104 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1105 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1106 bool CheckBlock() const;
1108 bool GetCoinAge(uint64& nCoinAge) const; // ppcoin: calculate total coin age spent in block
1117 // The block chain is a tree shaped structure starting with the
1118 // genesis block at the root, with each block potentially having multiple
1119 // candidates to be the next block. pprev and pnext link a path through the
1120 // main/longest chain. A blockindex may have multiple pprev pointing back
1121 // to it, but pnext will only point forward to the longest branch, or will
1122 // be null if the block is not part of the longest chain.
1127 const uint256* phashBlock;
1131 unsigned int nBlockPos;
1132 uint64 nChainTrust;// ppcoin: trust score of chain, in the unit of coin-days
1134 int nCheckpoint; // ppcoin: chain auto checkpoint height
1135 bool fProofOfStake; // ppcoin: is the block of proof-of-stake type
1136 COutPoint prevoutStake;
1137 unsigned int nStakeTime;
1141 uint256 hashMerkleRoot;
1144 unsigned int nNonce;
1157 fProofOfStake = true;
1158 prevoutStake.SetNull();
1168 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1174 nBlockPos = nBlockPosIn;
1178 fProofOfStake = block.IsProofOfStake();
1181 prevoutStake = block.vtx[1].vin[0].prevout;
1182 nStakeTime = block.vtx[1].nTime;
1186 prevoutStake.SetNull();
1190 nVersion = block.nVersion;
1191 hashMerkleRoot = block.hashMerkleRoot;
1192 nTime = block.nTime;
1193 nBits = block.nBits;
1194 nNonce = block.nNonce;
1197 CBlock GetBlockHeader() const
1200 block.nVersion = nVersion;
1202 block.hashPrevBlock = pprev->GetBlockHash();
1203 block.hashMerkleRoot = hashMerkleRoot;
1204 block.nTime = nTime;
1205 block.nBits = nBits;
1206 block.nNonce = nNonce;
1210 uint256 GetBlockHash() const
1215 int64 GetBlockTime() const
1217 return (int64)nTime;
1220 int64 GetBlockTrust() const
1222 return (nChainTrust - (pprev? pprev->nChainTrust : 0));
1225 bool IsInMainChain() const
1227 return (pnext || this == pindexBest);
1230 bool CheckIndex() const
1232 return IsProofOfWork() ? CheckProofOfWork(GetBlockHash(), nBits) : true;
1235 bool EraseBlockFromDisk()
1237 // Open history file
1238 CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");
1242 // Overwrite with empty null block
1250 enum { nMedianTimeSpan=11 };
1252 int64 GetMedianTimePast() const
1254 int64 pmedian[nMedianTimeSpan];
1255 int64* pbegin = &pmedian[nMedianTimeSpan];
1256 int64* pend = &pmedian[nMedianTimeSpan];
1258 const CBlockIndex* pindex = this;
1259 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1260 *(--pbegin) = pindex->GetBlockTime();
1262 std::sort(pbegin, pend);
1263 return pbegin[(pend - pbegin)/2];
1266 int64 GetMedianTime() const
1268 const CBlockIndex* pindex = this;
1269 for (int i = 0; i < nMedianTimeSpan/2; i++)
1272 return GetBlockTime();
1273 pindex = pindex->pnext;
1275 return pindex->GetMedianTimePast();
1278 bool IsProofOfWork() const
1280 return !fProofOfStake;
1283 bool IsProofOfStake() const
1285 return fProofOfStake;
1288 std::string ToString() const
1290 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nChainTrust=%"PRI64d" nHeight=%d, nCheckpoint=%d, fProofOfStake=%d prevoutStake=(%s), nStakeTime=%d merkle=%s, hashBlock=%s)",
1291 pprev, pnext, nFile, nBlockPos, nChainTrust, nHeight, nCheckpoint,
1292 fProofOfStake, prevoutStake.ToString().c_str(), nStakeTime,
1293 hashMerkleRoot.ToString().substr(0,10).c_str(),
1294 GetBlockHash().ToString().substr(0,20).c_str());
1299 printf("%s\n", ToString().c_str());
1306 // Used to marshal pointers into hashes for db storage.
1308 class CDiskBlockIndex : public CBlockIndex
1320 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1322 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1323 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1328 if (!(nType & SER_GETHASH))
1329 READWRITE(nVersion);
1331 READWRITE(hashNext);
1333 READWRITE(nBlockPos);
1334 READWRITE(nChainTrust);
1336 READWRITE(nCheckpoint);
1337 READWRITE(fProofOfStake);
1340 READWRITE(prevoutStake);
1341 READWRITE(nStakeTime);
1345 const_cast<CDiskBlockIndex*>(this)->prevoutStake.SetNull();
1346 const_cast<CDiskBlockIndex*>(this)->nStakeTime = 0;
1350 READWRITE(this->nVersion);
1351 READWRITE(hashPrev);
1352 READWRITE(hashMerkleRoot);
1358 uint256 GetBlockHash() const
1361 block.nVersion = nVersion;
1362 block.hashPrevBlock = hashPrev;
1363 block.hashMerkleRoot = hashMerkleRoot;
1364 block.nTime = nTime;
1365 block.nBits = nBits;
1366 block.nNonce = nNonce;
1367 return block.GetHash();
1371 std::string ToString() const
1373 std::string str = "CDiskBlockIndex(";
1374 str += CBlockIndex::ToString();
1375 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1376 GetBlockHash().ToString().c_str(),
1377 hashPrev.ToString().substr(0,20).c_str(),
1378 hashNext.ToString().substr(0,20).c_str());
1384 printf("%s\n", ToString().c_str());
1396 // Describes a place in the block chain to another node such that if the
1397 // other node doesn't have the same branch, it can find a recent common trunk.
1398 // The further back it is, the further before the fork it may be.
1403 std::vector<uint256> vHave;
1410 explicit CBlockLocator(const CBlockIndex* pindex)
1415 explicit CBlockLocator(uint256 hashBlock)
1417 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1418 if (mi != mapBlockIndex.end())
1424 if (!(nType & SER_GETHASH))
1425 READWRITE(nVersion);
1436 return vHave.empty();
1439 void Set(const CBlockIndex* pindex)
1445 vHave.push_back(pindex->GetBlockHash());
1447 // Exponentially larger steps back
1448 for (int i = 0; pindex && i < nStep; i++)
1449 pindex = pindex->pprev;
1450 if (vHave.size() > 10)
1453 vHave.push_back(hashGenesisBlock);
1456 int GetDistanceBack()
1458 // Retrace how far back it was in the sender's branch
1461 BOOST_FOREACH(const uint256& hash, vHave)
1463 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1464 if (mi != mapBlockIndex.end())
1466 CBlockIndex* pindex = (*mi).second;
1467 if (pindex->IsInMainChain())
1477 CBlockIndex* GetBlockIndex()
1479 // Find the first block the caller has in the main chain
1480 BOOST_FOREACH(const uint256& hash, vHave)
1482 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1483 if (mi != mapBlockIndex.end())
1485 CBlockIndex* pindex = (*mi).second;
1486 if (pindex->IsInMainChain())
1490 return pindexGenesisBlock;
1493 uint256 GetBlockHash()
1495 // Find the first block the caller has in the main chain
1496 BOOST_FOREACH(const uint256& hash, vHave)
1498 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1499 if (mi != mapBlockIndex.end())
1501 CBlockIndex* pindex = (*mi).second;
1502 if (pindex->IsInMainChain())
1506 return hashGenesisBlock;
1511 CBlockIndex* pindex = GetBlockIndex();
1514 return pindex->nHeight;
1527 // Alerts are for notifying old versions if they become too obsolete and
1528 // need to upgrade. The message is displayed in the status bar.
1529 // Alert messages are broadcast as a vector of signed data. Unserializing may
1530 // not read the entire buffer if the alert is for a newer version, but older
1531 // versions can still relay the original data.
1533 class CUnsignedAlert
1537 int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
1541 std::set<int> setCancel;
1542 int nMinVer; // lowest version inclusive
1543 int nMaxVer; // highest version inclusive
1544 std::set<std::string> setSubVer; // empty matches all
1548 std::string strComment;
1549 std::string strStatusBar;
1550 std::string strReserved;
1554 READWRITE(this->nVersion);
1555 nVersion = this->nVersion;
1556 READWRITE(nRelayUntil);
1557 READWRITE(nExpiration);
1560 READWRITE(setCancel);
1563 READWRITE(setSubVer);
1564 READWRITE(nPriority);
1566 READWRITE(strComment);
1567 READWRITE(strStatusBar);
1568 READWRITE(strReserved);
1585 strStatusBar.clear();
1586 strReserved.clear();
1589 std::string ToString() const
1591 std::string strSetCancel;
1592 BOOST_FOREACH(int n, setCancel)
1593 strSetCancel += strprintf("%d ", n);
1594 std::string strSetSubVer;
1595 BOOST_FOREACH(std::string str, setSubVer)
1596 strSetSubVer += "\"" + str + "\" ";
1600 " nRelayUntil = %"PRI64d"\n"
1601 " nExpiration = %"PRI64d"\n"
1609 " strComment = \"%s\"\n"
1610 " strStatusBar = \"%s\"\n"
1617 strSetCancel.c_str(),
1620 strSetSubVer.c_str(),
1623 strStatusBar.c_str());
1628 printf("%s", ToString().c_str());
1632 class CAlert : public CUnsignedAlert
1635 std::vector<unsigned char> vchMsg;
1636 std::vector<unsigned char> vchSig;
1651 CUnsignedAlert::SetNull();
1658 return (nExpiration == 0);
1661 uint256 GetHash() const
1663 return SerializeHash(*this);
1666 bool IsInEffect() const
1668 return (GetAdjustedTime() < nExpiration);
1671 bool Cancels(const CAlert& alert) const
1674 return false; // this was a no-op before 31403
1675 return (alert.nID <= nCancel || setCancel.count(alert.nID));
1678 bool AppliesTo(int nVersion, std::string strSubVerIn) const
1680 return (IsInEffect() &&
1681 nMinVer <= nVersion && nVersion <= nMaxVer &&
1682 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1685 bool AppliesToMe() const
1687 return AppliesTo(VERSION, ::pszSubVer);
1690 bool RelayTo(CNode* pnode) const
1694 // returns true if wasn't already contained in the set
1695 if (pnode->setKnown.insert(GetHash()).second)
1697 if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
1699 GetAdjustedTime() < nRelayUntil)
1701 pnode->PushMessage("alert", *this);
1708 bool CheckSignature()
1711 if (!key.SetPubKey(ParseHex("0487ca85b6ae9d311f996c7616d20d0c88a5b4f07d25e78f419019f35cce6522acf978b2d99f0e7a58db1f120439e5c1889266927854aa57c93956c2569188a539")))
1712 return error("CAlert::CheckSignature() : SetPubKey failed");
1713 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
1714 return error("CAlert::CheckSignature() : verify signature failed");
1716 // Now unserialize the data
1717 CDataStream sMsg(vchMsg);
1718 sMsg >> *(CUnsignedAlert*)this;
1722 bool ProcessAlert();