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;
70 extern std::map<uint256, CBlock*> mapOrphanBlocks;
73 extern int fGenerateBitcoins;
74 extern int64 nTransactionFee;
75 extern int fLimitProcessors;
76 extern int nLimitProcessors;
77 extern int fMinimizeToTray;
78 extern int fMinimizeOnClose;
80 extern int64 nBalanceReserve;
90 void RegisterWallet(CWallet* pwalletIn);
91 void UnregisterWallet(CWallet* pwalletIn);
92 bool ProcessBlock(CNode* pfrom, CBlock* pblock);
93 bool CheckDiskSpace(uint64 nAdditionalBytes=0);
94 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
95 FILE* AppendBlockFile(unsigned int& nFileRet);
96 bool LoadBlockIndex(bool fAllowNew=true);
97 void PrintBlockTree();
98 bool ProcessMessages(CNode* pfrom);
99 bool SendMessages(CNode* pto, bool fSendTrickle);
100 void GenerateBitcoins(bool fGenerate, CWallet* pwallet);
101 CBlock* CreateNewBlock(CWallet* pwallet, bool fProofOfWorkOnly=false);
102 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce);
103 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
104 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey);
105 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
106 int64 GetProofOfStakeReward(int64 nCoinAge);
107 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime);
108 int GetNumBlocksOfPeers();
109 bool IsInitialBlockDownload();
110 std::string GetWarnings(std::string strFor);
111 bool Reorganize(CTxDB& txdb, CBlockIndex* pindexNew);
112 uint256 WantedByOrphan(const CBlock* pblockOrphan);
113 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake);
125 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
128 bool WriteSetting(const std::string& strKey, const T& value)
131 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
133 std::string strWalletFile;
134 if (!GetWalletFile(pwallet, strWalletFile))
136 fOk |= CWalletDB(strWalletFile).WriteSetting(strKey, value);
146 unsigned int nBlockPos;
154 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
157 nBlockPos = nBlockPosIn;
161 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
162 void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
163 bool IsNull() const { return (nFile == -1); }
165 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
167 return (a.nFile == b.nFile &&
168 a.nBlockPos == b.nBlockPos &&
169 a.nTxPos == b.nTxPos);
172 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
177 std::string ToString() const
180 return strprintf("null");
182 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
187 printf("%s", ToString().c_str());
200 CInPoint() { SetNull(); }
201 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
202 void SetNull() { ptx = NULL; n = -1; }
203 bool IsNull() const { return (ptx == NULL && n == -1); }
215 COutPoint() { SetNull(); }
216 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
217 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
218 void SetNull() { hash = 0; n = -1; }
219 bool IsNull() const { return (hash == 0 && n == -1); }
221 friend bool operator<(const COutPoint& a, const COutPoint& b)
223 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
226 friend bool operator==(const COutPoint& a, const COutPoint& b)
228 return (a.hash == b.hash && a.n == b.n);
231 friend bool operator!=(const COutPoint& a, const COutPoint& b)
236 std::string ToString() const
238 return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,10).c_str(), n);
243 printf("%s\n", ToString().c_str());
251 // An input of a transaction. It contains the location of the previous
252 // transaction's output that it claims and a signature that matches the
253 // output's public key.
260 unsigned int nSequence;
264 nSequence = UINT_MAX;
267 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
270 scriptSig = scriptSigIn;
271 nSequence = nSequenceIn;
274 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
276 prevout = COutPoint(hashPrevTx, nOut);
277 scriptSig = scriptSigIn;
278 nSequence = nSequenceIn;
284 READWRITE(scriptSig);
285 READWRITE(nSequence);
290 return (nSequence == UINT_MAX);
293 friend bool operator==(const CTxIn& a, const CTxIn& b)
295 return (a.prevout == b.prevout &&
296 a.scriptSig == b.scriptSig &&
297 a.nSequence == b.nSequence);
300 friend bool operator!=(const CTxIn& a, const CTxIn& b)
305 std::string ToString() const
308 str += strprintf("CTxIn(");
309 str += prevout.ToString();
310 if (prevout.IsNull())
311 str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
313 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
314 if (nSequence != UINT_MAX)
315 str += strprintf(", nSequence=%u", nSequence);
322 printf("%s\n", ToString().c_str());
330 // An output of a transaction. It contains the public key that the next input
331 // must be able to sign with to claim it.
337 CScript scriptPubKey;
344 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
347 scriptPubKey = scriptPubKeyIn;
353 READWRITE(scriptPubKey);
359 scriptPubKey.clear();
364 return (nValue == -1);
370 scriptPubKey.clear();
375 return (nValue == 0 && scriptPubKey.empty());
378 uint256 GetHash() const
380 return SerializeHash(*this);
383 friend bool operator==(const CTxOut& a, const CTxOut& b)
385 return (a.nValue == b.nValue &&
386 a.scriptPubKey == b.scriptPubKey);
389 friend bool operator!=(const CTxOut& a, const CTxOut& b)
394 std::string ToString() const
396 if (IsEmpty()) return "CTxOut(empty)";
397 if (scriptPubKey.size() < 6)
398 return "CTxOut(error)";
399 return strprintf("CTxOut(nValue=%s, scriptPubKey=%s)", FormatMoney(nValue).c_str(), scriptPubKey.ToString().substr(0,30).c_str());
404 printf("%s\n", ToString().c_str());
412 // The basic transaction that is broadcasted on the network and contained in
413 // blocks. A transaction can contain multiple inputs and outputs.
420 std::vector<CTxIn> vin;
421 std::vector<CTxOut> vout;
422 unsigned int nLockTime;
424 // Denial-of-service detection:
426 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
435 READWRITE(this->nVersion);
436 nVersion = this->nVersion;
440 READWRITE(nLockTime);
446 nTime = GetAdjustedTime();
450 nDoS = 0; // Denial-of-service prevention
455 return (vin.empty() && vout.empty());
458 uint256 GetHash() const
460 return SerializeHash(*this);
463 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
465 // Time based nLockTime implemented in 0.1.6
468 if (nBlockHeight == 0)
469 nBlockHeight = nBestHeight;
471 nBlockTime = GetAdjustedTime();
472 if ((int64)nLockTime < (nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
474 BOOST_FOREACH(const CTxIn& txin, vin)
480 bool IsNewerThan(const CTransaction& old) const
482 if (vin.size() != old.vin.size())
484 for (int i = 0; i < vin.size(); i++)
485 if (vin[i].prevout != old.vin[i].prevout)
489 unsigned int nLowest = UINT_MAX;
490 for (int i = 0; i < vin.size(); i++)
492 if (vin[i].nSequence != old.vin[i].nSequence)
494 if (vin[i].nSequence <= nLowest)
497 nLowest = vin[i].nSequence;
499 if (old.vin[i].nSequence < nLowest)
502 nLowest = old.vin[i].nSequence;
509 bool IsCoinBase() const
511 return (vin.size() == 1 && vin[0].prevout.IsNull() && vout.size() == 1);
514 bool IsCoinStake() const
516 // ppcoin: the coin stake transaction is marked with the first output empty
517 return (vin.size() > 0 && vout.size() == 2 && vout[0].IsEmpty());
520 int GetSigOpCount() const
523 BOOST_FOREACH(const CTxIn& txin, vin)
524 n += txin.scriptSig.GetSigOpCount();
525 BOOST_FOREACH(const CTxOut& txout, vout)
526 n += txout.scriptPubKey.GetSigOpCount();
530 bool IsStandard() const
532 BOOST_FOREACH(const CTxIn& txin, vin)
533 if (!txin.scriptSig.IsPushOnly())
534 return error("nonstandard txin: %s", txin.scriptSig.ToString().c_str());
535 BOOST_FOREACH(const CTxOut& txout, vout)
536 if (!::IsStandard(txout.scriptPubKey))
537 return error("nonstandard txout: %s", txout.scriptPubKey.ToString().c_str());
541 int64 GetValueOut() const
544 BOOST_FOREACH(const CTxOut& txout, vout)
546 nValueOut += txout.nValue;
547 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
548 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
553 static bool AllowFree(double dPriority)
555 // Large (in bytes) low-priority (new, small-coin) transactions
557 return dPriority > COIN * 144 / 250;
560 int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=false, bool fForRelay=false) const
562 // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
563 int64 nBaseFee = fForRelay ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
565 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);
566 unsigned int nNewBlockSize = nBlockSize + nBytes;
567 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
573 // Transactions under 10K are free
574 // (about 4500bc if made of 50bc inputs)
580 // Free transaction area
581 if (nNewBlockSize < 27000)
586 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
587 if (nMinFee < nBaseFee)
588 BOOST_FOREACH(const CTxOut& txout, vout)
589 if (txout.nValue < CENT)
592 // Raise the price as the block approaches full
593 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
595 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
597 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
600 if (!MoneyRange(nMinFee))
606 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
608 CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");
610 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
613 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
614 return error("CTransaction::ReadFromDisk() : fseek failed");
617 // Return file pointer
620 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
621 return error("CTransaction::ReadFromDisk() : second fseek failed");
622 *pfileRet = filein.release();
627 friend bool operator==(const CTransaction& a, const CTransaction& b)
629 return (a.nVersion == b.nVersion &&
630 a.nTime == b.nTime &&
633 a.nLockTime == b.nLockTime);
636 friend bool operator!=(const CTransaction& a, const CTransaction& b)
642 std::string ToString() const
645 str += IsCoinBase()? "Coinbase" : (IsCoinStake()? "Coinstake" : "CTransaction");
646 str += strprintf("(hash=%s, nTime=%d, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
647 GetHash().ToString().substr(0,10).c_str(),
653 for (int i = 0; i < vin.size(); i++)
654 str += " " + vin[i].ToString() + "\n";
655 for (int i = 0; i < vout.size(); i++)
656 str += " " + vout[i].ToString() + "\n";
662 printf("%s", ToString().c_str());
666 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
667 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
668 bool ReadFromDisk(COutPoint prevout);
669 bool DisconnectInputs(CTxDB& txdb);
670 bool ConnectInputs(CTxDB& txdb, std::map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
671 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee=0);
672 bool ClientConnectInputs();
673 bool CheckTransaction() const;
674 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
675 bool AcceptToMemoryPool(bool fCheckInputs=true, bool* pfMissingInputs=NULL);
677 bool AddToMemoryPoolUnchecked();
679 bool RemoveFromMemoryPool();
680 bool GetCoinAge(CTxDB& txdb, uint64& nCoinAge) const; // ppcoin: get transaction coin age
681 bool CheckProofOfStake(unsigned int nBits) const;
689 // A transaction with a merkle branch linking it to the block chain
691 class CMerkleTx : public CTransaction
695 std::vector<uint256> vMerkleBranch;
699 mutable char fMerkleVerified;
707 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
716 fMerkleVerified = false;
722 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
723 nVersion = this->nVersion;
724 READWRITE(hashBlock);
725 READWRITE(vMerkleBranch);
730 int SetMerkleBranch(const CBlock* pblock=NULL);
731 int GetDepthInMainChain(int& nHeightRet) const;
732 int GetDepthInMainChain() const { int nHeight; return GetDepthInMainChain(nHeight); }
733 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
734 int GetBlocksToMaturity() const;
735 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
736 bool AcceptToMemoryPool();
743 // A txdb record that contains the disk location of a transaction and the
744 // locations of transactions that spend its outputs. vSpent is really only
745 // used as a flag, but having the location is very helpful for debugging.
751 std::vector<CDiskTxPos> vSpent;
758 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
761 vSpent.resize(nOutputs);
766 if (!(nType & SER_GETHASH))
783 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
785 return (a.pos == b.pos &&
786 a.vSpent == b.vSpent);
789 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
793 int GetDepthInMainChain() const;
801 // Nodes collect new transactions into a block, hash them into a hash tree,
802 // and scan through nonce values to make the block's hash satisfy proof-of-work
803 // requirements. When they solve the proof-of-work, they broadcast the block
804 // to everyone and the block is added to the block chain. The first transaction
805 // in the block is a special one that creates a new coin owned by the creator
808 // Blocks are appended to blk0001.dat files on disk. Their location on disk
809 // is indexed by CBlockIndex objects in memory.
816 uint256 hashPrevBlock;
817 uint256 hashMerkleRoot;
823 std::vector<CTransaction> vtx;
825 // ppcoin: block signature - signed by coin base txout[0]'s owner
826 std::vector<unsigned char> vchBlockSig;
829 mutable std::vector<uint256> vMerkleTree;
831 // Denial-of-service detection:
833 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
842 READWRITE(this->nVersion);
843 nVersion = this->nVersion;
844 READWRITE(hashPrevBlock);
845 READWRITE(hashMerkleRoot);
850 // ConnectBlock depends on vtx following header to generate CDiskTxPos
851 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
854 READWRITE(vchBlockSig);
858 const_cast<CBlock*>(this)->vtx.clear();
859 const_cast<CBlock*>(this)->vchBlockSig.clear();
882 uint256 GetHash() const
884 return Hash(BEGIN(nVersion), END(nNonce));
887 int64 GetBlockTime() const
892 // ppcoin: two types of block: proof-of-work or proof-of-stake
893 bool IsProofOfStake() const
895 return (vtx.size() > 1 && vtx[1].IsCoinStake());
898 bool IsProofOfWork() const
900 return !IsProofOfStake();
903 std::pair<COutPoint, unsigned int> GetProofOfStake() const
905 return IsProofOfStake()? std::make_pair(vtx[1].vin[0].prevout, vtx[1].nTime) : std::make_pair(COutPoint(), (unsigned int)0);
908 // ppcoin: get max transaction timestamp
909 int64 GetMaxTransactionTime() const
911 int64 maxTransactionTime = 0;
912 BOOST_FOREACH(const CTransaction& tx, vtx)
913 maxTransactionTime = std::max(maxTransactionTime, (int64)tx.nTime);
914 return maxTransactionTime;
917 int GetSigOpCount() const
920 BOOST_FOREACH(const CTransaction& tx, vtx)
921 n += tx.GetSigOpCount();
926 uint256 BuildMerkleTree() const
929 BOOST_FOREACH(const CTransaction& tx, vtx)
930 vMerkleTree.push_back(tx.GetHash());
932 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
934 for (int i = 0; i < nSize; i += 2)
936 int i2 = std::min(i+1, nSize-1);
937 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
938 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
942 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
945 std::vector<uint256> GetMerkleBranch(int nIndex) const
947 if (vMerkleTree.empty())
949 std::vector<uint256> vMerkleBranch;
951 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
953 int i = std::min(nIndex^1, nSize-1);
954 vMerkleBranch.push_back(vMerkleTree[j+i]);
958 return vMerkleBranch;
961 static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
965 BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
968 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
970 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
977 bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
979 // Open history file to append
980 CAutoFile fileout = AppendBlockFile(nFileRet);
982 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
984 // Write index header
985 unsigned int nSize = fileout.GetSerializeSize(*this);
986 fileout << FLATDATA(pchMessageStart) << nSize;
989 nBlockPosRet = ftell(fileout);
990 if (nBlockPosRet == -1)
991 return error("CBlock::WriteToDisk() : ftell failed");
994 // Flush stdio buffers and commit to disk before returning
996 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
999 _commit(_fileno(fileout));
1001 fsync(fileno(fileout));
1008 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
1012 // Open history file to read
1013 CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");
1015 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1016 if (!fReadTransactions)
1017 filein.nType |= SER_BLOCKHEADERONLY;
1023 if (fReadTransactions && IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
1024 return error("CBlock::ReadFromDisk() : errors in block header");
1033 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d, vchBlockSig=%s)\n",
1034 GetHash().ToString().substr(0,20).c_str(),
1036 hashPrevBlock.ToString().substr(0,20).c_str(),
1037 hashMerkleRoot.ToString().substr(0,10).c_str(),
1038 nTime, nBits, nNonce,
1040 HexStr(vchBlockSig.begin(), vchBlockSig.end()).c_str());
1041 for (int i = 0; i < vtx.size(); i++)
1046 printf(" vMerkleTree: ");
1047 for (int i = 0; i < vMerkleTree.size(); i++)
1048 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1053 bool SignBlock(const CKeyStore& keystore)
1055 std::vector<std::pair<opcodetype, valtype> > vSolution;
1056 const CTxOut& txout = IsProofOfStake()? vtx[1].vout[1] : vtx[0].vout[0];
1058 if (!Solver(txout.scriptPubKey, vSolution))
1060 BOOST_FOREACH(PAIRTYPE(opcodetype, valtype)& item, vSolution)
1062 if (item.first == OP_PUBKEY)
1065 const valtype& vchPubKey = item.second;
1067 if (!keystore.GetKey(Hash160(vchPubKey), key))
1069 if (key.GetPubKey() != vchPubKey)
1071 return key.Sign(GetHash(), vchBlockSig);
1077 bool CheckBlockSignature() const
1079 if (GetHash() == hashGenesisBlock)
1080 return vchBlockSig.empty();
1082 std::vector<std::pair<opcodetype, valtype> > vSolution;
1083 const CTxOut& txout = IsProofOfStake()? vtx[1].vout[1] : vtx[0].vout[0];
1085 if (!Solver(txout.scriptPubKey, vSolution))
1087 BOOST_FOREACH(PAIRTYPE(opcodetype, valtype)& item, vSolution)
1089 if (item.first == OP_PUBKEY)
1091 const valtype& vchPubKey = item.second;
1093 if (!key.SetPubKey(vchPubKey))
1095 if (vchBlockSig.empty())
1097 return key.Verify(GetHash(), vchBlockSig);
1103 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1104 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1105 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1106 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1107 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1108 bool CheckBlock() const;
1110 bool GetCoinAge(uint64& nCoinAge) const; // ppcoin: calculate total coin age spent in block
1119 // The block chain is a tree shaped structure starting with the
1120 // genesis block at the root, with each block potentially having multiple
1121 // candidates to be the next block. pprev and pnext link a path through the
1122 // main/longest chain. A blockindex may have multiple pprev pointing back
1123 // to it, but pnext will only point forward to the longest branch, or will
1124 // be null if the block is not part of the longest chain.
1129 const uint256* phashBlock;
1133 unsigned int nBlockPos;
1134 uint64 nChainTrust;// ppcoin: trust score of chain, in the unit of coin-days
1136 bool fProofOfStake; // ppcoin: is the block of proof-of-stake type
1137 COutPoint prevoutStake;
1138 unsigned int nStakeTime;
1142 uint256 hashMerkleRoot;
1145 unsigned int nNonce;
1157 fProofOfStake = true;
1158 prevoutStake.SetNull();
1168 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1174 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, fProofOfStake=%d prevoutStake=(%s), nStakeTime=%d merkle=%s, hashBlock=%s)",
1290 pprev, pnext, nFile, nBlockPos, nChainTrust, nHeight,
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(fProofOfStake);
1338 READWRITE(prevoutStake);
1339 READWRITE(nStakeTime);
1343 const_cast<CDiskBlockIndex*>(this)->prevoutStake.SetNull();
1344 const_cast<CDiskBlockIndex*>(this)->nStakeTime = 0;
1348 READWRITE(this->nVersion);
1349 READWRITE(hashPrev);
1350 READWRITE(hashMerkleRoot);
1356 uint256 GetBlockHash() const
1359 block.nVersion = nVersion;
1360 block.hashPrevBlock = hashPrev;
1361 block.hashMerkleRoot = hashMerkleRoot;
1362 block.nTime = nTime;
1363 block.nBits = nBits;
1364 block.nNonce = nNonce;
1365 return block.GetHash();
1369 std::string ToString() const
1371 std::string str = "CDiskBlockIndex(";
1372 str += CBlockIndex::ToString();
1373 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1374 GetBlockHash().ToString().c_str(),
1375 hashPrev.ToString().substr(0,20).c_str(),
1376 hashNext.ToString().substr(0,20).c_str());
1382 printf("%s\n", ToString().c_str());
1394 // Describes a place in the block chain to another node such that if the
1395 // other node doesn't have the same branch, it can find a recent common trunk.
1396 // The further back it is, the further before the fork it may be.
1401 std::vector<uint256> vHave;
1408 explicit CBlockLocator(const CBlockIndex* pindex)
1413 explicit CBlockLocator(uint256 hashBlock)
1415 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1416 if (mi != mapBlockIndex.end())
1422 if (!(nType & SER_GETHASH))
1423 READWRITE(nVersion);
1434 return vHave.empty();
1437 void Set(const CBlockIndex* pindex)
1443 vHave.push_back(pindex->GetBlockHash());
1445 // Exponentially larger steps back
1446 for (int i = 0; pindex && i < nStep; i++)
1447 pindex = pindex->pprev;
1448 if (vHave.size() > 10)
1451 vHave.push_back(hashGenesisBlock);
1454 int GetDistanceBack()
1456 // Retrace how far back it was in the sender's branch
1459 BOOST_FOREACH(const uint256& hash, vHave)
1461 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1462 if (mi != mapBlockIndex.end())
1464 CBlockIndex* pindex = (*mi).second;
1465 if (pindex->IsInMainChain())
1475 CBlockIndex* GetBlockIndex()
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 pindexGenesisBlock;
1491 uint256 GetBlockHash()
1493 // Find the first block the caller has in the main chain
1494 BOOST_FOREACH(const uint256& hash, vHave)
1496 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1497 if (mi != mapBlockIndex.end())
1499 CBlockIndex* pindex = (*mi).second;
1500 if (pindex->IsInMainChain())
1504 return hashGenesisBlock;
1509 CBlockIndex* pindex = GetBlockIndex();
1512 return pindex->nHeight;
1525 // Alerts are for notifying old versions if they become too obsolete and
1526 // need to upgrade. The message is displayed in the status bar.
1527 // Alert messages are broadcast as a vector of signed data. Unserializing may
1528 // not read the entire buffer if the alert is for a newer version, but older
1529 // versions can still relay the original data.
1531 class CUnsignedAlert
1535 int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
1539 std::set<int> setCancel;
1540 int nMinVer; // lowest version inclusive
1541 int nMaxVer; // highest version inclusive
1542 std::set<std::string> setSubVer; // empty matches all
1546 std::string strComment;
1547 std::string strStatusBar;
1548 std::string strReserved;
1552 READWRITE(this->nVersion);
1553 nVersion = this->nVersion;
1554 READWRITE(nRelayUntil);
1555 READWRITE(nExpiration);
1558 READWRITE(setCancel);
1561 READWRITE(setSubVer);
1562 READWRITE(nPriority);
1564 READWRITE(strComment);
1565 READWRITE(strStatusBar);
1566 READWRITE(strReserved);
1583 strStatusBar.clear();
1584 strReserved.clear();
1587 std::string ToString() const
1589 std::string strSetCancel;
1590 BOOST_FOREACH(int n, setCancel)
1591 strSetCancel += strprintf("%d ", n);
1592 std::string strSetSubVer;
1593 BOOST_FOREACH(std::string str, setSubVer)
1594 strSetSubVer += "\"" + str + "\" ";
1598 " nRelayUntil = %"PRI64d"\n"
1599 " nExpiration = %"PRI64d"\n"
1607 " strComment = \"%s\"\n"
1608 " strStatusBar = \"%s\"\n"
1615 strSetCancel.c_str(),
1618 strSetSubVer.c_str(),
1621 strStatusBar.c_str());
1626 printf("%s", ToString().c_str());
1630 class CAlert : public CUnsignedAlert
1633 std::vector<unsigned char> vchMsg;
1634 std::vector<unsigned char> vchSig;
1649 CUnsignedAlert::SetNull();
1656 return (nExpiration == 0);
1659 uint256 GetHash() const
1661 return SerializeHash(*this);
1664 bool IsInEffect() const
1666 return (GetAdjustedTime() < nExpiration);
1669 bool Cancels(const CAlert& alert) const
1672 return false; // this was a no-op before 31403
1673 return (alert.nID <= nCancel || setCancel.count(alert.nID));
1676 bool AppliesTo(int nVersion, std::string strSubVerIn) const
1678 return (IsInEffect() &&
1679 nMinVer <= nVersion && nVersion <= nMaxVer &&
1680 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1683 bool AppliesToMe() const
1685 return AppliesTo(VERSION, ::pszSubVer);
1688 bool RelayTo(CNode* pnode) const
1692 // returns true if wasn't already contained in the set
1693 if (pnode->setKnown.insert(GetHash()).second)
1695 if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
1697 GetAdjustedTime() < nRelayUntil)
1699 pnode->PushMessage("alert", *this);
1706 bool CheckSignature()
1709 if (!key.SetPubKey(ParseHex("0487ca85b6ae9d311f996c7616d20d0c88a5b4f07d25e78f419019f35cce6522acf978b2d99f0e7a58db1f120439e5c1889266927854aa57c93956c2569188a539")))
1710 return error("CAlert::CheckSignature() : SetPubKey failed");
1711 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
1712 return error("CAlert::CheckSignature() : verify signature failed");
1714 // Now unserialize the data
1715 CDataStream sMsg(vchMsg);
1716 sMsg >> *(CUnsignedAlert*)this;
1720 bool ProcessAlert();