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 MAX_MONEY = 21000000 * COIN;
41 inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
42 static const int COINBASE_MATURITY = 100;
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 uint256 hashGenesisBlock;
57 extern CBigNum bnProofOfWorkLimit;
58 extern CBlockIndex* pindexGenesisBlock;
59 extern int nBestHeight;
60 extern CBigNum bnBestChainWork;
61 extern CBigNum bnBestInvalidWork;
62 extern uint256 hashBestChain;
63 extern CBlockIndex* pindexBest;
64 extern unsigned int nTransactionsUpdated;
65 extern std::map<uint256, int> mapRequestCount;
66 extern CCriticalSection cs_mapRequestCount;
67 extern std::map<std::string, std::string> mapAddressBook;
68 extern CCriticalSection cs_mapAddressBook;
69 extern std::vector<unsigned char> vchDefaultKey;
70 extern double dHashesPerSec;
71 extern int64 nHPSTimerStart;
74 extern int fGenerateBitcoins;
75 extern int64 nTransactionFee;
76 extern CAddress addrIncoming;
77 extern int fLimitProcessors;
78 extern int nLimitProcessors;
79 extern int fMinimizeToTray;
80 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);
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 bool IsInitialBlockDownload();
122 std::string GetWarnings(std::string strFor);
139 unsigned int nBlockPos;
147 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
150 nBlockPos = nBlockPosIn;
154 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
155 void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
156 bool IsNull() const { return (nFile == -1); }
158 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
160 return (a.nFile == b.nFile &&
161 a.nBlockPos == b.nBlockPos &&
162 a.nTxPos == b.nTxPos);
165 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
170 std::string ToString() const
173 return strprintf("null");
175 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
180 printf("%s", ToString().c_str());
193 CInPoint() { SetNull(); }
194 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
195 void SetNull() { ptx = NULL; n = -1; }
196 bool IsNull() const { return (ptx == NULL && n == -1); }
208 COutPoint() { SetNull(); }
209 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
210 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
211 void SetNull() { hash = 0; n = -1; }
212 bool IsNull() const { return (hash == 0 && n == -1); }
214 friend bool operator<(const COutPoint& a, const COutPoint& b)
216 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
219 friend bool operator==(const COutPoint& a, const COutPoint& b)
221 return (a.hash == b.hash && a.n == b.n);
224 friend bool operator!=(const COutPoint& a, const COutPoint& b)
229 std::string ToString() const
231 return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,10).c_str(), n);
236 printf("%s\n", ToString().c_str());
244 // An input of a transaction. It contains the location of the previous
245 // transaction's output that it claims and a signature that matches the
246 // output's public key.
253 unsigned int nSequence;
257 nSequence = UINT_MAX;
260 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
263 scriptSig = scriptSigIn;
264 nSequence = nSequenceIn;
267 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
269 prevout = COutPoint(hashPrevTx, nOut);
270 scriptSig = scriptSigIn;
271 nSequence = nSequenceIn;
277 READWRITE(scriptSig);
278 READWRITE(nSequence);
283 return (nSequence == UINT_MAX);
286 friend bool operator==(const CTxIn& a, const CTxIn& b)
288 return (a.prevout == b.prevout &&
289 a.scriptSig == b.scriptSig &&
290 a.nSequence == b.nSequence);
293 friend bool operator!=(const CTxIn& a, const CTxIn& b)
298 std::string ToString() const
301 str += strprintf("CTxIn(");
302 str += prevout.ToString();
303 if (prevout.IsNull())
304 str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
306 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
307 if (nSequence != UINT_MAX)
308 str += strprintf(", nSequence=%u", nSequence);
315 printf("%s\n", ToString().c_str());
319 int64 GetDebit() const;
326 // An output of a transaction. It contains the public key that the next input
327 // must be able to sign with to claim it.
333 CScript scriptPubKey;
340 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
343 scriptPubKey = scriptPubKeyIn;
349 READWRITE(scriptPubKey);
355 scriptPubKey.clear();
360 return (nValue == -1);
363 uint256 GetHash() const
365 return SerializeHash(*this);
370 return ::IsMine(scriptPubKey);
373 int64 GetCredit() const
375 if (!MoneyRange(nValue))
376 throw std::runtime_error("CTxOut::GetCredit() : value out of range");
377 return (IsMine() ? nValue : 0);
380 bool IsChange() const
382 // On a debit transaction, a txout that's mine but isn't in the address book is change
383 std::vector<unsigned char> vchPubKey;
384 if (ExtractPubKey(scriptPubKey, true, vchPubKey))
385 CRITICAL_BLOCK(cs_mapAddressBook)
386 if (!mapAddressBook.count(PubKeyToAddress(vchPubKey)))
391 int64 GetChange() const
393 if (!MoneyRange(nValue))
394 throw std::runtime_error("CTxOut::GetChange() : value out of range");
395 return (IsChange() ? nValue : 0);
398 friend bool operator==(const CTxOut& a, const CTxOut& b)
400 return (a.nValue == b.nValue &&
401 a.scriptPubKey == b.scriptPubKey);
404 friend bool operator!=(const CTxOut& a, const CTxOut& b)
409 std::string ToString() const
411 if (scriptPubKey.size() < 6)
412 return "CTxOut(error)";
413 return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,30).c_str());
418 printf("%s\n", ToString().c_str());
426 // The basic transaction that is broadcasted on the network and contained in
427 // blocks. A transaction can contain multiple inputs and outputs.
433 std::vector<CTxIn> vin;
434 std::vector<CTxOut> vout;
435 unsigned int nLockTime;
445 READWRITE(this->nVersion);
446 nVersion = this->nVersion;
449 READWRITE(nLockTime);
462 return (vin.empty() && vout.empty());
465 uint256 GetHash() const
467 return SerializeHash(*this);
470 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
472 // Time based nLockTime implemented in 0.1.6
475 if (nBlockHeight == 0)
476 nBlockHeight = nBestHeight;
478 nBlockTime = GetAdjustedTime();
479 if ((int64)nLockTime < (nLockTime < 500000000 ? (int64)nBlockHeight : nBlockTime))
481 BOOST_FOREACH(const CTxIn& txin, vin)
487 bool IsNewerThan(const CTransaction& old) const
489 if (vin.size() != old.vin.size())
491 for (int i = 0; i < vin.size(); i++)
492 if (vin[i].prevout != old.vin[i].prevout)
496 unsigned int nLowest = UINT_MAX;
497 for (int i = 0; i < vin.size(); i++)
499 if (vin[i].nSequence != old.vin[i].nSequence)
501 if (vin[i].nSequence <= nLowest)
504 nLowest = vin[i].nSequence;
506 if (old.vin[i].nSequence < nLowest)
509 nLowest = old.vin[i].nSequence;
516 bool IsCoinBase() const
518 return (vin.size() == 1 && vin[0].prevout.IsNull());
521 int GetSigOpCount() const
524 BOOST_FOREACH(const CTxIn& txin, vin)
525 n += txin.scriptSig.GetSigOpCount();
526 BOOST_FOREACH(const CTxOut& txout, vout)
527 n += txout.scriptPubKey.GetSigOpCount();
531 bool IsStandard() const
533 BOOST_FOREACH(const CTxIn& txin, vin)
534 if (!txin.scriptSig.IsPushOnly())
535 return error("nonstandard txin: %s", txin.scriptSig.ToString().c_str());
536 BOOST_FOREACH(const CTxOut& txout, vout)
537 if (!::IsStandard(txout.scriptPubKey))
538 return error("nonstandard txout: %s", txout.scriptPubKey.ToString().c_str());
544 BOOST_FOREACH(const CTxOut& txout, vout)
550 bool IsFromMe() const
552 return (GetDebit() > 0);
555 int64 GetDebit() const
558 BOOST_FOREACH(const CTxIn& txin, vin)
560 nDebit += txin.GetDebit();
561 if (!MoneyRange(nDebit))
562 throw std::runtime_error("CTransaction::GetDebit() : value out of range");
567 int64 GetCredit() const
570 BOOST_FOREACH(const CTxOut& txout, vout)
572 nCredit += txout.GetCredit();
573 if (!MoneyRange(nCredit))
574 throw std::runtime_error("CTransaction::GetCredit() : value out of range");
579 int64 GetChange() const
584 BOOST_FOREACH(const CTxOut& txout, vout)
586 nChange += txout.GetChange();
587 if (!MoneyRange(nChange))
588 throw std::runtime_error("CTransaction::GetChange() : value out of range");
593 int64 GetValueOut() const
596 BOOST_FOREACH(const CTxOut& txout, vout)
598 nValueOut += txout.nValue;
599 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
600 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
605 static bool AllowFree(double dPriority)
607 // Large (in bytes) low-priority (new, small-coin) transactions
609 return dPriority > COIN * 144 / 250;
612 int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=true) const
614 // Base fee is 1 cent per kilobyte
615 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);
616 unsigned int nNewBlockSize = nBlockSize + nBytes;
617 int64 nMinFee = (1 + (int64)nBytes / 1000) * MIN_TX_FEE;
623 // Transactions under 10K are free
624 // (about 4500bc if made of 50bc inputs)
630 // Free transaction area
631 if (nNewBlockSize < 27000)
636 // To limit dust spam, require MIN_TX_FEE if any output is less than 0.01
637 if (nMinFee < MIN_TX_FEE)
638 BOOST_FOREACH(const CTxOut& txout, vout)
639 if (txout.nValue < CENT)
640 nMinFee = MIN_TX_FEE;
642 // Raise the price as the block approaches full
643 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
645 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
647 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
650 if (!MoneyRange(nMinFee))
656 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
658 CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");
660 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
663 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
664 return error("CTransaction::ReadFromDisk() : fseek failed");
667 // Return file pointer
670 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
671 return error("CTransaction::ReadFromDisk() : second fseek failed");
672 *pfileRet = filein.release();
677 friend bool operator==(const CTransaction& a, const CTransaction& b)
679 return (a.nVersion == b.nVersion &&
682 a.nLockTime == b.nLockTime);
685 friend bool operator!=(const CTransaction& a, const CTransaction& b)
691 std::string ToString() const
694 str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
695 GetHash().ToString().substr(0,10).c_str(),
700 for (int i = 0; i < vin.size(); i++)
701 str += " " + vin[i].ToString() + "\n";
702 for (int i = 0; i < vout.size(); i++)
703 str += " " + vout[i].ToString() + "\n";
709 printf("%s", ToString().c_str());
713 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
714 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
715 bool ReadFromDisk(COutPoint prevout);
716 bool DisconnectInputs(CTxDB& txdb);
717 bool ConnectInputs(CTxDB& txdb, std::map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
718 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee=0);
719 bool ClientConnectInputs();
720 bool CheckTransaction() const;
721 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
722 bool AcceptToMemoryPool(bool fCheckInputs=true, bool* pfMissingInputs=NULL)
725 return AcceptToMemoryPool(txdb, fCheckInputs, pfMissingInputs);
728 bool AddToMemoryPoolUnchecked();
730 bool RemoveFromMemoryPool();
738 // A transaction with a merkle branch linking it to the block chain
740 class CMerkleTx : public CTransaction
744 std::vector<uint256> vMerkleBranch;
748 mutable char fMerkleVerified;
756 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
765 fMerkleVerified = false;
771 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
772 nVersion = this->nVersion;
773 READWRITE(hashBlock);
774 READWRITE(vMerkleBranch);
779 int SetMerkleBranch(const CBlock* pblock=NULL);
780 int GetDepthInMainChain(int& nHeightRet) const;
781 int GetDepthInMainChain() const { int nHeight; return GetDepthInMainChain(nHeight); }
782 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
783 int GetBlocksToMaturity() const;
784 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
785 bool AcceptToMemoryPool() { CTxDB txdb("r"); return AcceptToMemoryPool(txdb); }
792 // A transaction with a bunch of additional info that only the owner cares
793 // about. It includes any unrecorded transactions needed to link it back
794 // to the block chain.
796 class CWalletTx : public CMerkleTx
799 std::vector<CMerkleTx> vtxPrev;
800 std::map<std::string, std::string> mapValue;
801 std::vector<std::pair<std::string, std::string> > vOrderForm;
802 unsigned int fTimeReceivedIsTxTime;
803 unsigned int nTimeReceived; // time received by this node
805 std::string strFromAccount;
806 std::vector<char> vfSpent;
809 mutable char fDebitCached;
810 mutable char fCreditCached;
811 mutable char fAvailableCreditCached;
812 mutable char fChangeCached;
813 mutable int64 nDebitCached;
814 mutable int64 nCreditCached;
815 mutable int64 nAvailableCreditCached;
816 mutable int64 nChangeCached;
818 // memory only UI hints
819 mutable unsigned int nTimeDisplayed;
820 mutable int nLinesDisplayed;
821 mutable char fConfirmedDisplayed;
829 CWalletTx(const CMerkleTx& txIn) : CMerkleTx(txIn)
834 CWalletTx(const CTransaction& txIn) : CMerkleTx(txIn)
844 fTimeReceivedIsTxTime = false;
847 strFromAccount.clear();
849 fDebitCached = false;
850 fCreditCached = false;
851 fAvailableCreditCached = false;
852 fChangeCached = false;
855 nAvailableCreditCached = 0;
859 fConfirmedDisplayed = false;
864 CWalletTx* pthis = const_cast<CWalletTx*>(this);
871 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
874 BOOST_FOREACH(char f, vfSpent)
876 str += (f ? '1' : '0');
880 pthis->mapValue["spent"] = str;
883 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
886 READWRITE(vOrderForm);
887 READWRITE(fTimeReceivedIsTxTime);
888 READWRITE(nTimeReceived);
894 pthis->strFromAccount = pthis->mapValue["fromaccount"];
896 if (mapValue.count("spent"))
897 BOOST_FOREACH(char c, pthis->mapValue["spent"])
898 pthis->vfSpent.push_back(c != '0');
900 pthis->vfSpent.assign(vout.size(), fSpent);
903 pthis->mapValue.erase("fromaccount");
904 pthis->mapValue.erase("version");
905 pthis->mapValue.erase("spent");
908 // marks certain txout's as spent
909 // returns true if any update took place
910 bool UpdateSpent(const std::vector<char>& vfNewSpent)
912 bool fReturn = false;
913 for (int i=0; i < vfNewSpent.size(); i++)
915 if (i == vfSpent.size())
918 if (vfNewSpent[i] && !vfSpent[i])
922 fAvailableCreditCached = false;
930 fCreditCached = false;
931 fAvailableCreditCached = false;
932 fDebitCached = false;
933 fChangeCached = false;
936 void MarkSpent(unsigned int nOut)
938 if (nOut >= vout.size())
939 throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
940 vfSpent.resize(vout.size());
943 vfSpent[nOut] = true;
944 fAvailableCreditCached = false;
948 bool IsSpent(unsigned int nOut) const
950 if (nOut >= vout.size())
951 throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
952 if (nOut >= vfSpent.size())
954 return (!!vfSpent[nOut]);
957 int64 GetDebit() const
963 nDebitCached = CTransaction::GetDebit();
968 int64 GetCredit(bool fUseCache=true) const
970 // Must wait until coinbase is safely deep enough in the chain before valuing it
971 if (IsCoinBase() && GetBlocksToMaturity() > 0)
974 // GetBalance can assume transactions in mapWallet won't change
975 if (fUseCache && fCreditCached)
976 return nCreditCached;
977 nCreditCached = CTransaction::GetCredit();
978 fCreditCached = true;
979 return nCreditCached;
982 int64 GetAvailableCredit(bool fUseCache=true) const
984 // Must wait until coinbase is safely deep enough in the chain before valuing it
985 if (IsCoinBase() && GetBlocksToMaturity() > 0)
988 if (fUseCache && fAvailableCreditCached)
989 return nAvailableCreditCached;
992 for (int i = 0; i < vout.size(); i++)
996 const CTxOut &txout = vout[i];
997 nCredit += txout.GetCredit();
998 if (!MoneyRange(nCredit))
999 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
1003 nAvailableCreditCached = nCredit;
1004 fAvailableCreditCached = true;
1009 int64 GetChange() const
1012 return nChangeCached;
1013 nChangeCached = CTransaction::GetChange();
1014 fChangeCached = true;
1015 return nChangeCached;
1018 void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<std::string /* address */, int64> >& listReceived,
1019 std::list<std::pair<std::string /* address */, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
1021 void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,
1022 int64& nSent, int64& nFee) const;
1024 bool IsFromMe() const
1026 return (GetDebit() > 0);
1029 bool IsConfirmed() const
1031 // Quick answer in most cases
1034 if (GetDepthInMainChain() >= 1)
1036 if (!IsFromMe()) // using wtx's cached debit
1039 // If no confirmations but it's from us, we can still
1040 // consider it confirmed if all dependencies are confirmed
1041 std::map<uint256, const CMerkleTx*> mapPrev;
1042 std::vector<const CMerkleTx*> vWorkQueue;
1043 vWorkQueue.reserve(vtxPrev.size()+1);
1044 vWorkQueue.push_back(this);
1045 for (int i = 0; i < vWorkQueue.size(); i++)
1047 const CMerkleTx* ptx = vWorkQueue[i];
1049 if (!ptx->IsFinal())
1051 if (ptx->GetDepthInMainChain() >= 1)
1053 if (!ptx->IsFromMe())
1056 if (mapPrev.empty())
1057 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
1058 mapPrev[tx.GetHash()] = &tx;
1060 BOOST_FOREACH(const CTxIn& txin, ptx->vin)
1062 if (!mapPrev.count(txin.prevout.hash))
1064 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
1072 return CWalletDB().WriteTx(GetHash(), *this);
1076 int64 GetTxTime() const;
1077 int GetRequestCount() const;
1079 void AddSupportingTransactions(CTxDB& txdb);
1081 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
1082 bool AcceptWalletTransaction() { CTxDB txdb("r"); return AcceptWalletTransaction(txdb); }
1084 void RelayWalletTransaction(CTxDB& txdb);
1085 void RelayWalletTransaction() { CTxDB txdb("r"); RelayWalletTransaction(txdb); }
1092 // A txdb record that contains the disk location of a transaction and the
1093 // locations of transactions that spend its outputs. vSpent is really only
1094 // used as a flag, but having the location is very helpful for debugging.
1100 std::vector<CDiskTxPos> vSpent;
1107 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
1110 vSpent.resize(nOutputs);
1115 if (!(nType & SER_GETHASH))
1116 READWRITE(nVersion);
1129 return pos.IsNull();
1132 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
1134 return (a.pos == b.pos &&
1135 a.vSpent == b.vSpent);
1138 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
1142 int GetDepthInMainChain() const;
1150 // Nodes collect new transactions into a block, hash them into a hash tree,
1151 // and scan through nonce values to make the block's hash satisfy proof-of-work
1152 // requirements. When they solve the proof-of-work, they broadcast the block
1153 // to everyone and the block is added to the block chain. The first transaction
1154 // in the block is a special one that creates a new coin owned by the creator
1157 // Blocks are appended to blk0001.dat files on disk. Their location on disk
1158 // is indexed by CBlockIndex objects in memory.
1165 uint256 hashPrevBlock;
1166 uint256 hashMerkleRoot;
1169 unsigned int nNonce;
1172 std::vector<CTransaction> vtx;
1175 mutable std::vector<uint256> vMerkleTree;
1185 READWRITE(this->nVersion);
1186 nVersion = this->nVersion;
1187 READWRITE(hashPrevBlock);
1188 READWRITE(hashMerkleRoot);
1193 // ConnectBlock depends on vtx being last so it can calculate offset
1194 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
1197 const_cast<CBlock*>(this)->vtx.clear();
1209 vMerkleTree.clear();
1214 return (nBits == 0);
1217 uint256 GetHash() const
1219 return Hash(BEGIN(nVersion), END(nNonce));
1222 int64 GetBlockTime() const
1224 return (int64)nTime;
1227 int GetSigOpCount() const
1230 BOOST_FOREACH(const CTransaction& tx, vtx)
1231 n += tx.GetSigOpCount();
1236 uint256 BuildMerkleTree() const
1238 vMerkleTree.clear();
1239 BOOST_FOREACH(const CTransaction& tx, vtx)
1240 vMerkleTree.push_back(tx.GetHash());
1242 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1244 for (int i = 0; i < nSize; i += 2)
1246 int i2 = std::min(i+1, nSize-1);
1247 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
1248 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
1252 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
1255 std::vector<uint256> GetMerkleBranch(int nIndex) const
1257 if (vMerkleTree.empty())
1259 std::vector<uint256> vMerkleBranch;
1261 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1263 int i = std::min(nIndex^1, nSize-1);
1264 vMerkleBranch.push_back(vMerkleTree[j+i]);
1268 return vMerkleBranch;
1271 static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
1275 BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
1278 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
1280 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
1287 bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
1289 // Open history file to append
1290 CAutoFile fileout = AppendBlockFile(nFileRet);
1292 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
1294 // Write index header
1295 unsigned int nSize = fileout.GetSerializeSize(*this);
1296 fileout << FLATDATA(pchMessageStart) << nSize;
1299 nBlockPosRet = ftell(fileout);
1300 if (nBlockPosRet == -1)
1301 return error("CBlock::WriteToDisk() : ftell failed");
1304 // Flush stdio buffers and commit to disk before returning
1306 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
1309 _commit(_fileno(fileout));
1311 fsync(fileno(fileout));
1318 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
1322 // Open history file to read
1323 CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");
1325 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1326 if (!fReadTransactions)
1327 filein.nType |= SER_BLOCKHEADERONLY;
1333 if (!CheckProofOfWork(GetHash(), nBits))
1334 return error("CBlock::ReadFromDisk() : errors in block header");
1343 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
1344 GetHash().ToString().substr(0,20).c_str(),
1346 hashPrevBlock.ToString().substr(0,20).c_str(),
1347 hashMerkleRoot.ToString().substr(0,10).c_str(),
1348 nTime, nBits, nNonce,
1350 for (int i = 0; i < vtx.size(); i++)
1355 printf(" vMerkleTree: ");
1356 for (int i = 0; i < vMerkleTree.size(); i++)
1357 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1362 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1363 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1364 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1365 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1366 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1367 bool CheckBlock() const;
1377 // The block chain is a tree shaped structure starting with the
1378 // genesis block at the root, with each block potentially having multiple
1379 // candidates to be the next block. pprev and pnext link a path through the
1380 // main/longest chain. A blockindex may have multiple pprev pointing back
1381 // to it, but pnext will only point forward to the longest branch, or will
1382 // be null if the block is not part of the longest chain.
1387 const uint256* phashBlock;
1391 unsigned int nBlockPos;
1393 CBigNum bnChainWork;
1397 uint256 hashMerkleRoot;
1400 unsigned int nNonce;
1420 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1426 nBlockPos = nBlockPosIn;
1430 nVersion = block.nVersion;
1431 hashMerkleRoot = block.hashMerkleRoot;
1432 nTime = block.nTime;
1433 nBits = block.nBits;
1434 nNonce = block.nNonce;
1437 CBlock GetBlockHeader() const
1440 block.nVersion = nVersion;
1442 block.hashPrevBlock = pprev->GetBlockHash();
1443 block.hashMerkleRoot = hashMerkleRoot;
1444 block.nTime = nTime;
1445 block.nBits = nBits;
1446 block.nNonce = nNonce;
1450 uint256 GetBlockHash() const
1455 int64 GetBlockTime() const
1457 return (int64)nTime;
1460 CBigNum GetBlockWork() const
1463 bnTarget.SetCompact(nBits);
1466 return (CBigNum(1)<<256) / (bnTarget+1);
1469 bool IsInMainChain() const
1471 return (pnext || this == pindexBest);
1474 bool CheckIndex() const
1476 return CheckProofOfWork(GetBlockHash(), nBits);
1479 bool EraseBlockFromDisk()
1481 // Open history file
1482 CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");
1486 // Overwrite with empty null block
1494 enum { nMedianTimeSpan=11 };
1496 int64 GetMedianTimePast() const
1498 int64 pmedian[nMedianTimeSpan];
1499 int64* pbegin = &pmedian[nMedianTimeSpan];
1500 int64* pend = &pmedian[nMedianTimeSpan];
1502 const CBlockIndex* pindex = this;
1503 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1504 *(--pbegin) = pindex->GetBlockTime();
1506 std::sort(pbegin, pend);
1507 return pbegin[(pend - pbegin)/2];
1510 int64 GetMedianTime() const
1512 const CBlockIndex* pindex = this;
1513 for (int i = 0; i < nMedianTimeSpan/2; i++)
1516 return GetBlockTime();
1517 pindex = pindex->pnext;
1519 return pindex->GetMedianTimePast();
1524 std::string ToString() const
1526 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
1527 pprev, pnext, nFile, nBlockPos, nHeight,
1528 hashMerkleRoot.ToString().substr(0,10).c_str(),
1529 GetBlockHash().ToString().substr(0,20).c_str());
1534 printf("%s\n", ToString().c_str());
1541 // Used to marshal pointers into hashes for db storage.
1543 class CDiskBlockIndex : public CBlockIndex
1555 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1557 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1558 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1563 if (!(nType & SER_GETHASH))
1564 READWRITE(nVersion);
1566 READWRITE(hashNext);
1568 READWRITE(nBlockPos);
1572 READWRITE(this->nVersion);
1573 READWRITE(hashPrev);
1574 READWRITE(hashMerkleRoot);
1580 uint256 GetBlockHash() const
1583 block.nVersion = nVersion;
1584 block.hashPrevBlock = hashPrev;
1585 block.hashMerkleRoot = hashMerkleRoot;
1586 block.nTime = nTime;
1587 block.nBits = nBits;
1588 block.nNonce = nNonce;
1589 return block.GetHash();
1593 std::string ToString() const
1595 std::string str = "CDiskBlockIndex(";
1596 str += CBlockIndex::ToString();
1597 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1598 GetBlockHash().ToString().c_str(),
1599 hashPrev.ToString().substr(0,20).c_str(),
1600 hashNext.ToString().substr(0,20).c_str());
1606 printf("%s\n", ToString().c_str());
1618 // Describes a place in the block chain to another node such that if the
1619 // other node doesn't have the same branch, it can find a recent common trunk.
1620 // The further back it is, the further before the fork it may be.
1625 std::vector<uint256> vHave;
1632 explicit CBlockLocator(const CBlockIndex* pindex)
1637 explicit CBlockLocator(uint256 hashBlock)
1639 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1640 if (mi != mapBlockIndex.end())
1646 if (!(nType & SER_GETHASH))
1647 READWRITE(nVersion);
1658 return vHave.empty();
1661 void Set(const CBlockIndex* pindex)
1667 vHave.push_back(pindex->GetBlockHash());
1669 // Exponentially larger steps back
1670 for (int i = 0; pindex && i < nStep; i++)
1671 pindex = pindex->pprev;
1672 if (vHave.size() > 10)
1675 vHave.push_back(hashGenesisBlock);
1678 int GetDistanceBack()
1680 // Retrace how far back it was in the sender's branch
1683 BOOST_FOREACH(const uint256& hash, vHave)
1685 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1686 if (mi != mapBlockIndex.end())
1688 CBlockIndex* pindex = (*mi).second;
1689 if (pindex->IsInMainChain())
1699 CBlockIndex* GetBlockIndex()
1701 // Find the first block the caller has in the main chain
1702 BOOST_FOREACH(const uint256& hash, vHave)
1704 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1705 if (mi != mapBlockIndex.end())
1707 CBlockIndex* pindex = (*mi).second;
1708 if (pindex->IsInMainChain())
1712 return pindexGenesisBlock;
1715 uint256 GetBlockHash()
1717 // Find the first block the caller has in the main chain
1718 BOOST_FOREACH(const uint256& hash, vHave)
1720 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1721 if (mi != mapBlockIndex.end())
1723 CBlockIndex* pindex = (*mi).second;
1724 if (pindex->IsInMainChain())
1728 return hashGenesisBlock;
1733 CBlockIndex* pindex = GetBlockIndex();
1736 return pindex->nHeight;
1746 // Private key that includes an expiration date in case it never gets used.
1751 CPrivKey vchPrivKey;
1754 std::string strComment;
1755 //// todo: add something to note what created it (user, getnewaddress, change)
1756 //// maybe should have a map<string, string> property map
1758 CWalletKey(int64 nExpires=0)
1760 nTimeCreated = (nExpires ? GetTime() : 0);
1761 nTimeExpires = nExpires;
1766 if (!(nType & SER_GETHASH))
1767 READWRITE(nVersion);
1768 READWRITE(vchPrivKey);
1769 READWRITE(nTimeCreated);
1770 READWRITE(nTimeExpires);
1771 READWRITE(strComment);
1781 // Account information.
1782 // Stored in wallet with key "acc"+string account name
1787 std::vector<unsigned char> vchPubKey;
1801 if (!(nType & SER_GETHASH))
1802 READWRITE(nVersion);
1803 READWRITE(vchPubKey);
1810 // Internal transfers.
1811 // Database key is acentry<account><counter>
1813 class CAccountingEntry
1816 std::string strAccount;
1819 std::string strOtherAccount;
1820 std::string strComment;
1832 strOtherAccount.clear();
1838 if (!(nType & SER_GETHASH))
1839 READWRITE(nVersion);
1840 // Note: strAccount is serialized as part of the key, not here.
1841 READWRITE(nCreditDebit);
1843 READWRITE(strOtherAccount);
1844 READWRITE(strComment);
1857 // Alerts are for notifying old versions if they become too obsolete and
1858 // need to upgrade. The message is displayed in the status bar.
1859 // Alert messages are broadcast as a vector of signed data. Unserializing may
1860 // not read the entire buffer if the alert is for a newer version, but older
1861 // versions can still relay the original data.
1863 class CUnsignedAlert
1867 int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
1871 std::set<int> setCancel;
1872 int nMinVer; // lowest version inclusive
1873 int nMaxVer; // highest version inclusive
1874 std::set<std::string> setSubVer; // empty matches all
1878 std::string strComment;
1879 std::string strStatusBar;
1880 std::string strReserved;
1884 READWRITE(this->nVersion);
1885 nVersion = this->nVersion;
1886 READWRITE(nRelayUntil);
1887 READWRITE(nExpiration);
1890 READWRITE(setCancel);
1893 READWRITE(setSubVer);
1894 READWRITE(nPriority);
1896 READWRITE(strComment);
1897 READWRITE(strStatusBar);
1898 READWRITE(strReserved);
1915 strStatusBar.clear();
1916 strReserved.clear();
1919 std::string ToString() const
1921 std::string strSetCancel;
1922 BOOST_FOREACH(int n, setCancel)
1923 strSetCancel += strprintf("%d ", n);
1924 std::string strSetSubVer;
1925 BOOST_FOREACH(std::string str, setSubVer)
1926 strSetSubVer += "\"" + str + "\" ";
1930 " nRelayUntil = %"PRI64d"\n"
1931 " nExpiration = %"PRI64d"\n"
1939 " strComment = \"%s\"\n"
1940 " strStatusBar = \"%s\"\n"
1947 strSetCancel.c_str(),
1950 strSetSubVer.c_str(),
1953 strStatusBar.c_str());
1958 printf("%s", ToString().c_str());
1962 class CAlert : public CUnsignedAlert
1965 std::vector<unsigned char> vchMsg;
1966 std::vector<unsigned char> vchSig;
1981 CUnsignedAlert::SetNull();
1988 return (nExpiration == 0);
1991 uint256 GetHash() const
1993 return SerializeHash(*this);
1996 bool IsInEffect() const
1998 return (GetAdjustedTime() < nExpiration);
2001 bool Cancels(const CAlert& alert) const
2004 return false; // this was a no-op before 31403
2005 return (alert.nID <= nCancel || setCancel.count(alert.nID));
2008 bool AppliesTo(int nVersion, std::string strSubVerIn) const
2010 return (IsInEffect() &&
2011 nMinVer <= nVersion && nVersion <= nMaxVer &&
2012 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
2015 bool AppliesToMe() const
2017 return AppliesTo(VERSION, ::pszSubVer);
2020 bool RelayTo(CNode* pnode) const
2024 // returns true if wasn't already contained in the set
2025 if (pnode->setKnown.insert(GetHash()).second)
2027 if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
2029 GetAdjustedTime() < nRelayUntil)
2031 pnode->PushMessage("alert", *this);
2038 bool CheckSignature()
2041 if (!key.SetPubKey(ParseHex("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284")))
2042 return error("CAlert::CheckSignature() : SetPubKey failed");
2043 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
2044 return error("CAlert::CheckSignature() : verify signature failed");
2046 // Now unserialize the data
2047 CDataStream sMsg(vchMsg);
2048 sMsg >> *(CUnsignedAlert*)this;
2052 bool ProcessAlert();
2064 extern std::map<uint256, CTransaction> mapTransactions;
2065 extern std::map<uint256, CWalletTx> mapWallet;
2066 extern std::vector<uint256> vWalletUpdated;
2067 extern CCriticalSection cs_mapWallet;
2068 extern std::map<std::vector<unsigned char>, CPrivKey> mapKeys;
2069 extern std::map<uint160, std::vector<unsigned char> > mapPubKeys;
2070 extern CCriticalSection cs_mapKeys;
2071 extern CKey keyUser;