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;
49 static const uint256 hashGenesisBlockOfficial("0x000000007c82d1f0aa2896b01bf533a8cc26a1f44790be4ceb4ecde7bee24add");
50 static const uint256 hashGenesisBlockTestNet("0x00000007199508e34a9ff81e6ec0c477a4cccff2a4767a8eee39c11db367b008");
56 extern CCriticalSection cs_main;
57 extern std::map<uint256, CBlockIndex*> mapBlockIndex;
58 extern std::set<std::pair<COutPoint, unsigned int> > setStakeSeen;
59 extern uint256 hashGenesisBlock;
60 extern CBlockIndex* pindexGenesisBlock;
61 extern int nBestHeight;
62 extern uint64 nBestChainTrust;
63 extern uint64 nBestInvalidTrust;
64 extern uint256 hashBestChain;
65 extern CBlockIndex* pindexBest;
66 extern unsigned int nTransactionsUpdated;
67 extern double dHashesPerSec;
68 extern int64 nHPSTimerStart;
69 extern int64 nTimeBestReceived;
70 extern CCriticalSection cs_setpwalletRegistered;
71 extern std::set<CWallet*> setpwalletRegistered;
72 extern std::map<uint256, CBlock*> mapOrphanBlocks;
75 extern int fGenerateBitcoins;
76 extern int64 nTransactionFee;
77 extern int fLimitProcessors;
78 extern int nLimitProcessors;
79 extern int fMinimizeToTray;
80 extern int fMinimizeOnClose;
82 extern int64 nBalanceReserve;
92 void RegisterWallet(CWallet* pwalletIn);
93 void UnregisterWallet(CWallet* pwalletIn);
94 bool ProcessBlock(CNode* pfrom, CBlock* pblock);
95 bool CheckDiskSpace(uint64 nAdditionalBytes=0);
96 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
97 FILE* AppendBlockFile(unsigned int& nFileRet);
98 bool LoadBlockIndex(bool fAllowNew=true);
99 void PrintBlockTree();
100 bool ProcessMessages(CNode* pfrom);
101 bool SendMessages(CNode* pto, bool fSendTrickle);
102 void GenerateBitcoins(bool fGenerate, CWallet* pwallet);
103 CBlock* CreateNewBlock(CWallet* pwallet, bool fProofOfWorkOnly=false);
104 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce);
105 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
106 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey);
107 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
108 int64 GetProofOfStakeReward(int64 nCoinAge);
109 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime);
110 int GetNumBlocksOfPeers();
111 bool IsInitialBlockDownload();
112 std::string GetWarnings(std::string strFor);
113 bool Reorganize(CTxDB& txdb, CBlockIndex* pindexNew);
114 uint256 WantedByOrphan(const CBlock* pblockOrphan);
115 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake);
127 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
130 bool WriteSetting(const std::string& strKey, const T& value)
133 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
135 std::string strWalletFile;
136 if (!GetWalletFile(pwallet, strWalletFile))
138 fOk |= CWalletDB(strWalletFile).WriteSetting(strKey, value);
148 unsigned int nBlockPos;
156 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
159 nBlockPos = nBlockPosIn;
163 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
164 void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
165 bool IsNull() const { return (nFile == -1); }
167 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
169 return (a.nFile == b.nFile &&
170 a.nBlockPos == b.nBlockPos &&
171 a.nTxPos == b.nTxPos);
174 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
179 std::string ToString() const
182 return strprintf("null");
184 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
189 printf("%s", ToString().c_str());
202 CInPoint() { SetNull(); }
203 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
204 void SetNull() { ptx = NULL; n = -1; }
205 bool IsNull() const { return (ptx == NULL && n == -1); }
217 COutPoint() { SetNull(); }
218 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
219 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
220 void SetNull() { hash = 0; n = -1; }
221 bool IsNull() const { return (hash == 0 && n == -1); }
223 friend bool operator<(const COutPoint& a, const COutPoint& b)
225 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
228 friend bool operator==(const COutPoint& a, const COutPoint& b)
230 return (a.hash == b.hash && a.n == b.n);
233 friend bool operator!=(const COutPoint& a, const COutPoint& b)
238 std::string ToString() const
240 return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,10).c_str(), n);
245 printf("%s\n", ToString().c_str());
253 // An input of a transaction. It contains the location of the previous
254 // transaction's output that it claims and a signature that matches the
255 // output's public key.
262 unsigned int nSequence;
266 nSequence = UINT_MAX;
269 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
272 scriptSig = scriptSigIn;
273 nSequence = nSequenceIn;
276 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
278 prevout = COutPoint(hashPrevTx, nOut);
279 scriptSig = scriptSigIn;
280 nSequence = nSequenceIn;
286 READWRITE(scriptSig);
287 READWRITE(nSequence);
292 return (nSequence == UINT_MAX);
295 friend bool operator==(const CTxIn& a, const CTxIn& b)
297 return (a.prevout == b.prevout &&
298 a.scriptSig == b.scriptSig &&
299 a.nSequence == b.nSequence);
302 friend bool operator!=(const CTxIn& a, const CTxIn& b)
307 std::string ToString() const
310 str += strprintf("CTxIn(");
311 str += prevout.ToString();
312 if (prevout.IsNull())
313 str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
315 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
316 if (nSequence != UINT_MAX)
317 str += strprintf(", nSequence=%u", nSequence);
324 printf("%s\n", ToString().c_str());
332 // An output of a transaction. It contains the public key that the next input
333 // must be able to sign with to claim it.
339 CScript scriptPubKey;
346 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
349 scriptPubKey = scriptPubKeyIn;
355 READWRITE(scriptPubKey);
361 scriptPubKey.clear();
366 return (nValue == -1);
372 scriptPubKey.clear();
377 return (nValue == 0 && scriptPubKey.empty());
380 uint256 GetHash() const
382 return SerializeHash(*this);
385 friend bool operator==(const CTxOut& a, const CTxOut& b)
387 return (a.nValue == b.nValue &&
388 a.scriptPubKey == b.scriptPubKey);
391 friend bool operator!=(const CTxOut& a, const CTxOut& b)
396 std::string ToString() const
398 if (IsEmpty()) return "CTxOut(empty)";
399 if (scriptPubKey.size() < 6)
400 return "CTxOut(error)";
401 return strprintf("CTxOut(nValue=%s, scriptPubKey=%s)", FormatMoney(nValue).c_str(), scriptPubKey.ToString().substr(0,30).c_str());
406 printf("%s\n", ToString().c_str());
414 // The basic transaction that is broadcasted on the network and contained in
415 // blocks. A transaction can contain multiple inputs and outputs.
422 std::vector<CTxIn> vin;
423 std::vector<CTxOut> vout;
424 unsigned int nLockTime;
426 // Denial-of-service detection:
428 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
437 READWRITE(this->nVersion);
438 nVersion = this->nVersion;
442 READWRITE(nLockTime);
448 nTime = GetAdjustedTime();
452 nDoS = 0; // Denial-of-service prevention
457 return (vin.empty() && vout.empty());
460 uint256 GetHash() const
462 return SerializeHash(*this);
465 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
467 // Time based nLockTime implemented in 0.1.6
470 if (nBlockHeight == 0)
471 nBlockHeight = nBestHeight;
473 nBlockTime = GetAdjustedTime();
474 if ((int64)nLockTime < (nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
476 BOOST_FOREACH(const CTxIn& txin, vin)
482 bool IsNewerThan(const CTransaction& old) const
484 if (vin.size() != old.vin.size())
486 for (int i = 0; i < vin.size(); i++)
487 if (vin[i].prevout != old.vin[i].prevout)
491 unsigned int nLowest = UINT_MAX;
492 for (int i = 0; i < vin.size(); i++)
494 if (vin[i].nSequence != old.vin[i].nSequence)
496 if (vin[i].nSequence <= nLowest)
499 nLowest = vin[i].nSequence;
501 if (old.vin[i].nSequence < nLowest)
504 nLowest = old.vin[i].nSequence;
511 bool IsCoinBase() const
513 return (vin.size() == 1 && vin[0].prevout.IsNull() && vout.size() == 1);
516 bool IsCoinStake() const
518 // ppcoin: the coin stake transaction is marked with the first output empty
519 return (vin.size() > 0 && vout.size() == 2 && vout[0].IsEmpty());
522 int GetSigOpCount() const
525 BOOST_FOREACH(const CTxIn& txin, vin)
526 n += txin.scriptSig.GetSigOpCount();
527 BOOST_FOREACH(const CTxOut& txout, vout)
528 n += txout.scriptPubKey.GetSigOpCount();
532 bool IsStandard() const
534 BOOST_FOREACH(const CTxIn& txin, vin)
535 if (!txin.scriptSig.IsPushOnly())
536 return error("nonstandard txin: %s", txin.scriptSig.ToString().c_str());
537 BOOST_FOREACH(const CTxOut& txout, vout)
538 if (!::IsStandard(txout.scriptPubKey))
539 return error("nonstandard txout: %s", txout.scriptPubKey.ToString().c_str());
543 int64 GetValueOut() const
546 BOOST_FOREACH(const CTxOut& txout, vout)
548 nValueOut += txout.nValue;
549 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
550 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
555 static bool AllowFree(double dPriority)
557 // Large (in bytes) low-priority (new, small-coin) transactions
559 return dPriority > COIN * 144 / 250;
562 int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=false, bool fForRelay=false) const
564 // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
565 int64 nBaseFee = fForRelay ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
567 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);
568 unsigned int nNewBlockSize = nBlockSize + nBytes;
569 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
575 // Transactions under 10K are free
576 // (about 4500bc if made of 50bc inputs)
582 // Free transaction area
583 if (nNewBlockSize < 27000)
588 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
589 if (nMinFee < nBaseFee)
590 BOOST_FOREACH(const CTxOut& txout, vout)
591 if (txout.nValue < CENT)
594 // Raise the price as the block approaches full
595 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
597 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
599 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
602 if (!MoneyRange(nMinFee))
608 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
610 CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");
612 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
615 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
616 return error("CTransaction::ReadFromDisk() : fseek failed");
619 // Return file pointer
622 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
623 return error("CTransaction::ReadFromDisk() : second fseek failed");
624 *pfileRet = filein.release();
629 friend bool operator==(const CTransaction& a, const CTransaction& b)
631 return (a.nVersion == b.nVersion &&
632 a.nTime == b.nTime &&
635 a.nLockTime == b.nLockTime);
638 friend bool operator!=(const CTransaction& a, const CTransaction& b)
644 std::string ToString() const
647 str += IsCoinBase()? "Coinbase" : (IsCoinStake()? "Coinstake" : "CTransaction");
648 str += strprintf("(hash=%s, nTime=%d, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
649 GetHash().ToString().substr(0,10).c_str(),
655 for (int i = 0; i < vin.size(); i++)
656 str += " " + vin[i].ToString() + "\n";
657 for (int i = 0; i < vout.size(); i++)
658 str += " " + vout[i].ToString() + "\n";
664 printf("%s", ToString().c_str());
668 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
669 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
670 bool ReadFromDisk(COutPoint prevout);
671 bool DisconnectInputs(CTxDB& txdb);
672 bool ConnectInputs(CTxDB& txdb, std::map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
673 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee=0);
674 bool ClientConnectInputs();
675 bool CheckTransaction() const;
676 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
677 bool AcceptToMemoryPool(bool fCheckInputs=true, bool* pfMissingInputs=NULL);
679 bool AddToMemoryPoolUnchecked();
681 bool RemoveFromMemoryPool();
682 bool GetCoinAge(CTxDB& txdb, uint64& nCoinAge) const; // ppcoin: get transaction coin age
683 bool CheckProofOfStake(unsigned int nBits) const;
691 // A transaction with a merkle branch linking it to the block chain
693 class CMerkleTx : public CTransaction
697 std::vector<uint256> vMerkleBranch;
701 mutable char fMerkleVerified;
709 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
718 fMerkleVerified = false;
724 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
725 nVersion = this->nVersion;
726 READWRITE(hashBlock);
727 READWRITE(vMerkleBranch);
732 int SetMerkleBranch(const CBlock* pblock=NULL);
733 int GetDepthInMainChain(int& nHeightRet) const;
734 int GetDepthInMainChain() const { int nHeight; return GetDepthInMainChain(nHeight); }
735 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
736 int GetBlocksToMaturity() const;
737 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
738 bool AcceptToMemoryPool();
745 // A txdb record that contains the disk location of a transaction and the
746 // locations of transactions that spend its outputs. vSpent is really only
747 // used as a flag, but having the location is very helpful for debugging.
753 std::vector<CDiskTxPos> vSpent;
760 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
763 vSpent.resize(nOutputs);
768 if (!(nType & SER_GETHASH))
785 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
787 return (a.pos == b.pos &&
788 a.vSpent == b.vSpent);
791 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
795 int GetDepthInMainChain() const;
803 // Nodes collect new transactions into a block, hash them into a hash tree,
804 // and scan through nonce values to make the block's hash satisfy proof-of-work
805 // requirements. When they solve the proof-of-work, they broadcast the block
806 // to everyone and the block is added to the block chain. The first transaction
807 // in the block is a special one that creates a new coin owned by the creator
810 // Blocks are appended to blk0001.dat files on disk. Their location on disk
811 // is indexed by CBlockIndex objects in memory.
818 uint256 hashPrevBlock;
819 uint256 hashMerkleRoot;
825 std::vector<CTransaction> vtx;
827 // ppcoin: block signature - signed by coin base txout[0]'s owner
828 std::vector<unsigned char> vchBlockSig;
831 mutable std::vector<uint256> vMerkleTree;
833 // Denial-of-service detection:
835 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
844 READWRITE(this->nVersion);
845 nVersion = this->nVersion;
846 READWRITE(hashPrevBlock);
847 READWRITE(hashMerkleRoot);
852 // ConnectBlock depends on vtx following header to generate CDiskTxPos
853 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
856 READWRITE(vchBlockSig);
860 const_cast<CBlock*>(this)->vtx.clear();
861 const_cast<CBlock*>(this)->vchBlockSig.clear();
884 uint256 GetHash() const
886 return Hash(BEGIN(nVersion), END(nNonce));
889 int64 GetBlockTime() const
894 // ppcoin: two types of block: proof-of-work or proof-of-stake
895 bool IsProofOfStake() const
897 return (vtx.size() > 1 && vtx[1].IsCoinStake());
900 bool IsProofOfWork() const
902 return !IsProofOfStake();
905 std::pair<COutPoint, unsigned int> GetProofOfStake() const
907 return IsProofOfStake()? std::make_pair(vtx[1].vin[0].prevout, vtx[1].nTime) : std::make_pair(COutPoint(), (unsigned int)0);
910 // ppcoin: get max transaction timestamp
911 int64 GetMaxTransactionTime() const
913 int64 maxTransactionTime = 0;
914 BOOST_FOREACH(const CTransaction& tx, vtx)
915 maxTransactionTime = std::max(maxTransactionTime, (int64)tx.nTime);
916 return maxTransactionTime;
919 int GetSigOpCount() const
922 BOOST_FOREACH(const CTransaction& tx, vtx)
923 n += tx.GetSigOpCount();
928 uint256 BuildMerkleTree() const
931 BOOST_FOREACH(const CTransaction& tx, vtx)
932 vMerkleTree.push_back(tx.GetHash());
934 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
936 for (int i = 0; i < nSize; i += 2)
938 int i2 = std::min(i+1, nSize-1);
939 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
940 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
944 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
947 std::vector<uint256> GetMerkleBranch(int nIndex) const
949 if (vMerkleTree.empty())
951 std::vector<uint256> vMerkleBranch;
953 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
955 int i = std::min(nIndex^1, nSize-1);
956 vMerkleBranch.push_back(vMerkleTree[j+i]);
960 return vMerkleBranch;
963 static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
967 BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
970 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
972 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
979 bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
981 // Open history file to append
982 CAutoFile fileout = AppendBlockFile(nFileRet);
984 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
986 // Write index header
987 unsigned int nSize = fileout.GetSerializeSize(*this);
988 fileout << FLATDATA(pchMessageStart) << nSize;
991 nBlockPosRet = ftell(fileout);
992 if (nBlockPosRet == -1)
993 return error("CBlock::WriteToDisk() : ftell failed");
996 // Flush stdio buffers and commit to disk before returning
998 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
1001 _commit(_fileno(fileout));
1003 fsync(fileno(fileout));
1010 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
1014 // Open history file to read
1015 CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");
1017 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1018 if (!fReadTransactions)
1019 filein.nType |= SER_BLOCKHEADERONLY;
1025 if (fReadTransactions && IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
1026 return error("CBlock::ReadFromDisk() : errors in block header");
1035 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d, vchBlockSig=%s)\n",
1036 GetHash().ToString().substr(0,20).c_str(),
1038 hashPrevBlock.ToString().substr(0,20).c_str(),
1039 hashMerkleRoot.ToString().substr(0,10).c_str(),
1040 nTime, nBits, nNonce,
1042 HexStr(vchBlockSig.begin(), vchBlockSig.end()).c_str());
1043 for (int i = 0; i < vtx.size(); i++)
1048 printf(" vMerkleTree: ");
1049 for (int i = 0; i < vMerkleTree.size(); i++)
1050 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1055 bool SignBlock(const CKeyStore& keystore)
1057 std::vector<std::pair<opcodetype, valtype> > vSolution;
1058 const CTxOut& txout = IsProofOfStake()? vtx[1].vout[1] : vtx[0].vout[0];
1060 if (!Solver(txout.scriptPubKey, vSolution))
1062 BOOST_FOREACH(PAIRTYPE(opcodetype, valtype)& item, vSolution)
1064 if (item.first == OP_PUBKEY)
1067 const valtype& vchPubKey = item.second;
1069 if (!keystore.GetKey(Hash160(vchPubKey), key))
1071 if (key.GetPubKey() != vchPubKey)
1073 return key.Sign(GetHash(), vchBlockSig);
1079 bool CheckBlockSignature() const
1081 if (GetHash() == hashGenesisBlock)
1082 return vchBlockSig.empty();
1084 std::vector<std::pair<opcodetype, valtype> > vSolution;
1085 const CTxOut& txout = IsProofOfStake()? vtx[1].vout[1] : vtx[0].vout[0];
1087 if (!Solver(txout.scriptPubKey, vSolution))
1089 BOOST_FOREACH(PAIRTYPE(opcodetype, valtype)& item, vSolution)
1091 if (item.first == OP_PUBKEY)
1093 const valtype& vchPubKey = item.second;
1095 if (!key.SetPubKey(vchPubKey))
1097 if (vchBlockSig.empty())
1099 return key.Verify(GetHash(), vchBlockSig);
1105 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1106 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1107 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1108 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1109 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1110 bool CheckBlock() const;
1112 bool GetCoinAge(uint64& nCoinAge) const; // ppcoin: calculate total coin age spent in block
1121 // The block chain is a tree shaped structure starting with the
1122 // genesis block at the root, with each block potentially having multiple
1123 // candidates to be the next block. pprev and pnext link a path through the
1124 // main/longest chain. A blockindex may have multiple pprev pointing back
1125 // to it, but pnext will only point forward to the longest branch, or will
1126 // be null if the block is not part of the longest chain.
1131 const uint256* phashBlock;
1135 unsigned int nBlockPos;
1136 uint64 nChainTrust;// ppcoin: trust score of chain, in the unit of coin-days
1138 bool fProofOfStake; // ppcoin: is the block of proof-of-stake type
1139 COutPoint prevoutStake;
1140 unsigned int nStakeTime;
1144 uint256 hashMerkleRoot;
1147 unsigned int nNonce;
1159 fProofOfStake = true;
1160 prevoutStake.SetNull();
1170 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1176 nBlockPos = nBlockPosIn;
1179 fProofOfStake = block.IsProofOfStake();
1182 prevoutStake = block.vtx[1].vin[0].prevout;
1183 nStakeTime = block.vtx[1].nTime;
1187 prevoutStake.SetNull();
1191 nVersion = block.nVersion;
1192 hashMerkleRoot = block.hashMerkleRoot;
1193 nTime = block.nTime;
1194 nBits = block.nBits;
1195 nNonce = block.nNonce;
1198 CBlock GetBlockHeader() const
1201 block.nVersion = nVersion;
1203 block.hashPrevBlock = pprev->GetBlockHash();
1204 block.hashMerkleRoot = hashMerkleRoot;
1205 block.nTime = nTime;
1206 block.nBits = nBits;
1207 block.nNonce = nNonce;
1211 uint256 GetBlockHash() const
1216 int64 GetBlockTime() const
1218 return (int64)nTime;
1221 int64 GetBlockTrust() const
1223 return (nChainTrust - (pprev? pprev->nChainTrust : 0));
1226 bool IsInMainChain() const
1228 return (pnext || this == pindexBest);
1231 bool CheckIndex() const
1233 return IsProofOfWork() ? CheckProofOfWork(GetBlockHash(), nBits) : true;
1236 bool EraseBlockFromDisk()
1238 // Open history file
1239 CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");
1243 // Overwrite with empty null block
1251 enum { nMedianTimeSpan=11 };
1253 int64 GetMedianTimePast() const
1255 int64 pmedian[nMedianTimeSpan];
1256 int64* pbegin = &pmedian[nMedianTimeSpan];
1257 int64* pend = &pmedian[nMedianTimeSpan];
1259 const CBlockIndex* pindex = this;
1260 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1261 *(--pbegin) = pindex->GetBlockTime();
1263 std::sort(pbegin, pend);
1264 return pbegin[(pend - pbegin)/2];
1267 int64 GetMedianTime() const
1269 const CBlockIndex* pindex = this;
1270 for (int i = 0; i < nMedianTimeSpan/2; i++)
1273 return GetBlockTime();
1274 pindex = pindex->pnext;
1276 return pindex->GetMedianTimePast();
1279 bool IsProofOfWork() const
1281 return !fProofOfStake;
1284 bool IsProofOfStake() const
1286 return fProofOfStake;
1289 std::string ToString() const
1291 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)",
1292 pprev, pnext, nFile, nBlockPos, nChainTrust, nHeight,
1293 fProofOfStake, prevoutStake.ToString().c_str(), nStakeTime,
1294 hashMerkleRoot.ToString().substr(0,10).c_str(),
1295 GetBlockHash().ToString().substr(0,20).c_str());
1300 printf("%s\n", ToString().c_str());
1307 // Used to marshal pointers into hashes for db storage.
1309 class CDiskBlockIndex : public CBlockIndex
1321 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1323 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1324 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1329 if (!(nType & SER_GETHASH))
1330 READWRITE(nVersion);
1332 READWRITE(hashNext);
1334 READWRITE(nBlockPos);
1335 READWRITE(nChainTrust);
1337 READWRITE(fProofOfStake);
1340 READWRITE(prevoutStake);
1341 READWRITE(nStakeTime);
1345 const_cast<CDiskBlockIndex*>(this)->prevoutStake.SetNull();
1346 const_cast<CDiskBlockIndex*>(this)->nStakeTime = 0;
1350 READWRITE(this->nVersion);
1351 READWRITE(hashPrev);
1352 READWRITE(hashMerkleRoot);
1358 uint256 GetBlockHash() const
1361 block.nVersion = nVersion;
1362 block.hashPrevBlock = hashPrev;
1363 block.hashMerkleRoot = hashMerkleRoot;
1364 block.nTime = nTime;
1365 block.nBits = nBits;
1366 block.nNonce = nNonce;
1367 return block.GetHash();
1371 std::string ToString() const
1373 std::string str = "CDiskBlockIndex(";
1374 str += CBlockIndex::ToString();
1375 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1376 GetBlockHash().ToString().c_str(),
1377 hashPrev.ToString().substr(0,20).c_str(),
1378 hashNext.ToString().substr(0,20).c_str());
1384 printf("%s\n", ToString().c_str());
1396 // Describes a place in the block chain to another node such that if the
1397 // other node doesn't have the same branch, it can find a recent common trunk.
1398 // The further back it is, the further before the fork it may be.
1403 std::vector<uint256> vHave;
1410 explicit CBlockLocator(const CBlockIndex* pindex)
1415 explicit CBlockLocator(uint256 hashBlock)
1417 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1418 if (mi != mapBlockIndex.end())
1424 if (!(nType & SER_GETHASH))
1425 READWRITE(nVersion);
1436 return vHave.empty();
1439 void Set(const CBlockIndex* pindex)
1445 vHave.push_back(pindex->GetBlockHash());
1447 // Exponentially larger steps back
1448 for (int i = 0; pindex && i < nStep; i++)
1449 pindex = pindex->pprev;
1450 if (vHave.size() > 10)
1453 vHave.push_back(hashGenesisBlock);
1456 int GetDistanceBack()
1458 // Retrace how far back it was in the sender's branch
1461 BOOST_FOREACH(const uint256& hash, vHave)
1463 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1464 if (mi != mapBlockIndex.end())
1466 CBlockIndex* pindex = (*mi).second;
1467 if (pindex->IsInMainChain())
1477 CBlockIndex* GetBlockIndex()
1479 // Find the first block the caller has in the main chain
1480 BOOST_FOREACH(const uint256& hash, vHave)
1482 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1483 if (mi != mapBlockIndex.end())
1485 CBlockIndex* pindex = (*mi).second;
1486 if (pindex->IsInMainChain())
1490 return pindexGenesisBlock;
1493 uint256 GetBlockHash()
1495 // Find the first block the caller has in the main chain
1496 BOOST_FOREACH(const uint256& hash, vHave)
1498 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1499 if (mi != mapBlockIndex.end())
1501 CBlockIndex* pindex = (*mi).second;
1502 if (pindex->IsInMainChain())
1506 return hashGenesisBlock;
1511 CBlockIndex* pindex = GetBlockIndex();
1514 return pindex->nHeight;
1527 // Alerts are for notifying old versions if they become too obsolete and
1528 // need to upgrade. The message is displayed in the status bar.
1529 // Alert messages are broadcast as a vector of signed data. Unserializing may
1530 // not read the entire buffer if the alert is for a newer version, but older
1531 // versions can still relay the original data.
1533 class CUnsignedAlert
1537 int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
1541 std::set<int> setCancel;
1542 int nMinVer; // lowest version inclusive
1543 int nMaxVer; // highest version inclusive
1544 std::set<std::string> setSubVer; // empty matches all
1548 std::string strComment;
1549 std::string strStatusBar;
1550 std::string strReserved;
1554 READWRITE(this->nVersion);
1555 nVersion = this->nVersion;
1556 READWRITE(nRelayUntil);
1557 READWRITE(nExpiration);
1560 READWRITE(setCancel);
1563 READWRITE(setSubVer);
1564 READWRITE(nPriority);
1566 READWRITE(strComment);
1567 READWRITE(strStatusBar);
1568 READWRITE(strReserved);
1585 strStatusBar.clear();
1586 strReserved.clear();
1589 std::string ToString() const
1591 std::string strSetCancel;
1592 BOOST_FOREACH(int n, setCancel)
1593 strSetCancel += strprintf("%d ", n);
1594 std::string strSetSubVer;
1595 BOOST_FOREACH(std::string str, setSubVer)
1596 strSetSubVer += "\"" + str + "\" ";
1600 " nRelayUntil = %"PRI64d"\n"
1601 " nExpiration = %"PRI64d"\n"
1609 " strComment = \"%s\"\n"
1610 " strStatusBar = \"%s\"\n"
1617 strSetCancel.c_str(),
1620 strSetSubVer.c_str(),
1623 strStatusBar.c_str());
1628 printf("%s", ToString().c_str());
1632 class CAlert : public CUnsignedAlert
1635 std::vector<unsigned char> vchMsg;
1636 std::vector<unsigned char> vchSig;
1651 CUnsignedAlert::SetNull();
1658 return (nExpiration == 0);
1661 uint256 GetHash() const
1663 return SerializeHash(*this);
1666 bool IsInEffect() const
1668 return (GetAdjustedTime() < nExpiration);
1671 bool Cancels(const CAlert& alert) const
1674 return false; // this was a no-op before 31403
1675 return (alert.nID <= nCancel || setCancel.count(alert.nID));
1678 bool AppliesTo(int nVersion, std::string strSubVerIn) const
1680 return (IsInEffect() &&
1681 nMinVer <= nVersion && nVersion <= nMaxVer &&
1682 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1685 bool AppliesToMe() const
1687 return AppliesTo(VERSION, ::pszSubVer);
1690 bool RelayTo(CNode* pnode) const
1694 // returns true if wasn't already contained in the set
1695 if (pnode->setKnown.insert(GetHash()).second)
1697 if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
1699 GetAdjustedTime() < nRelayUntil)
1701 pnode->PushMessage("alert", *this);
1708 bool CheckSignature()
1711 if (!key.SetPubKey(ParseHex("0487ca85b6ae9d311f996c7616d20d0c88a5b4f07d25e78f419019f35cce6522acf978b2d99f0e7a58db1f120439e5c1889266927854aa57c93956c2569188a539")))
1712 return error("CAlert::CheckSignature() : SetPubKey failed");
1713 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
1714 return error("CAlert::CheckSignature() : verify signature failed");
1716 // Now unserialize the data
1717 CDataStream sMsg(vchMsg);
1718 sMsg >> *(CUnsignedAlert*)this;
1722 bool ProcessAlert();