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<COutPoint> 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);
122 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
125 bool WriteSetting(const std::string& strKey, const T& value)
128 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
130 std::string strWalletFile;
131 if (!GetWalletFile(pwallet, strWalletFile))
133 fOk |= CWalletDB(strWalletFile).WriteSetting(strKey, value);
143 unsigned int nBlockPos;
151 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
154 nBlockPos = nBlockPosIn;
158 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
159 void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
160 bool IsNull() const { return (nFile == -1); }
162 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
164 return (a.nFile == b.nFile &&
165 a.nBlockPos == b.nBlockPos &&
166 a.nTxPos == b.nTxPos);
169 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
174 std::string ToString() const
177 return strprintf("null");
179 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
184 printf("%s", ToString().c_str());
197 CInPoint() { SetNull(); }
198 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
199 void SetNull() { ptx = NULL; n = -1; }
200 bool IsNull() const { return (ptx == NULL && n == -1); }
212 COutPoint() { SetNull(); }
213 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
214 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
215 void SetNull() { hash = 0; n = -1; }
216 bool IsNull() const { return (hash == 0 && n == -1); }
218 friend bool operator<(const COutPoint& a, const COutPoint& b)
220 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
223 friend bool operator==(const COutPoint& a, const COutPoint& b)
225 return (a.hash == b.hash && a.n == b.n);
228 friend bool operator!=(const COutPoint& a, const COutPoint& b)
233 std::string ToString() const
235 return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,10).c_str(), n);
240 printf("%s\n", ToString().c_str());
248 // An input of a transaction. It contains the location of the previous
249 // transaction's output that it claims and a signature that matches the
250 // output's public key.
257 unsigned int nSequence;
261 nSequence = UINT_MAX;
264 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
267 scriptSig = scriptSigIn;
268 nSequence = nSequenceIn;
271 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
273 prevout = COutPoint(hashPrevTx, nOut);
274 scriptSig = scriptSigIn;
275 nSequence = nSequenceIn;
281 READWRITE(scriptSig);
282 READWRITE(nSequence);
287 return (nSequence == UINT_MAX);
290 friend bool operator==(const CTxIn& a, const CTxIn& b)
292 return (a.prevout == b.prevout &&
293 a.scriptSig == b.scriptSig &&
294 a.nSequence == b.nSequence);
297 friend bool operator!=(const CTxIn& a, const CTxIn& b)
302 std::string ToString() const
305 str += strprintf("CTxIn(");
306 str += prevout.ToString();
307 if (prevout.IsNull())
308 str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
310 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
311 if (nSequence != UINT_MAX)
312 str += strprintf(", nSequence=%u", nSequence);
319 printf("%s\n", ToString().c_str());
327 // An output of a transaction. It contains the public key that the next input
328 // must be able to sign with to claim it.
334 CScript scriptPubKey;
341 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
344 scriptPubKey = scriptPubKeyIn;
350 READWRITE(scriptPubKey);
356 scriptPubKey.clear();
361 return (nValue == -1);
367 scriptPubKey.clear();
372 return (nValue == 0 && scriptPubKey.empty());
375 uint256 GetHash() const
377 return SerializeHash(*this);
380 friend bool operator==(const CTxOut& a, const CTxOut& b)
382 return (a.nValue == b.nValue &&
383 a.scriptPubKey == b.scriptPubKey);
386 friend bool operator!=(const CTxOut& a, const CTxOut& b)
391 std::string ToString() const
393 if (IsEmpty()) return "CTxOut(empty)";
394 if (scriptPubKey.size() < 6)
395 return "CTxOut(error)";
396 return strprintf("CTxOut(nValue=%s, scriptPubKey=%s)", FormatMoney(nValue).c_str(), scriptPubKey.ToString().substr(0,30).c_str());
401 printf("%s\n", ToString().c_str());
409 // The basic transaction that is broadcasted on the network and contained in
410 // blocks. A transaction can contain multiple inputs and outputs.
417 std::vector<CTxIn> vin;
418 std::vector<CTxOut> vout;
419 unsigned int nLockTime;
421 // Denial-of-service detection:
423 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
432 READWRITE(this->nVersion);
433 nVersion = this->nVersion;
437 READWRITE(nLockTime);
443 nTime = GetAdjustedTime();
447 nDoS = 0; // Denial-of-service prevention
452 return (vin.empty() && vout.empty());
455 uint256 GetHash() const
457 return SerializeHash(*this);
460 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
462 // Time based nLockTime implemented in 0.1.6
465 if (nBlockHeight == 0)
466 nBlockHeight = nBestHeight;
468 nBlockTime = GetAdjustedTime();
469 if ((int64)nLockTime < (nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
471 BOOST_FOREACH(const CTxIn& txin, vin)
477 bool IsNewerThan(const CTransaction& old) const
479 if (vin.size() != old.vin.size())
481 for (int i = 0; i < vin.size(); i++)
482 if (vin[i].prevout != old.vin[i].prevout)
486 unsigned int nLowest = UINT_MAX;
487 for (int i = 0; i < vin.size(); i++)
489 if (vin[i].nSequence != old.vin[i].nSequence)
491 if (vin[i].nSequence <= nLowest)
494 nLowest = vin[i].nSequence;
496 if (old.vin[i].nSequence < nLowest)
499 nLowest = old.vin[i].nSequence;
506 bool IsCoinBase() const
508 return (vin.size() == 1 && vin[0].prevout.IsNull() && vout.size() == 1);
511 bool IsCoinStake() const
513 // ppcoin: the coin stake transaction is marked with the first output empty
514 return (vin.size() > 0 && vout.size() == 2 && vout[0].IsEmpty());
517 int GetSigOpCount() const
520 BOOST_FOREACH(const CTxIn& txin, vin)
521 n += txin.scriptSig.GetSigOpCount();
522 BOOST_FOREACH(const CTxOut& txout, vout)
523 n += txout.scriptPubKey.GetSigOpCount();
527 bool IsStandard() const
529 BOOST_FOREACH(const CTxIn& txin, vin)
530 if (!txin.scriptSig.IsPushOnly())
531 return error("nonstandard txin: %s", txin.scriptSig.ToString().c_str());
532 BOOST_FOREACH(const CTxOut& txout, vout)
533 if (!::IsStandard(txout.scriptPubKey))
534 return error("nonstandard txout: %s", txout.scriptPubKey.ToString().c_str());
538 int64 GetValueOut() const
541 BOOST_FOREACH(const CTxOut& txout, vout)
543 nValueOut += txout.nValue;
544 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
545 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
550 static bool AllowFree(double dPriority)
552 // Large (in bytes) low-priority (new, small-coin) transactions
554 return dPriority > COIN * 144 / 250;
557 int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=false, bool fForRelay=false) const
559 // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
560 int64 nBaseFee = fForRelay ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
562 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);
563 unsigned int nNewBlockSize = nBlockSize + nBytes;
564 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
570 // Transactions under 10K are free
571 // (about 4500bc if made of 50bc inputs)
577 // Free transaction area
578 if (nNewBlockSize < 27000)
583 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
584 if (nMinFee < nBaseFee)
585 BOOST_FOREACH(const CTxOut& txout, vout)
586 if (txout.nValue < CENT)
589 // Raise the price as the block approaches full
590 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
592 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
594 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
597 if (!MoneyRange(nMinFee))
603 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
605 CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");
607 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
610 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
611 return error("CTransaction::ReadFromDisk() : fseek failed");
614 // Return file pointer
617 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
618 return error("CTransaction::ReadFromDisk() : second fseek failed");
619 *pfileRet = filein.release();
624 friend bool operator==(const CTransaction& a, const CTransaction& b)
626 return (a.nVersion == b.nVersion &&
627 a.nTime == b.nTime &&
630 a.nLockTime == b.nLockTime);
633 friend bool operator!=(const CTransaction& a, const CTransaction& b)
639 std::string ToString() const
642 str += IsCoinBase()? "Coinbase" : (IsCoinStake()? "Coinstake" : "CTransaction");
643 str += strprintf("(hash=%s, nTime=%d, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
644 GetHash().ToString().substr(0,10).c_str(),
650 for (int i = 0; i < vin.size(); i++)
651 str += " " + vin[i].ToString() + "\n";
652 for (int i = 0; i < vout.size(); i++)
653 str += " " + vout[i].ToString() + "\n";
659 printf("%s", ToString().c_str());
663 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
664 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
665 bool ReadFromDisk(COutPoint prevout);
666 bool DisconnectInputs(CTxDB& txdb);
667 bool ConnectInputs(CTxDB& txdb, std::map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
668 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee=0);
669 bool ClientConnectInputs();
670 bool CheckTransaction() const;
671 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
672 bool AcceptToMemoryPool(bool fCheckInputs=true, bool* pfMissingInputs=NULL);
674 bool AddToMemoryPoolUnchecked();
676 bool RemoveFromMemoryPool();
677 bool GetCoinAge(CTxDB& txdb, uint64& nCoinAge) const; // ppcoin: get transaction coin age
678 bool CheckProofOfStake(unsigned int nBits) const;
686 // A transaction with a merkle branch linking it to the block chain
688 class CMerkleTx : public CTransaction
692 std::vector<uint256> vMerkleBranch;
696 mutable char fMerkleVerified;
704 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
713 fMerkleVerified = false;
719 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
720 nVersion = this->nVersion;
721 READWRITE(hashBlock);
722 READWRITE(vMerkleBranch);
727 int SetMerkleBranch(const CBlock* pblock=NULL);
728 int GetDepthInMainChain(int& nHeightRet) const;
729 int GetDepthInMainChain() const { int nHeight; return GetDepthInMainChain(nHeight); }
730 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
731 int GetBlocksToMaturity() const;
732 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
733 bool AcceptToMemoryPool();
740 // A txdb record that contains the disk location of a transaction and the
741 // locations of transactions that spend its outputs. vSpent is really only
742 // used as a flag, but having the location is very helpful for debugging.
748 std::vector<CDiskTxPos> vSpent;
755 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
758 vSpent.resize(nOutputs);
763 if (!(nType & SER_GETHASH))
780 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
782 return (a.pos == b.pos &&
783 a.vSpent == b.vSpent);
786 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
790 int GetDepthInMainChain() const;
798 // Nodes collect new transactions into a block, hash them into a hash tree,
799 // and scan through nonce values to make the block's hash satisfy proof-of-work
800 // requirements. When they solve the proof-of-work, they broadcast the block
801 // to everyone and the block is added to the block chain. The first transaction
802 // in the block is a special one that creates a new coin owned by the creator
805 // Blocks are appended to blk0001.dat files on disk. Their location on disk
806 // is indexed by CBlockIndex objects in memory.
813 uint256 hashPrevBlock;
814 uint256 hashMerkleRoot;
820 std::vector<CTransaction> vtx;
822 // ppcoin: block signature - signed by coin base txout[0]'s owner
823 std::vector<unsigned char> vchBlockSig;
826 mutable std::vector<uint256> vMerkleTree;
828 // Denial-of-service detection:
830 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
839 READWRITE(this->nVersion);
840 nVersion = this->nVersion;
841 READWRITE(hashPrevBlock);
842 READWRITE(hashMerkleRoot);
847 // ConnectBlock depends on vtx following header to generate CDiskTxPos
848 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
851 READWRITE(vchBlockSig);
855 const_cast<CBlock*>(this)->vtx.clear();
856 const_cast<CBlock*>(this)->vchBlockSig.clear();
879 uint256 GetHash() const
881 return Hash(BEGIN(nVersion), END(nNonce));
884 int64 GetBlockTime() const
889 // ppcoin: two types of block: proof-of-work or proof-of-stake
890 bool IsProofOfStake() const
892 return (vtx.size() > 1 && vtx[1].IsCoinStake());
895 bool IsProofOfWork() const
897 return !IsProofOfStake();
900 COutPoint GetProofOfStake() const
902 return IsProofOfStake()? vtx[1].vin[0].prevout : COutPoint();
905 // ppcoin: get max transaction timestamp
906 int64 GetMaxTransactionTime() const
908 int64 maxTransactionTime = 0;
909 BOOST_FOREACH(const CTransaction& tx, vtx)
910 maxTransactionTime = std::max(maxTransactionTime, (int64)tx.nTime);
911 return maxTransactionTime;
914 int GetSigOpCount() const
917 BOOST_FOREACH(const CTransaction& tx, vtx)
918 n += tx.GetSigOpCount();
923 uint256 BuildMerkleTree() const
926 BOOST_FOREACH(const CTransaction& tx, vtx)
927 vMerkleTree.push_back(tx.GetHash());
929 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
931 for (int i = 0; i < nSize; i += 2)
933 int i2 = std::min(i+1, nSize-1);
934 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
935 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
939 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
942 std::vector<uint256> GetMerkleBranch(int nIndex) const
944 if (vMerkleTree.empty())
946 std::vector<uint256> vMerkleBranch;
948 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
950 int i = std::min(nIndex^1, nSize-1);
951 vMerkleBranch.push_back(vMerkleTree[j+i]);
955 return vMerkleBranch;
958 static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
962 BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
965 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
967 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
974 bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
976 // Open history file to append
977 CAutoFile fileout = AppendBlockFile(nFileRet);
979 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
981 // Write index header
982 unsigned int nSize = fileout.GetSerializeSize(*this);
983 fileout << FLATDATA(pchMessageStart) << nSize;
986 nBlockPosRet = ftell(fileout);
987 if (nBlockPosRet == -1)
988 return error("CBlock::WriteToDisk() : ftell failed");
991 // Flush stdio buffers and commit to disk before returning
993 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
996 _commit(_fileno(fileout));
998 fsync(fileno(fileout));
1005 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
1009 // Open history file to read
1010 CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");
1012 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1013 if (!fReadTransactions)
1014 filein.nType |= SER_BLOCKHEADERONLY;
1020 if (fReadTransactions && IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
1021 return error("CBlock::ReadFromDisk() : errors in block header");
1030 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d, vchBlockSig=%s)\n",
1031 GetHash().ToString().substr(0,20).c_str(),
1033 hashPrevBlock.ToString().substr(0,20).c_str(),
1034 hashMerkleRoot.ToString().substr(0,10).c_str(),
1035 nTime, nBits, nNonce,
1037 HexStr(vchBlockSig.begin(), vchBlockSig.end()).c_str());
1038 for (int i = 0; i < vtx.size(); i++)
1043 printf(" vMerkleTree: ");
1044 for (int i = 0; i < vMerkleTree.size(); i++)
1045 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1050 bool SignBlock(const CKeyStore& keystore)
1052 std::vector<std::pair<opcodetype, valtype> > vSolution;
1053 const CTxOut& txout = IsProofOfStake()? vtx[1].vout[1] : vtx[0].vout[0];
1055 if (!Solver(txout.scriptPubKey, vSolution))
1057 BOOST_FOREACH(PAIRTYPE(opcodetype, valtype)& item, vSolution)
1059 if (item.first == OP_PUBKEY)
1062 const valtype& vchPubKey = item.second;
1064 if (!keystore.GetKey(Hash160(vchPubKey), key))
1066 if (key.GetPubKey() != vchPubKey)
1068 return key.Sign(GetHash(), vchBlockSig);
1074 bool CheckBlockSignature() const
1076 if (GetHash() == hashGenesisBlock)
1077 return vchBlockSig.empty();
1079 std::vector<std::pair<opcodetype, valtype> > vSolution;
1080 const CTxOut& txout = IsProofOfStake()? vtx[1].vout[1] : vtx[0].vout[0];
1082 if (!Solver(txout.scriptPubKey, vSolution))
1084 BOOST_FOREACH(PAIRTYPE(opcodetype, valtype)& item, vSolution)
1086 if (item.first == OP_PUBKEY)
1088 const valtype& vchPubKey = item.second;
1090 if (!key.SetPubKey(vchPubKey))
1092 if (vchBlockSig.empty())
1094 return key.Verify(GetHash(), vchBlockSig);
1100 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1101 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1102 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1103 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1104 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1105 bool CheckBlock() const;
1107 bool GetCoinAge(uint64& nCoinAge) const; // ppcoin: calculate total coin age spent in block
1116 // The block chain is a tree shaped structure starting with the
1117 // genesis block at the root, with each block potentially having multiple
1118 // candidates to be the next block. pprev and pnext link a path through the
1119 // main/longest chain. A blockindex may have multiple pprev pointing back
1120 // to it, but pnext will only point forward to the longest branch, or will
1121 // be null if the block is not part of the longest chain.
1126 const uint256* phashBlock;
1130 unsigned int nBlockPos;
1131 uint64 nChainTrust;// ppcoin: trust score of chain, in the unit of coin-days
1133 int nCheckpoint; // ppcoin: chain auto checkpoint height
1134 bool fProofOfStake; // ppcoin: is the block of proof-of-stake type
1135 COutPoint prevoutStake;
1139 uint256 hashMerkleRoot;
1142 unsigned int nNonce;
1155 fProofOfStake = true;
1156 prevoutStake.SetNull();
1165 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1171 nBlockPos = nBlockPosIn;
1175 fProofOfStake = block.IsProofOfStake();
1177 prevoutStake = block.vtx[1].vin[0].prevout;
1179 prevoutStake.SetNull();
1181 nVersion = block.nVersion;
1182 hashMerkleRoot = block.hashMerkleRoot;
1183 nTime = block.nTime;
1184 nBits = block.nBits;
1185 nNonce = block.nNonce;
1188 CBlock GetBlockHeader() const
1191 block.nVersion = nVersion;
1193 block.hashPrevBlock = pprev->GetBlockHash();
1194 block.hashMerkleRoot = hashMerkleRoot;
1195 block.nTime = nTime;
1196 block.nBits = nBits;
1197 block.nNonce = nNonce;
1201 uint256 GetBlockHash() const
1206 int64 GetBlockTime() const
1208 return (int64)nTime;
1211 int64 GetBlockTrust() const
1213 return (nChainTrust - (pprev? pprev->nChainTrust : 0));
1216 bool IsInMainChain() const
1218 return (pnext || this == pindexBest);
1221 bool CheckIndex() const
1223 return IsProofOfWork() ? CheckProofOfWork(GetBlockHash(), nBits) : true;
1226 bool EraseBlockFromDisk()
1228 // Open history file
1229 CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");
1233 // Overwrite with empty null block
1241 enum { nMedianTimeSpan=11 };
1243 int64 GetMedianTimePast() const
1245 int64 pmedian[nMedianTimeSpan];
1246 int64* pbegin = &pmedian[nMedianTimeSpan];
1247 int64* pend = &pmedian[nMedianTimeSpan];
1249 const CBlockIndex* pindex = this;
1250 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1251 *(--pbegin) = pindex->GetBlockTime();
1253 std::sort(pbegin, pend);
1254 return pbegin[(pend - pbegin)/2];
1257 int64 GetMedianTime() const
1259 const CBlockIndex* pindex = this;
1260 for (int i = 0; i < nMedianTimeSpan/2; i++)
1263 return GetBlockTime();
1264 pindex = pindex->pnext;
1266 return pindex->GetMedianTimePast();
1269 bool IsProofOfWork() const
1271 return !fProofOfStake;
1274 bool IsProofOfStake() const
1276 return fProofOfStake;
1279 std::string ToString() const
1281 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nChainTrust=%"PRI64d" nHeight=%d, nCheckpoint=%d, fProofOfStake=%d prevoutStake=(%s) merkle=%s, hashBlock=%s)",
1282 pprev, pnext, nFile, nBlockPos, nChainTrust, nHeight, nCheckpoint,
1283 fProofOfStake, prevoutStake.ToString().c_str(),
1284 hashMerkleRoot.ToString().substr(0,10).c_str(),
1285 GetBlockHash().ToString().substr(0,20).c_str());
1290 printf("%s\n", ToString().c_str());
1297 // Used to marshal pointers into hashes for db storage.
1299 class CDiskBlockIndex : public CBlockIndex
1311 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1313 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1314 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1319 if (!(nType & SER_GETHASH))
1320 READWRITE(nVersion);
1322 READWRITE(hashNext);
1324 READWRITE(nBlockPos);
1325 READWRITE(nChainTrust);
1327 READWRITE(nCheckpoint);
1328 READWRITE(fProofOfStake);
1329 READWRITE(prevoutStake);
1332 READWRITE(this->nVersion);
1333 READWRITE(hashPrev);
1334 READWRITE(hashMerkleRoot);
1340 uint256 GetBlockHash() const
1343 block.nVersion = nVersion;
1344 block.hashPrevBlock = hashPrev;
1345 block.hashMerkleRoot = hashMerkleRoot;
1346 block.nTime = nTime;
1347 block.nBits = nBits;
1348 block.nNonce = nNonce;
1349 return block.GetHash();
1353 std::string ToString() const
1355 std::string str = "CDiskBlockIndex(";
1356 str += CBlockIndex::ToString();
1357 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1358 GetBlockHash().ToString().c_str(),
1359 hashPrev.ToString().substr(0,20).c_str(),
1360 hashNext.ToString().substr(0,20).c_str());
1366 printf("%s\n", ToString().c_str());
1378 // Describes a place in the block chain to another node such that if the
1379 // other node doesn't have the same branch, it can find a recent common trunk.
1380 // The further back it is, the further before the fork it may be.
1385 std::vector<uint256> vHave;
1392 explicit CBlockLocator(const CBlockIndex* pindex)
1397 explicit CBlockLocator(uint256 hashBlock)
1399 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1400 if (mi != mapBlockIndex.end())
1406 if (!(nType & SER_GETHASH))
1407 READWRITE(nVersion);
1418 return vHave.empty();
1421 void Set(const CBlockIndex* pindex)
1427 vHave.push_back(pindex->GetBlockHash());
1429 // Exponentially larger steps back
1430 for (int i = 0; pindex && i < nStep; i++)
1431 pindex = pindex->pprev;
1432 if (vHave.size() > 10)
1435 vHave.push_back(hashGenesisBlock);
1438 int GetDistanceBack()
1440 // Retrace how far back it was in the sender's branch
1443 BOOST_FOREACH(const uint256& hash, vHave)
1445 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1446 if (mi != mapBlockIndex.end())
1448 CBlockIndex* pindex = (*mi).second;
1449 if (pindex->IsInMainChain())
1459 CBlockIndex* GetBlockIndex()
1461 // Find the first block the caller has in the main chain
1462 BOOST_FOREACH(const uint256& hash, vHave)
1464 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1465 if (mi != mapBlockIndex.end())
1467 CBlockIndex* pindex = (*mi).second;
1468 if (pindex->IsInMainChain())
1472 return pindexGenesisBlock;
1475 uint256 GetBlockHash()
1477 // Find the first block the caller has in the main chain
1478 BOOST_FOREACH(const uint256& hash, vHave)
1480 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1481 if (mi != mapBlockIndex.end())
1483 CBlockIndex* pindex = (*mi).second;
1484 if (pindex->IsInMainChain())
1488 return hashGenesisBlock;
1493 CBlockIndex* pindex = GetBlockIndex();
1496 return pindex->nHeight;
1509 // Alerts are for notifying old versions if they become too obsolete and
1510 // need to upgrade. The message is displayed in the status bar.
1511 // Alert messages are broadcast as a vector of signed data. Unserializing may
1512 // not read the entire buffer if the alert is for a newer version, but older
1513 // versions can still relay the original data.
1515 class CUnsignedAlert
1519 int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
1523 std::set<int> setCancel;
1524 int nMinVer; // lowest version inclusive
1525 int nMaxVer; // highest version inclusive
1526 std::set<std::string> setSubVer; // empty matches all
1530 std::string strComment;
1531 std::string strStatusBar;
1532 std::string strReserved;
1536 READWRITE(this->nVersion);
1537 nVersion = this->nVersion;
1538 READWRITE(nRelayUntil);
1539 READWRITE(nExpiration);
1542 READWRITE(setCancel);
1545 READWRITE(setSubVer);
1546 READWRITE(nPriority);
1548 READWRITE(strComment);
1549 READWRITE(strStatusBar);
1550 READWRITE(strReserved);
1567 strStatusBar.clear();
1568 strReserved.clear();
1571 std::string ToString() const
1573 std::string strSetCancel;
1574 BOOST_FOREACH(int n, setCancel)
1575 strSetCancel += strprintf("%d ", n);
1576 std::string strSetSubVer;
1577 BOOST_FOREACH(std::string str, setSubVer)
1578 strSetSubVer += "\"" + str + "\" ";
1582 " nRelayUntil = %"PRI64d"\n"
1583 " nExpiration = %"PRI64d"\n"
1591 " strComment = \"%s\"\n"
1592 " strStatusBar = \"%s\"\n"
1599 strSetCancel.c_str(),
1602 strSetSubVer.c_str(),
1605 strStatusBar.c_str());
1610 printf("%s", ToString().c_str());
1614 class CAlert : public CUnsignedAlert
1617 std::vector<unsigned char> vchMsg;
1618 std::vector<unsigned char> vchSig;
1633 CUnsignedAlert::SetNull();
1640 return (nExpiration == 0);
1643 uint256 GetHash() const
1645 return SerializeHash(*this);
1648 bool IsInEffect() const
1650 return (GetAdjustedTime() < nExpiration);
1653 bool Cancels(const CAlert& alert) const
1656 return false; // this was a no-op before 31403
1657 return (alert.nID <= nCancel || setCancel.count(alert.nID));
1660 bool AppliesTo(int nVersion, std::string strSubVerIn) const
1662 return (IsInEffect() &&
1663 nMinVer <= nVersion && nVersion <= nMaxVer &&
1664 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1667 bool AppliesToMe() const
1669 return AppliesTo(VERSION, ::pszSubVer);
1672 bool RelayTo(CNode* pnode) const
1676 // returns true if wasn't already contained in the set
1677 if (pnode->setKnown.insert(GetHash()).second)
1679 if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
1681 GetAdjustedTime() < nRelayUntil)
1683 pnode->PushMessage("alert", *this);
1690 bool CheckSignature()
1693 if (!key.SetPubKey(ParseHex("0487ca85b6ae9d311f996c7616d20d0c88a5b4f07d25e78f419019f35cce6522acf978b2d99f0e7a58db1f120439e5c1889266927854aa57c93956c2569188a539")))
1694 return error("CAlert::CheckSignature() : SetPubKey failed");
1695 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
1696 return error("CAlert::CheckSignature() : verify signature failed");
1698 // Now unserialize the data
1699 CDataStream sMsg(vchMsg);
1700 sMsg >> *(CUnsignedAlert*)this;
1704 bool ProcessAlert();