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);
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 std::pair<COutPoint, unsigned int> GetProofOfStake() const
902 return IsProofOfStake()? std::make_pair(vtx[1].vin[0].prevout, vtx[1].nTime) : std::make_pair(COutPoint(), (unsigned int)0);
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;
1136 unsigned int nStakeTime;
1140 uint256 hashMerkleRoot;
1143 unsigned int nNonce;
1156 fProofOfStake = true;
1157 prevoutStake.SetNull();
1167 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1173 nBlockPos = nBlockPosIn;
1177 fProofOfStake = block.IsProofOfStake();
1180 prevoutStake = block.vtx[1].vin[0].prevout;
1181 nStakeTime = block.vtx[1].nTime;
1185 prevoutStake.SetNull();
1189 nVersion = block.nVersion;
1190 hashMerkleRoot = block.hashMerkleRoot;
1191 nTime = block.nTime;
1192 nBits = block.nBits;
1193 nNonce = block.nNonce;
1196 CBlock GetBlockHeader() const
1199 block.nVersion = nVersion;
1201 block.hashPrevBlock = pprev->GetBlockHash();
1202 block.hashMerkleRoot = hashMerkleRoot;
1203 block.nTime = nTime;
1204 block.nBits = nBits;
1205 block.nNonce = nNonce;
1209 uint256 GetBlockHash() const
1214 int64 GetBlockTime() const
1216 return (int64)nTime;
1219 int64 GetBlockTrust() const
1221 return (nChainTrust - (pprev? pprev->nChainTrust : 0));
1224 bool IsInMainChain() const
1226 return (pnext || this == pindexBest);
1229 bool CheckIndex() const
1231 return IsProofOfWork() ? CheckProofOfWork(GetBlockHash(), nBits) : true;
1234 bool EraseBlockFromDisk()
1236 // Open history file
1237 CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");
1241 // Overwrite with empty null block
1249 enum { nMedianTimeSpan=11 };
1251 int64 GetMedianTimePast() const
1253 int64 pmedian[nMedianTimeSpan];
1254 int64* pbegin = &pmedian[nMedianTimeSpan];
1255 int64* pend = &pmedian[nMedianTimeSpan];
1257 const CBlockIndex* pindex = this;
1258 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1259 *(--pbegin) = pindex->GetBlockTime();
1261 std::sort(pbegin, pend);
1262 return pbegin[(pend - pbegin)/2];
1265 int64 GetMedianTime() const
1267 const CBlockIndex* pindex = this;
1268 for (int i = 0; i < nMedianTimeSpan/2; i++)
1271 return GetBlockTime();
1272 pindex = pindex->pnext;
1274 return pindex->GetMedianTimePast();
1277 bool IsProofOfWork() const
1279 return !fProofOfStake;
1282 bool IsProofOfStake() const
1284 return fProofOfStake;
1287 std::string ToString() const
1289 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)",
1290 pprev, pnext, nFile, nBlockPos, nChainTrust, nHeight, nCheckpoint,
1291 fProofOfStake, prevoutStake.ToString().c_str(), nStakeTime,
1292 hashMerkleRoot.ToString().substr(0,10).c_str(),
1293 GetBlockHash().ToString().substr(0,20).c_str());
1298 printf("%s\n", ToString().c_str());
1305 // Used to marshal pointers into hashes for db storage.
1307 class CDiskBlockIndex : public CBlockIndex
1319 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1321 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1322 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1327 if (!(nType & SER_GETHASH))
1328 READWRITE(nVersion);
1330 READWRITE(hashNext);
1332 READWRITE(nBlockPos);
1333 READWRITE(nChainTrust);
1335 READWRITE(nCheckpoint);
1336 READWRITE(fProofOfStake);
1339 READWRITE(prevoutStake);
1340 READWRITE(nStakeTime);
1344 const_cast<CDiskBlockIndex*>(this)->prevoutStake.SetNull();
1345 const_cast<CDiskBlockIndex*>(this)->nStakeTime = 0;
1349 READWRITE(this->nVersion);
1350 READWRITE(hashPrev);
1351 READWRITE(hashMerkleRoot);
1357 uint256 GetBlockHash() const
1360 block.nVersion = nVersion;
1361 block.hashPrevBlock = hashPrev;
1362 block.hashMerkleRoot = hashMerkleRoot;
1363 block.nTime = nTime;
1364 block.nBits = nBits;
1365 block.nNonce = nNonce;
1366 return block.GetHash();
1370 std::string ToString() const
1372 std::string str = "CDiskBlockIndex(";
1373 str += CBlockIndex::ToString();
1374 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1375 GetBlockHash().ToString().c_str(),
1376 hashPrev.ToString().substr(0,20).c_str(),
1377 hashNext.ToString().substr(0,20).c_str());
1383 printf("%s\n", ToString().c_str());
1395 // Describes a place in the block chain to another node such that if the
1396 // other node doesn't have the same branch, it can find a recent common trunk.
1397 // The further back it is, the further before the fork it may be.
1402 std::vector<uint256> vHave;
1409 explicit CBlockLocator(const CBlockIndex* pindex)
1414 explicit CBlockLocator(uint256 hashBlock)
1416 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1417 if (mi != mapBlockIndex.end())
1423 if (!(nType & SER_GETHASH))
1424 READWRITE(nVersion);
1435 return vHave.empty();
1438 void Set(const CBlockIndex* pindex)
1444 vHave.push_back(pindex->GetBlockHash());
1446 // Exponentially larger steps back
1447 for (int i = 0; pindex && i < nStep; i++)
1448 pindex = pindex->pprev;
1449 if (vHave.size() > 10)
1452 vHave.push_back(hashGenesisBlock);
1455 int GetDistanceBack()
1457 // Retrace how far back it was in the sender's branch
1460 BOOST_FOREACH(const uint256& hash, vHave)
1462 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1463 if (mi != mapBlockIndex.end())
1465 CBlockIndex* pindex = (*mi).second;
1466 if (pindex->IsInMainChain())
1476 CBlockIndex* GetBlockIndex()
1478 // Find the first block the caller has in the main chain
1479 BOOST_FOREACH(const uint256& hash, vHave)
1481 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1482 if (mi != mapBlockIndex.end())
1484 CBlockIndex* pindex = (*mi).second;
1485 if (pindex->IsInMainChain())
1489 return pindexGenesisBlock;
1492 uint256 GetBlockHash()
1494 // Find the first block the caller has in the main chain
1495 BOOST_FOREACH(const uint256& hash, vHave)
1497 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1498 if (mi != mapBlockIndex.end())
1500 CBlockIndex* pindex = (*mi).second;
1501 if (pindex->IsInMainChain())
1505 return hashGenesisBlock;
1510 CBlockIndex* pindex = GetBlockIndex();
1513 return pindex->nHeight;
1526 // Alerts are for notifying old versions if they become too obsolete and
1527 // need to upgrade. The message is displayed in the status bar.
1528 // Alert messages are broadcast as a vector of signed data. Unserializing may
1529 // not read the entire buffer if the alert is for a newer version, but older
1530 // versions can still relay the original data.
1532 class CUnsignedAlert
1536 int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
1540 std::set<int> setCancel;
1541 int nMinVer; // lowest version inclusive
1542 int nMaxVer; // highest version inclusive
1543 std::set<std::string> setSubVer; // empty matches all
1547 std::string strComment;
1548 std::string strStatusBar;
1549 std::string strReserved;
1553 READWRITE(this->nVersion);
1554 nVersion = this->nVersion;
1555 READWRITE(nRelayUntil);
1556 READWRITE(nExpiration);
1559 READWRITE(setCancel);
1562 READWRITE(setSubVer);
1563 READWRITE(nPriority);
1565 READWRITE(strComment);
1566 READWRITE(strStatusBar);
1567 READWRITE(strReserved);
1584 strStatusBar.clear();
1585 strReserved.clear();
1588 std::string ToString() const
1590 std::string strSetCancel;
1591 BOOST_FOREACH(int n, setCancel)
1592 strSetCancel += strprintf("%d ", n);
1593 std::string strSetSubVer;
1594 BOOST_FOREACH(std::string str, setSubVer)
1595 strSetSubVer += "\"" + str + "\" ";
1599 " nRelayUntil = %"PRI64d"\n"
1600 " nExpiration = %"PRI64d"\n"
1608 " strComment = \"%s\"\n"
1609 " strStatusBar = \"%s\"\n"
1616 strSetCancel.c_str(),
1619 strSetSubVer.c_str(),
1622 strStatusBar.c_str());
1627 printf("%s", ToString().c_str());
1631 class CAlert : public CUnsignedAlert
1634 std::vector<unsigned char> vchMsg;
1635 std::vector<unsigned char> vchSig;
1650 CUnsignedAlert::SetNull();
1657 return (nExpiration == 0);
1660 uint256 GetHash() const
1662 return SerializeHash(*this);
1665 bool IsInEffect() const
1667 return (GetAdjustedTime() < nExpiration);
1670 bool Cancels(const CAlert& alert) const
1673 return false; // this was a no-op before 31403
1674 return (alert.nID <= nCancel || setCancel.count(alert.nID));
1677 bool AppliesTo(int nVersion, std::string strSubVerIn) const
1679 return (IsInEffect() &&
1680 nMinVer <= nVersion && nVersion <= nMaxVer &&
1681 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1684 bool AppliesToMe() const
1686 return AppliesTo(VERSION, ::pszSubVer);
1689 bool RelayTo(CNode* pnode) const
1693 // returns true if wasn't already contained in the set
1694 if (pnode->setKnown.insert(GetHash()).second)
1696 if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
1698 GetAdjustedTime() < nRelayUntil)
1700 pnode->PushMessage("alert", *this);
1707 bool CheckSignature()
1710 if (!key.SetPubKey(ParseHex("0487ca85b6ae9d311f996c7616d20d0c88a5b4f07d25e78f419019f35cce6522acf978b2d99f0e7a58db1f120439e5c1889266927854aa57c93956c2569188a539")))
1711 return error("CAlert::CheckSignature() : SetPubKey failed");
1712 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
1713 return error("CAlert::CheckSignature() : verify signature failed");
1715 // Now unserialize the data
1716 CDataStream sMsg(vchMsg);
1717 sMsg >> *(CUnsignedAlert*)this;
1721 bool ProcessAlert();