1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Distributed under the MIT/X11 software license, see the accompanying
3 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
30 class CRequestTracker;
34 static const unsigned int MAX_BLOCK_SIZE = 1000000;
35 static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/2;
36 static const int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
37 static const int64 COIN = 100000000;
38 static const int64 CENT = 1000000;
39 static const int64 MIN_TX_FEE = 50000;
40 static const int64 MIN_RELAY_TX_FEE = 10000;
41 static const int64 MAX_MONEY = 21000000 * COIN;
42 inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
43 static const int COINBASE_MATURITY = 100;
45 static const int fHaveUPnP = true;
47 static const int fHaveUPnP = false;
55 extern CCriticalSection cs_main;
56 extern std::map<uint256, CBlockIndex*> mapBlockIndex;
57 extern uint256 hashGenesisBlock;
58 extern CBigNum bnProofOfWorkLimit;
59 extern CBlockIndex* pindexGenesisBlock;
60 extern int nBestHeight;
61 extern CBigNum bnBestChainWork;
62 extern CBigNum bnBestInvalidWork;
63 extern uint256 hashBestChain;
64 extern CBlockIndex* pindexBest;
65 extern unsigned int nTransactionsUpdated;
66 extern std::map<uint256, int> mapRequestCount;
67 extern CCriticalSection cs_mapRequestCount;
68 extern std::map<std::string, std::string> mapAddressBook;
69 extern CCriticalSection cs_mapAddressBook;
70 extern std::vector<unsigned char> vchDefaultKey;
71 extern double dHashesPerSec;
72 extern int64 nHPSTimerStart;
75 extern int fGenerateBitcoins;
76 extern int64 nTransactionFee;
77 extern CAddress addrIncoming;
78 extern int fLimitProcessors;
79 extern int nLimitProcessors;
80 extern int fMinimizeToTray;
81 extern int fMinimizeOnClose;
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 AddKey(const CKey& key);
96 std::vector<unsigned char> GenerateNewKey();
97 bool AddToWallet(const CWalletTx& wtxIn);
98 void WalletUpdateSpent(const COutPoint& prevout);
99 int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
100 void ReacceptWalletTransactions();
101 bool LoadBlockIndex(bool fAllowNew=true);
102 void PrintBlockTree();
103 bool ProcessMessages(CNode* pfrom);
104 bool ProcessMessage(CNode* pfrom, std::string strCommand, CDataStream& vRecv);
105 bool SendMessages(CNode* pto, bool fSendTrickle);
107 bool CreateTransaction(const std::vector<std::pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
108 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
109 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
110 bool BroadcastTransaction(CWalletTx& wtxNew);
111 std::string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
112 std::string SendMoneyToBitcoinAddress(std::string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
113 void GenerateBitcoins(bool fGenerate);
114 void ThreadBitcoinMiner(void* parg);
115 CBlock* CreateNewBlock(CReserveKey& reservekey);
116 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce, int64& nPrevTime);
117 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
118 bool CheckWork(CBlock* pblock, CReserveKey& reservekey);
120 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
121 int GetTotalBlocksEstimate();
122 bool IsInitialBlockDownload();
123 std::string GetWarnings(std::string strFor);
140 unsigned int nBlockPos;
148 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
151 nBlockPos = nBlockPosIn;
155 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
156 void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
157 bool IsNull() const { return (nFile == -1); }
159 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
161 return (a.nFile == b.nFile &&
162 a.nBlockPos == b.nBlockPos &&
163 a.nTxPos == b.nTxPos);
166 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
171 std::string ToString() const
174 return strprintf("null");
176 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
181 printf("%s", ToString().c_str());
194 CInPoint() { SetNull(); }
195 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
196 void SetNull() { ptx = NULL; n = -1; }
197 bool IsNull() const { return (ptx == NULL && n == -1); }
209 COutPoint() { SetNull(); }
210 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
211 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
212 void SetNull() { hash = 0; n = -1; }
213 bool IsNull() const { return (hash == 0 && n == -1); }
215 friend bool operator<(const COutPoint& a, const COutPoint& b)
217 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
220 friend bool operator==(const COutPoint& a, const COutPoint& b)
222 return (a.hash == b.hash && a.n == b.n);
225 friend bool operator!=(const COutPoint& a, const COutPoint& b)
230 std::string ToString() const
232 return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,10).c_str(), n);
237 printf("%s\n", ToString().c_str());
245 // An input of a transaction. It contains the location of the previous
246 // transaction's output that it claims and a signature that matches the
247 // output's public key.
254 unsigned int nSequence;
258 nSequence = UINT_MAX;
261 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
264 scriptSig = scriptSigIn;
265 nSequence = nSequenceIn;
268 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
270 prevout = COutPoint(hashPrevTx, nOut);
271 scriptSig = scriptSigIn;
272 nSequence = nSequenceIn;
278 READWRITE(scriptSig);
279 READWRITE(nSequence);
284 return (nSequence == UINT_MAX);
287 friend bool operator==(const CTxIn& a, const CTxIn& b)
289 return (a.prevout == b.prevout &&
290 a.scriptSig == b.scriptSig &&
291 a.nSequence == b.nSequence);
294 friend bool operator!=(const CTxIn& a, const CTxIn& b)
299 std::string ToString() const
302 str += strprintf("CTxIn(");
303 str += prevout.ToString();
304 if (prevout.IsNull())
305 str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
307 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
308 if (nSequence != UINT_MAX)
309 str += strprintf(", nSequence=%u", nSequence);
316 printf("%s\n", ToString().c_str());
320 int64 GetDebit() const;
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);
364 uint256 GetHash() const
366 return SerializeHash(*this);
371 return ::IsMine(scriptPubKey);
374 int64 GetCredit() const
376 if (!MoneyRange(nValue))
377 throw std::runtime_error("CTxOut::GetCredit() : value out of range");
378 return (IsMine() ? nValue : 0);
381 bool IsChange() const
383 // On a debit transaction, a txout that's mine but isn't in the address book is change
384 std::vector<unsigned char> vchPubKey;
385 if (ExtractPubKey(scriptPubKey, true, vchPubKey))
386 CRITICAL_BLOCK(cs_mapAddressBook)
387 if (!mapAddressBook.count(PubKeyToAddress(vchPubKey)))
392 int64 GetChange() const
394 if (!MoneyRange(nValue))
395 throw std::runtime_error("CTxOut::GetChange() : value out of range");
396 return (IsChange() ? nValue : 0);
399 friend bool operator==(const CTxOut& a, const CTxOut& b)
401 return (a.nValue == b.nValue &&
402 a.scriptPubKey == b.scriptPubKey);
405 friend bool operator!=(const CTxOut& a, const CTxOut& b)
410 std::string ToString() const
412 if (scriptPubKey.size() < 6)
413 return "CTxOut(error)";
414 return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,30).c_str());
419 printf("%s\n", ToString().c_str());
427 // The basic transaction that is broadcasted on the network and contained in
428 // blocks. A transaction can contain multiple inputs and outputs.
434 std::vector<CTxIn> vin;
435 std::vector<CTxOut> vout;
436 unsigned int nLockTime;
446 READWRITE(this->nVersion);
447 nVersion = this->nVersion;
450 READWRITE(nLockTime);
463 return (vin.empty() && vout.empty());
466 uint256 GetHash() const
468 return SerializeHash(*this);
471 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
473 // Time based nLockTime implemented in 0.1.6
476 if (nBlockHeight == 0)
477 nBlockHeight = nBestHeight;
479 nBlockTime = GetAdjustedTime();
480 if ((int64)nLockTime < (nLockTime < 500000000 ? (int64)nBlockHeight : nBlockTime))
482 BOOST_FOREACH(const CTxIn& txin, vin)
488 bool IsNewerThan(const CTransaction& old) const
490 if (vin.size() != old.vin.size())
492 for (int i = 0; i < vin.size(); i++)
493 if (vin[i].prevout != old.vin[i].prevout)
497 unsigned int nLowest = UINT_MAX;
498 for (int i = 0; i < vin.size(); i++)
500 if (vin[i].nSequence != old.vin[i].nSequence)
502 if (vin[i].nSequence <= nLowest)
505 nLowest = vin[i].nSequence;
507 if (old.vin[i].nSequence < nLowest)
510 nLowest = old.vin[i].nSequence;
517 bool IsCoinBase() const
519 return (vin.size() == 1 && vin[0].prevout.IsNull());
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());
545 BOOST_FOREACH(const CTxOut& txout, vout)
551 bool IsFromMe() const
553 return (GetDebit() > 0);
556 int64 GetDebit() const
559 BOOST_FOREACH(const CTxIn& txin, vin)
561 nDebit += txin.GetDebit();
562 if (!MoneyRange(nDebit))
563 throw std::runtime_error("CTransaction::GetDebit() : value out of range");
568 int64 GetCredit() const
571 BOOST_FOREACH(const CTxOut& txout, vout)
573 nCredit += txout.GetCredit();
574 if (!MoneyRange(nCredit))
575 throw std::runtime_error("CTransaction::GetCredit() : value out of range");
580 int64 GetChange() const
585 BOOST_FOREACH(const CTxOut& txout, vout)
587 nChange += txout.GetChange();
588 if (!MoneyRange(nChange))
589 throw std::runtime_error("CTransaction::GetChange() : value out of range");
594 int64 GetValueOut() const
597 BOOST_FOREACH(const CTxOut& txout, vout)
599 nValueOut += txout.nValue;
600 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
601 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
606 static bool AllowFree(double dPriority)
608 // Large (in bytes) low-priority (new, small-coin) transactions
610 return dPriority > COIN * 144 / 250;
613 int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=true, bool fForRelay=false) const
615 // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
616 int64 nBaseFee = fForRelay ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
618 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);
619 unsigned int nNewBlockSize = nBlockSize + nBytes;
620 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
626 // Transactions under 10K are free
627 // (about 4500bc if made of 50bc inputs)
633 // Free transaction area
634 if (nNewBlockSize < 27000)
639 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
640 if (nMinFee < nBaseFee)
641 BOOST_FOREACH(const CTxOut& txout, vout)
642 if (txout.nValue < CENT)
645 // Raise the price as the block approaches full
646 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
648 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
650 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
653 if (!MoneyRange(nMinFee))
659 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
661 CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");
663 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
666 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
667 return error("CTransaction::ReadFromDisk() : fseek failed");
670 // Return file pointer
673 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
674 return error("CTransaction::ReadFromDisk() : second fseek failed");
675 *pfileRet = filein.release();
680 friend bool operator==(const CTransaction& a, const CTransaction& b)
682 return (a.nVersion == b.nVersion &&
685 a.nLockTime == b.nLockTime);
688 friend bool operator!=(const CTransaction& a, const CTransaction& b)
694 std::string ToString() const
697 str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
698 GetHash().ToString().substr(0,10).c_str(),
703 for (int i = 0; i < vin.size(); i++)
704 str += " " + vin[i].ToString() + "\n";
705 for (int i = 0; i < vout.size(); i++)
706 str += " " + vout[i].ToString() + "\n";
712 printf("%s", ToString().c_str());
716 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
717 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
718 bool ReadFromDisk(COutPoint prevout);
719 bool DisconnectInputs(CTxDB& txdb);
720 bool ConnectInputs(CTxDB& txdb, std::map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
721 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee=0);
722 bool ClientConnectInputs();
723 bool CheckTransaction() const;
724 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
725 bool AcceptToMemoryPool(bool fCheckInputs=true, bool* pfMissingInputs=NULL)
728 return AcceptToMemoryPool(txdb, fCheckInputs, pfMissingInputs);
731 bool AddToMemoryPoolUnchecked();
733 bool RemoveFromMemoryPool();
741 // A transaction with a merkle branch linking it to the block chain
743 class CMerkleTx : public CTransaction
747 std::vector<uint256> vMerkleBranch;
751 mutable char fMerkleVerified;
759 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
768 fMerkleVerified = false;
774 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
775 nVersion = this->nVersion;
776 READWRITE(hashBlock);
777 READWRITE(vMerkleBranch);
782 int SetMerkleBranch(const CBlock* pblock=NULL);
783 int GetDepthInMainChain(int& nHeightRet) const;
784 int GetDepthInMainChain() const { int nHeight; return GetDepthInMainChain(nHeight); }
785 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
786 int GetBlocksToMaturity() const;
787 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
788 bool AcceptToMemoryPool() { CTxDB txdb("r"); return AcceptToMemoryPool(txdb); }
795 // A transaction with a bunch of additional info that only the owner cares
796 // about. It includes any unrecorded transactions needed to link it back
797 // to the block chain.
799 class CWalletTx : public CMerkleTx
802 std::vector<CMerkleTx> vtxPrev;
803 std::map<std::string, std::string> mapValue;
804 std::vector<std::pair<std::string, std::string> > vOrderForm;
805 unsigned int fTimeReceivedIsTxTime;
806 unsigned int nTimeReceived; // time received by this node
808 std::string strFromAccount;
809 std::vector<char> vfSpent;
812 mutable char fDebitCached;
813 mutable char fCreditCached;
814 mutable char fAvailableCreditCached;
815 mutable char fChangeCached;
816 mutable int64 nDebitCached;
817 mutable int64 nCreditCached;
818 mutable int64 nAvailableCreditCached;
819 mutable int64 nChangeCached;
821 // memory only UI hints
822 mutable unsigned int nTimeDisplayed;
823 mutable int nLinesDisplayed;
824 mutable char fConfirmedDisplayed;
832 CWalletTx(const CMerkleTx& txIn) : CMerkleTx(txIn)
837 CWalletTx(const CTransaction& txIn) : CMerkleTx(txIn)
847 fTimeReceivedIsTxTime = false;
850 strFromAccount.clear();
852 fDebitCached = false;
853 fCreditCached = false;
854 fAvailableCreditCached = false;
855 fChangeCached = false;
858 nAvailableCreditCached = 0;
862 fConfirmedDisplayed = false;
867 CWalletTx* pthis = const_cast<CWalletTx*>(this);
874 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
877 BOOST_FOREACH(char f, vfSpent)
879 str += (f ? '1' : '0');
883 pthis->mapValue["spent"] = str;
886 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
889 READWRITE(vOrderForm);
890 READWRITE(fTimeReceivedIsTxTime);
891 READWRITE(nTimeReceived);
897 pthis->strFromAccount = pthis->mapValue["fromaccount"];
899 if (mapValue.count("spent"))
900 BOOST_FOREACH(char c, pthis->mapValue["spent"])
901 pthis->vfSpent.push_back(c != '0');
903 pthis->vfSpent.assign(vout.size(), fSpent);
906 pthis->mapValue.erase("fromaccount");
907 pthis->mapValue.erase("version");
908 pthis->mapValue.erase("spent");
911 // marks certain txout's as spent
912 // returns true if any update took place
913 bool UpdateSpent(const std::vector<char>& vfNewSpent)
915 bool fReturn = false;
916 for (int i=0; i < vfNewSpent.size(); i++)
918 if (i == vfSpent.size())
921 if (vfNewSpent[i] && !vfSpent[i])
925 fAvailableCreditCached = false;
933 fCreditCached = false;
934 fAvailableCreditCached = false;
935 fDebitCached = false;
936 fChangeCached = false;
939 void MarkSpent(unsigned int nOut)
941 if (nOut >= vout.size())
942 throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
943 vfSpent.resize(vout.size());
946 vfSpent[nOut] = true;
947 fAvailableCreditCached = false;
951 bool IsSpent(unsigned int nOut) const
953 if (nOut >= vout.size())
954 throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
955 if (nOut >= vfSpent.size())
957 return (!!vfSpent[nOut]);
960 int64 GetDebit() const
966 nDebitCached = CTransaction::GetDebit();
971 int64 GetCredit(bool fUseCache=true) const
973 // Must wait until coinbase is safely deep enough in the chain before valuing it
974 if (IsCoinBase() && GetBlocksToMaturity() > 0)
977 // GetBalance can assume transactions in mapWallet won't change
978 if (fUseCache && fCreditCached)
979 return nCreditCached;
980 nCreditCached = CTransaction::GetCredit();
981 fCreditCached = true;
982 return nCreditCached;
985 int64 GetAvailableCredit(bool fUseCache=true) const
987 // Must wait until coinbase is safely deep enough in the chain before valuing it
988 if (IsCoinBase() && GetBlocksToMaturity() > 0)
991 if (fUseCache && fAvailableCreditCached)
992 return nAvailableCreditCached;
995 for (int i = 0; i < vout.size(); i++)
999 const CTxOut &txout = vout[i];
1000 nCredit += txout.GetCredit();
1001 if (!MoneyRange(nCredit))
1002 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
1006 nAvailableCreditCached = nCredit;
1007 fAvailableCreditCached = true;
1012 int64 GetChange() const
1015 return nChangeCached;
1016 nChangeCached = CTransaction::GetChange();
1017 fChangeCached = true;
1018 return nChangeCached;
1021 void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<std::string /* address */, int64> >& listReceived,
1022 std::list<std::pair<std::string /* address */, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
1024 void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,
1025 int64& nSent, int64& nFee) const;
1027 bool IsFromMe() const
1029 return (GetDebit() > 0);
1032 bool IsConfirmed() const
1034 // Quick answer in most cases
1037 if (GetDepthInMainChain() >= 1)
1039 if (!IsFromMe()) // using wtx's cached debit
1042 // If no confirmations but it's from us, we can still
1043 // consider it confirmed if all dependencies are confirmed
1044 std::map<uint256, const CMerkleTx*> mapPrev;
1045 std::vector<const CMerkleTx*> vWorkQueue;
1046 vWorkQueue.reserve(vtxPrev.size()+1);
1047 vWorkQueue.push_back(this);
1048 for (int i = 0; i < vWorkQueue.size(); i++)
1050 const CMerkleTx* ptx = vWorkQueue[i];
1052 if (!ptx->IsFinal())
1054 if (ptx->GetDepthInMainChain() >= 1)
1056 if (!ptx->IsFromMe())
1059 if (mapPrev.empty())
1060 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
1061 mapPrev[tx.GetHash()] = &tx;
1063 BOOST_FOREACH(const CTxIn& txin, ptx->vin)
1065 if (!mapPrev.count(txin.prevout.hash))
1067 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
1075 return CWalletDB().WriteTx(GetHash(), *this);
1079 int64 GetTxTime() const;
1080 int GetRequestCount() const;
1082 void AddSupportingTransactions(CTxDB& txdb);
1084 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
1085 bool AcceptWalletTransaction() { CTxDB txdb("r"); return AcceptWalletTransaction(txdb); }
1087 void RelayWalletTransaction(CTxDB& txdb);
1088 void RelayWalletTransaction() { CTxDB txdb("r"); RelayWalletTransaction(txdb); }
1095 // A txdb record that contains the disk location of a transaction and the
1096 // locations of transactions that spend its outputs. vSpent is really only
1097 // used as a flag, but having the location is very helpful for debugging.
1103 std::vector<CDiskTxPos> vSpent;
1110 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
1113 vSpent.resize(nOutputs);
1118 if (!(nType & SER_GETHASH))
1119 READWRITE(nVersion);
1132 return pos.IsNull();
1135 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
1137 return (a.pos == b.pos &&
1138 a.vSpent == b.vSpent);
1141 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
1145 int GetDepthInMainChain() const;
1153 // Nodes collect new transactions into a block, hash them into a hash tree,
1154 // and scan through nonce values to make the block's hash satisfy proof-of-work
1155 // requirements. When they solve the proof-of-work, they broadcast the block
1156 // to everyone and the block is added to the block chain. The first transaction
1157 // in the block is a special one that creates a new coin owned by the creator
1160 // Blocks are appended to blk0001.dat files on disk. Their location on disk
1161 // is indexed by CBlockIndex objects in memory.
1168 uint256 hashPrevBlock;
1169 uint256 hashMerkleRoot;
1172 unsigned int nNonce;
1175 std::vector<CTransaction> vtx;
1178 mutable std::vector<uint256> vMerkleTree;
1188 READWRITE(this->nVersion);
1189 nVersion = this->nVersion;
1190 READWRITE(hashPrevBlock);
1191 READWRITE(hashMerkleRoot);
1196 // ConnectBlock depends on vtx being last so it can calculate offset
1197 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
1200 const_cast<CBlock*>(this)->vtx.clear();
1212 vMerkleTree.clear();
1217 return (nBits == 0);
1220 uint256 GetHash() const
1222 return Hash(BEGIN(nVersion), END(nNonce));
1225 int64 GetBlockTime() const
1227 return (int64)nTime;
1230 int GetSigOpCount() const
1233 BOOST_FOREACH(const CTransaction& tx, vtx)
1234 n += tx.GetSigOpCount();
1239 uint256 BuildMerkleTree() const
1241 vMerkleTree.clear();
1242 BOOST_FOREACH(const CTransaction& tx, vtx)
1243 vMerkleTree.push_back(tx.GetHash());
1245 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1247 for (int i = 0; i < nSize; i += 2)
1249 int i2 = std::min(i+1, nSize-1);
1250 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
1251 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
1255 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
1258 std::vector<uint256> GetMerkleBranch(int nIndex) const
1260 if (vMerkleTree.empty())
1262 std::vector<uint256> vMerkleBranch;
1264 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1266 int i = std::min(nIndex^1, nSize-1);
1267 vMerkleBranch.push_back(vMerkleTree[j+i]);
1271 return vMerkleBranch;
1274 static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
1278 BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
1281 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
1283 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
1290 bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
1292 // Open history file to append
1293 CAutoFile fileout = AppendBlockFile(nFileRet);
1295 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
1297 // Write index header
1298 unsigned int nSize = fileout.GetSerializeSize(*this);
1299 fileout << FLATDATA(pchMessageStart) << nSize;
1302 nBlockPosRet = ftell(fileout);
1303 if (nBlockPosRet == -1)
1304 return error("CBlock::WriteToDisk() : ftell failed");
1307 // Flush stdio buffers and commit to disk before returning
1309 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
1312 _commit(_fileno(fileout));
1314 fsync(fileno(fileout));
1321 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
1325 // Open history file to read
1326 CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");
1328 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1329 if (!fReadTransactions)
1330 filein.nType |= SER_BLOCKHEADERONLY;
1336 if (!CheckProofOfWork(GetHash(), nBits))
1337 return error("CBlock::ReadFromDisk() : errors in block header");
1346 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
1347 GetHash().ToString().substr(0,20).c_str(),
1349 hashPrevBlock.ToString().substr(0,20).c_str(),
1350 hashMerkleRoot.ToString().substr(0,10).c_str(),
1351 nTime, nBits, nNonce,
1353 for (int i = 0; i < vtx.size(); i++)
1358 printf(" vMerkleTree: ");
1359 for (int i = 0; i < vMerkleTree.size(); i++)
1360 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1365 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1366 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1367 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1368 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1369 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1370 bool CheckBlock() const;
1380 // The block chain is a tree shaped structure starting with the
1381 // genesis block at the root, with each block potentially having multiple
1382 // candidates to be the next block. pprev and pnext link a path through the
1383 // main/longest chain. A blockindex may have multiple pprev pointing back
1384 // to it, but pnext will only point forward to the longest branch, or will
1385 // be null if the block is not part of the longest chain.
1390 const uint256* phashBlock;
1394 unsigned int nBlockPos;
1396 CBigNum bnChainWork;
1400 uint256 hashMerkleRoot;
1403 unsigned int nNonce;
1423 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1429 nBlockPos = nBlockPosIn;
1433 nVersion = block.nVersion;
1434 hashMerkleRoot = block.hashMerkleRoot;
1435 nTime = block.nTime;
1436 nBits = block.nBits;
1437 nNonce = block.nNonce;
1440 CBlock GetBlockHeader() const
1443 block.nVersion = nVersion;
1445 block.hashPrevBlock = pprev->GetBlockHash();
1446 block.hashMerkleRoot = hashMerkleRoot;
1447 block.nTime = nTime;
1448 block.nBits = nBits;
1449 block.nNonce = nNonce;
1453 uint256 GetBlockHash() const
1458 int64 GetBlockTime() const
1460 return (int64)nTime;
1463 CBigNum GetBlockWork() const
1466 bnTarget.SetCompact(nBits);
1469 return (CBigNum(1)<<256) / (bnTarget+1);
1472 bool IsInMainChain() const
1474 return (pnext || this == pindexBest);
1477 bool CheckIndex() const
1479 return CheckProofOfWork(GetBlockHash(), nBits);
1482 bool EraseBlockFromDisk()
1484 // Open history file
1485 CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");
1489 // Overwrite with empty null block
1497 enum { nMedianTimeSpan=11 };
1499 int64 GetMedianTimePast() const
1501 int64 pmedian[nMedianTimeSpan];
1502 int64* pbegin = &pmedian[nMedianTimeSpan];
1503 int64* pend = &pmedian[nMedianTimeSpan];
1505 const CBlockIndex* pindex = this;
1506 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1507 *(--pbegin) = pindex->GetBlockTime();
1509 std::sort(pbegin, pend);
1510 return pbegin[(pend - pbegin)/2];
1513 int64 GetMedianTime() const
1515 const CBlockIndex* pindex = this;
1516 for (int i = 0; i < nMedianTimeSpan/2; i++)
1519 return GetBlockTime();
1520 pindex = pindex->pnext;
1522 return pindex->GetMedianTimePast();
1527 std::string ToString() const
1529 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
1530 pprev, pnext, nFile, nBlockPos, nHeight,
1531 hashMerkleRoot.ToString().substr(0,10).c_str(),
1532 GetBlockHash().ToString().substr(0,20).c_str());
1537 printf("%s\n", ToString().c_str());
1544 // Used to marshal pointers into hashes for db storage.
1546 class CDiskBlockIndex : public CBlockIndex
1558 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1560 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1561 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1566 if (!(nType & SER_GETHASH))
1567 READWRITE(nVersion);
1569 READWRITE(hashNext);
1571 READWRITE(nBlockPos);
1575 READWRITE(this->nVersion);
1576 READWRITE(hashPrev);
1577 READWRITE(hashMerkleRoot);
1583 uint256 GetBlockHash() const
1586 block.nVersion = nVersion;
1587 block.hashPrevBlock = hashPrev;
1588 block.hashMerkleRoot = hashMerkleRoot;
1589 block.nTime = nTime;
1590 block.nBits = nBits;
1591 block.nNonce = nNonce;
1592 return block.GetHash();
1596 std::string ToString() const
1598 std::string str = "CDiskBlockIndex(";
1599 str += CBlockIndex::ToString();
1600 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1601 GetBlockHash().ToString().c_str(),
1602 hashPrev.ToString().substr(0,20).c_str(),
1603 hashNext.ToString().substr(0,20).c_str());
1609 printf("%s\n", ToString().c_str());
1621 // Describes a place in the block chain to another node such that if the
1622 // other node doesn't have the same branch, it can find a recent common trunk.
1623 // The further back it is, the further before the fork it may be.
1628 std::vector<uint256> vHave;
1635 explicit CBlockLocator(const CBlockIndex* pindex)
1640 explicit CBlockLocator(uint256 hashBlock)
1642 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1643 if (mi != mapBlockIndex.end())
1649 if (!(nType & SER_GETHASH))
1650 READWRITE(nVersion);
1661 return vHave.empty();
1664 void Set(const CBlockIndex* pindex)
1670 vHave.push_back(pindex->GetBlockHash());
1672 // Exponentially larger steps back
1673 for (int i = 0; pindex && i < nStep; i++)
1674 pindex = pindex->pprev;
1675 if (vHave.size() > 10)
1678 vHave.push_back(hashGenesisBlock);
1681 int GetDistanceBack()
1683 // Retrace how far back it was in the sender's branch
1686 BOOST_FOREACH(const uint256& hash, vHave)
1688 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1689 if (mi != mapBlockIndex.end())
1691 CBlockIndex* pindex = (*mi).second;
1692 if (pindex->IsInMainChain())
1702 CBlockIndex* GetBlockIndex()
1704 // Find the first block the caller has in the main chain
1705 BOOST_FOREACH(const uint256& hash, vHave)
1707 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1708 if (mi != mapBlockIndex.end())
1710 CBlockIndex* pindex = (*mi).second;
1711 if (pindex->IsInMainChain())
1715 return pindexGenesisBlock;
1718 uint256 GetBlockHash()
1720 // Find the first block the caller has in the main chain
1721 BOOST_FOREACH(const uint256& hash, vHave)
1723 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1724 if (mi != mapBlockIndex.end())
1726 CBlockIndex* pindex = (*mi).second;
1727 if (pindex->IsInMainChain())
1731 return hashGenesisBlock;
1736 CBlockIndex* pindex = GetBlockIndex();
1739 return pindex->nHeight;
1749 // Private key that includes an expiration date in case it never gets used.
1754 CPrivKey vchPrivKey;
1757 std::string strComment;
1758 //// todo: add something to note what created it (user, getnewaddress, change)
1759 //// maybe should have a map<string, string> property map
1761 CWalletKey(int64 nExpires=0)
1763 nTimeCreated = (nExpires ? GetTime() : 0);
1764 nTimeExpires = nExpires;
1769 if (!(nType & SER_GETHASH))
1770 READWRITE(nVersion);
1771 READWRITE(vchPrivKey);
1772 READWRITE(nTimeCreated);
1773 READWRITE(nTimeExpires);
1774 READWRITE(strComment);
1784 // Account information.
1785 // Stored in wallet with key "acc"+string account name
1790 std::vector<unsigned char> vchPubKey;
1804 if (!(nType & SER_GETHASH))
1805 READWRITE(nVersion);
1806 READWRITE(vchPubKey);
1813 // Internal transfers.
1814 // Database key is acentry<account><counter>
1816 class CAccountingEntry
1819 std::string strAccount;
1822 std::string strOtherAccount;
1823 std::string strComment;
1835 strOtherAccount.clear();
1841 if (!(nType & SER_GETHASH))
1842 READWRITE(nVersion);
1843 // Note: strAccount is serialized as part of the key, not here.
1844 READWRITE(nCreditDebit);
1846 READWRITE(strOtherAccount);
1847 READWRITE(strComment);
1860 // Alerts are for notifying old versions if they become too obsolete and
1861 // need to upgrade. The message is displayed in the status bar.
1862 // Alert messages are broadcast as a vector of signed data. Unserializing may
1863 // not read the entire buffer if the alert is for a newer version, but older
1864 // versions can still relay the original data.
1866 class CUnsignedAlert
1870 int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
1874 std::set<int> setCancel;
1875 int nMinVer; // lowest version inclusive
1876 int nMaxVer; // highest version inclusive
1877 std::set<std::string> setSubVer; // empty matches all
1881 std::string strComment;
1882 std::string strStatusBar;
1883 std::string strReserved;
1887 READWRITE(this->nVersion);
1888 nVersion = this->nVersion;
1889 READWRITE(nRelayUntil);
1890 READWRITE(nExpiration);
1893 READWRITE(setCancel);
1896 READWRITE(setSubVer);
1897 READWRITE(nPriority);
1899 READWRITE(strComment);
1900 READWRITE(strStatusBar);
1901 READWRITE(strReserved);
1918 strStatusBar.clear();
1919 strReserved.clear();
1922 std::string ToString() const
1924 std::string strSetCancel;
1925 BOOST_FOREACH(int n, setCancel)
1926 strSetCancel += strprintf("%d ", n);
1927 std::string strSetSubVer;
1928 BOOST_FOREACH(std::string str, setSubVer)
1929 strSetSubVer += "\"" + str + "\" ";
1933 " nRelayUntil = %"PRI64d"\n"
1934 " nExpiration = %"PRI64d"\n"
1942 " strComment = \"%s\"\n"
1943 " strStatusBar = \"%s\"\n"
1950 strSetCancel.c_str(),
1953 strSetSubVer.c_str(),
1956 strStatusBar.c_str());
1961 printf("%s", ToString().c_str());
1965 class CAlert : public CUnsignedAlert
1968 std::vector<unsigned char> vchMsg;
1969 std::vector<unsigned char> vchSig;
1984 CUnsignedAlert::SetNull();
1991 return (nExpiration == 0);
1994 uint256 GetHash() const
1996 return SerializeHash(*this);
1999 bool IsInEffect() const
2001 return (GetAdjustedTime() < nExpiration);
2004 bool Cancels(const CAlert& alert) const
2007 return false; // this was a no-op before 31403
2008 return (alert.nID <= nCancel || setCancel.count(alert.nID));
2011 bool AppliesTo(int nVersion, std::string strSubVerIn) const
2013 return (IsInEffect() &&
2014 nMinVer <= nVersion && nVersion <= nMaxVer &&
2015 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
2018 bool AppliesToMe() const
2020 return AppliesTo(VERSION, ::pszSubVer);
2023 bool RelayTo(CNode* pnode) const
2027 // returns true if wasn't already contained in the set
2028 if (pnode->setKnown.insert(GetHash()).second)
2030 if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
2032 GetAdjustedTime() < nRelayUntil)
2034 pnode->PushMessage("alert", *this);
2041 bool CheckSignature()
2044 if (!key.SetPubKey(ParseHex("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284")))
2045 return error("CAlert::CheckSignature() : SetPubKey failed");
2046 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
2047 return error("CAlert::CheckSignature() : verify signature failed");
2049 // Now unserialize the data
2050 CDataStream sMsg(vchMsg);
2051 sMsg >> *(CUnsignedAlert*)this;
2055 bool ProcessAlert();
2067 extern std::map<uint256, CTransaction> mapTransactions;
2068 extern std::map<uint256, CWalletTx> mapWallet;
2069 extern std::vector<uint256> vWalletUpdated;
2070 extern CCriticalSection cs_mapWallet;
2071 extern std::map<std::vector<unsigned char>, CPrivKey> mapKeys;
2072 extern std::map<uint160, std::vector<unsigned char> > mapPubKeys;
2073 extern CCriticalSection cs_mapKeys;
2074 extern CKey keyUser;