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 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, bool fForRelay=false) const
614 // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
615 int64 nBaseFee = fForRelay ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
617 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);
618 unsigned int nNewBlockSize = nBlockSize + nBytes;
619 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
625 // Transactions under 10K are free
626 // (about 4500bc if made of 50bc inputs)
632 // Free transaction area
633 if (nNewBlockSize < 27000)
638 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
639 if (nMinFee < nBaseFee)
640 BOOST_FOREACH(const CTxOut& txout, vout)
641 if (txout.nValue < CENT)
644 // Raise the price as the block approaches full
645 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
647 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
649 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
652 if (!MoneyRange(nMinFee))
658 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
660 CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");
662 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
665 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
666 return error("CTransaction::ReadFromDisk() : fseek failed");
669 // Return file pointer
672 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
673 return error("CTransaction::ReadFromDisk() : second fseek failed");
674 *pfileRet = filein.release();
679 friend bool operator==(const CTransaction& a, const CTransaction& b)
681 return (a.nVersion == b.nVersion &&
684 a.nLockTime == b.nLockTime);
687 friend bool operator!=(const CTransaction& a, const CTransaction& b)
693 std::string ToString() const
696 str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
697 GetHash().ToString().substr(0,10).c_str(),
702 for (int i = 0; i < vin.size(); i++)
703 str += " " + vin[i].ToString() + "\n";
704 for (int i = 0; i < vout.size(); i++)
705 str += " " + vout[i].ToString() + "\n";
711 printf("%s", ToString().c_str());
715 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
716 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
717 bool ReadFromDisk(COutPoint prevout);
718 bool DisconnectInputs(CTxDB& txdb);
719 bool ConnectInputs(CTxDB& txdb, std::map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
720 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee=0);
721 bool ClientConnectInputs();
722 bool CheckTransaction() const;
723 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
724 bool AcceptToMemoryPool(bool fCheckInputs=true, bool* pfMissingInputs=NULL)
727 return AcceptToMemoryPool(txdb, fCheckInputs, pfMissingInputs);
730 bool AddToMemoryPoolUnchecked();
732 bool RemoveFromMemoryPool();
740 // A transaction with a merkle branch linking it to the block chain
742 class CMerkleTx : public CTransaction
746 std::vector<uint256> vMerkleBranch;
750 mutable char fMerkleVerified;
758 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
767 fMerkleVerified = false;
773 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
774 nVersion = this->nVersion;
775 READWRITE(hashBlock);
776 READWRITE(vMerkleBranch);
781 int SetMerkleBranch(const CBlock* pblock=NULL);
782 int GetDepthInMainChain(int& nHeightRet) const;
783 int GetDepthInMainChain() const { int nHeight; return GetDepthInMainChain(nHeight); }
784 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
785 int GetBlocksToMaturity() const;
786 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
787 bool AcceptToMemoryPool() { CTxDB txdb("r"); return AcceptToMemoryPool(txdb); }
794 // A transaction with a bunch of additional info that only the owner cares
795 // about. It includes any unrecorded transactions needed to link it back
796 // to the block chain.
798 class CWalletTx : public CMerkleTx
801 std::vector<CMerkleTx> vtxPrev;
802 std::map<std::string, std::string> mapValue;
803 std::vector<std::pair<std::string, std::string> > vOrderForm;
804 unsigned int fTimeReceivedIsTxTime;
805 unsigned int nTimeReceived; // time received by this node
807 std::string strFromAccount;
808 std::vector<char> vfSpent;
811 mutable char fDebitCached;
812 mutable char fCreditCached;
813 mutable char fAvailableCreditCached;
814 mutable char fChangeCached;
815 mutable int64 nDebitCached;
816 mutable int64 nCreditCached;
817 mutable int64 nAvailableCreditCached;
818 mutable int64 nChangeCached;
820 // memory only UI hints
821 mutable unsigned int nTimeDisplayed;
822 mutable int nLinesDisplayed;
823 mutable char fConfirmedDisplayed;
831 CWalletTx(const CMerkleTx& txIn) : CMerkleTx(txIn)
836 CWalletTx(const CTransaction& txIn) : CMerkleTx(txIn)
846 fTimeReceivedIsTxTime = false;
849 strFromAccount.clear();
851 fDebitCached = false;
852 fCreditCached = false;
853 fAvailableCreditCached = false;
854 fChangeCached = false;
857 nAvailableCreditCached = 0;
861 fConfirmedDisplayed = false;
866 CWalletTx* pthis = const_cast<CWalletTx*>(this);
873 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
876 BOOST_FOREACH(char f, vfSpent)
878 str += (f ? '1' : '0');
882 pthis->mapValue["spent"] = str;
885 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
888 READWRITE(vOrderForm);
889 READWRITE(fTimeReceivedIsTxTime);
890 READWRITE(nTimeReceived);
896 pthis->strFromAccount = pthis->mapValue["fromaccount"];
898 if (mapValue.count("spent"))
899 BOOST_FOREACH(char c, pthis->mapValue["spent"])
900 pthis->vfSpent.push_back(c != '0');
902 pthis->vfSpent.assign(vout.size(), fSpent);
905 pthis->mapValue.erase("fromaccount");
906 pthis->mapValue.erase("version");
907 pthis->mapValue.erase("spent");
910 // marks certain txout's as spent
911 // returns true if any update took place
912 bool UpdateSpent(const std::vector<char>& vfNewSpent)
914 bool fReturn = false;
915 for (int i=0; i < vfNewSpent.size(); i++)
917 if (i == vfSpent.size())
920 if (vfNewSpent[i] && !vfSpent[i])
924 fAvailableCreditCached = false;
932 fCreditCached = false;
933 fAvailableCreditCached = false;
934 fDebitCached = false;
935 fChangeCached = false;
938 void MarkSpent(unsigned int nOut)
940 if (nOut >= vout.size())
941 throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
942 vfSpent.resize(vout.size());
945 vfSpent[nOut] = true;
946 fAvailableCreditCached = false;
950 bool IsSpent(unsigned int nOut) const
952 if (nOut >= vout.size())
953 throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
954 if (nOut >= vfSpent.size())
956 return (!!vfSpent[nOut]);
959 int64 GetDebit() const
965 nDebitCached = CTransaction::GetDebit();
970 int64 GetCredit(bool fUseCache=true) const
972 // Must wait until coinbase is safely deep enough in the chain before valuing it
973 if (IsCoinBase() && GetBlocksToMaturity() > 0)
976 // GetBalance can assume transactions in mapWallet won't change
977 if (fUseCache && fCreditCached)
978 return nCreditCached;
979 nCreditCached = CTransaction::GetCredit();
980 fCreditCached = true;
981 return nCreditCached;
984 int64 GetAvailableCredit(bool fUseCache=true) const
986 // Must wait until coinbase is safely deep enough in the chain before valuing it
987 if (IsCoinBase() && GetBlocksToMaturity() > 0)
990 if (fUseCache && fAvailableCreditCached)
991 return nAvailableCreditCached;
994 for (int i = 0; i < vout.size(); i++)
998 const CTxOut &txout = vout[i];
999 nCredit += txout.GetCredit();
1000 if (!MoneyRange(nCredit))
1001 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
1005 nAvailableCreditCached = nCredit;
1006 fAvailableCreditCached = true;
1011 int64 GetChange() const
1014 return nChangeCached;
1015 nChangeCached = CTransaction::GetChange();
1016 fChangeCached = true;
1017 return nChangeCached;
1020 void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<std::string /* address */, int64> >& listReceived,
1021 std::list<std::pair<std::string /* address */, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
1023 void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,
1024 int64& nSent, int64& nFee) const;
1026 bool IsFromMe() const
1028 return (GetDebit() > 0);
1031 bool IsConfirmed() const
1033 // Quick answer in most cases
1036 if (GetDepthInMainChain() >= 1)
1038 if (!IsFromMe()) // using wtx's cached debit
1041 // If no confirmations but it's from us, we can still
1042 // consider it confirmed if all dependencies are confirmed
1043 std::map<uint256, const CMerkleTx*> mapPrev;
1044 std::vector<const CMerkleTx*> vWorkQueue;
1045 vWorkQueue.reserve(vtxPrev.size()+1);
1046 vWorkQueue.push_back(this);
1047 for (int i = 0; i < vWorkQueue.size(); i++)
1049 const CMerkleTx* ptx = vWorkQueue[i];
1051 if (!ptx->IsFinal())
1053 if (ptx->GetDepthInMainChain() >= 1)
1055 if (!ptx->IsFromMe())
1058 if (mapPrev.empty())
1059 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
1060 mapPrev[tx.GetHash()] = &tx;
1062 BOOST_FOREACH(const CTxIn& txin, ptx->vin)
1064 if (!mapPrev.count(txin.prevout.hash))
1066 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
1074 return CWalletDB().WriteTx(GetHash(), *this);
1078 int64 GetTxTime() const;
1079 int GetRequestCount() const;
1081 void AddSupportingTransactions(CTxDB& txdb);
1083 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
1084 bool AcceptWalletTransaction() { CTxDB txdb("r"); return AcceptWalletTransaction(txdb); }
1086 void RelayWalletTransaction(CTxDB& txdb);
1087 void RelayWalletTransaction() { CTxDB txdb("r"); RelayWalletTransaction(txdb); }
1094 // A txdb record that contains the disk location of a transaction and the
1095 // locations of transactions that spend its outputs. vSpent is really only
1096 // used as a flag, but having the location is very helpful for debugging.
1102 std::vector<CDiskTxPos> vSpent;
1109 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
1112 vSpent.resize(nOutputs);
1117 if (!(nType & SER_GETHASH))
1118 READWRITE(nVersion);
1131 return pos.IsNull();
1134 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
1136 return (a.pos == b.pos &&
1137 a.vSpent == b.vSpent);
1140 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
1144 int GetDepthInMainChain() const;
1152 // Nodes collect new transactions into a block, hash them into a hash tree,
1153 // and scan through nonce values to make the block's hash satisfy proof-of-work
1154 // requirements. When they solve the proof-of-work, they broadcast the block
1155 // to everyone and the block is added to the block chain. The first transaction
1156 // in the block is a special one that creates a new coin owned by the creator
1159 // Blocks are appended to blk0001.dat files on disk. Their location on disk
1160 // is indexed by CBlockIndex objects in memory.
1167 uint256 hashPrevBlock;
1168 uint256 hashMerkleRoot;
1171 unsigned int nNonce;
1174 std::vector<CTransaction> vtx;
1177 mutable std::vector<uint256> vMerkleTree;
1187 READWRITE(this->nVersion);
1188 nVersion = this->nVersion;
1189 READWRITE(hashPrevBlock);
1190 READWRITE(hashMerkleRoot);
1195 // ConnectBlock depends on vtx being last so it can calculate offset
1196 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
1199 const_cast<CBlock*>(this)->vtx.clear();
1211 vMerkleTree.clear();
1216 return (nBits == 0);
1219 uint256 GetHash() const
1221 return Hash(BEGIN(nVersion), END(nNonce));
1224 int64 GetBlockTime() const
1226 return (int64)nTime;
1229 int GetSigOpCount() const
1232 BOOST_FOREACH(const CTransaction& tx, vtx)
1233 n += tx.GetSigOpCount();
1238 uint256 BuildMerkleTree() const
1240 vMerkleTree.clear();
1241 BOOST_FOREACH(const CTransaction& tx, vtx)
1242 vMerkleTree.push_back(tx.GetHash());
1244 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1246 for (int i = 0; i < nSize; i += 2)
1248 int i2 = std::min(i+1, nSize-1);
1249 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
1250 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
1254 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
1257 std::vector<uint256> GetMerkleBranch(int nIndex) const
1259 if (vMerkleTree.empty())
1261 std::vector<uint256> vMerkleBranch;
1263 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1265 int i = std::min(nIndex^1, nSize-1);
1266 vMerkleBranch.push_back(vMerkleTree[j+i]);
1270 return vMerkleBranch;
1273 static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
1277 BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
1280 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
1282 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
1289 bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
1291 // Open history file to append
1292 CAutoFile fileout = AppendBlockFile(nFileRet);
1294 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
1296 // Write index header
1297 unsigned int nSize = fileout.GetSerializeSize(*this);
1298 fileout << FLATDATA(pchMessageStart) << nSize;
1301 nBlockPosRet = ftell(fileout);
1302 if (nBlockPosRet == -1)
1303 return error("CBlock::WriteToDisk() : ftell failed");
1306 // Flush stdio buffers and commit to disk before returning
1308 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
1311 _commit(_fileno(fileout));
1313 fsync(fileno(fileout));
1320 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
1324 // Open history file to read
1325 CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");
1327 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1328 if (!fReadTransactions)
1329 filein.nType |= SER_BLOCKHEADERONLY;
1335 if (!CheckProofOfWork(GetHash(), nBits))
1336 return error("CBlock::ReadFromDisk() : errors in block header");
1345 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
1346 GetHash().ToString().substr(0,20).c_str(),
1348 hashPrevBlock.ToString().substr(0,20).c_str(),
1349 hashMerkleRoot.ToString().substr(0,10).c_str(),
1350 nTime, nBits, nNonce,
1352 for (int i = 0; i < vtx.size(); i++)
1357 printf(" vMerkleTree: ");
1358 for (int i = 0; i < vMerkleTree.size(); i++)
1359 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1364 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1365 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1366 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1367 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1368 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1369 bool CheckBlock() const;
1379 // The block chain is a tree shaped structure starting with the
1380 // genesis block at the root, with each block potentially having multiple
1381 // candidates to be the next block. pprev and pnext link a path through the
1382 // main/longest chain. A blockindex may have multiple pprev pointing back
1383 // to it, but pnext will only point forward to the longest branch, or will
1384 // be null if the block is not part of the longest chain.
1389 const uint256* phashBlock;
1393 unsigned int nBlockPos;
1395 CBigNum bnChainWork;
1399 uint256 hashMerkleRoot;
1402 unsigned int nNonce;
1422 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1428 nBlockPos = nBlockPosIn;
1432 nVersion = block.nVersion;
1433 hashMerkleRoot = block.hashMerkleRoot;
1434 nTime = block.nTime;
1435 nBits = block.nBits;
1436 nNonce = block.nNonce;
1439 CBlock GetBlockHeader() const
1442 block.nVersion = nVersion;
1444 block.hashPrevBlock = pprev->GetBlockHash();
1445 block.hashMerkleRoot = hashMerkleRoot;
1446 block.nTime = nTime;
1447 block.nBits = nBits;
1448 block.nNonce = nNonce;
1452 uint256 GetBlockHash() const
1457 int64 GetBlockTime() const
1459 return (int64)nTime;
1462 CBigNum GetBlockWork() const
1465 bnTarget.SetCompact(nBits);
1468 return (CBigNum(1)<<256) / (bnTarget+1);
1471 bool IsInMainChain() const
1473 return (pnext || this == pindexBest);
1476 bool CheckIndex() const
1478 return CheckProofOfWork(GetBlockHash(), nBits);
1481 bool EraseBlockFromDisk()
1483 // Open history file
1484 CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");
1488 // Overwrite with empty null block
1496 enum { nMedianTimeSpan=11 };
1498 int64 GetMedianTimePast() const
1500 int64 pmedian[nMedianTimeSpan];
1501 int64* pbegin = &pmedian[nMedianTimeSpan];
1502 int64* pend = &pmedian[nMedianTimeSpan];
1504 const CBlockIndex* pindex = this;
1505 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1506 *(--pbegin) = pindex->GetBlockTime();
1508 std::sort(pbegin, pend);
1509 return pbegin[(pend - pbegin)/2];
1512 int64 GetMedianTime() const
1514 const CBlockIndex* pindex = this;
1515 for (int i = 0; i < nMedianTimeSpan/2; i++)
1518 return GetBlockTime();
1519 pindex = pindex->pnext;
1521 return pindex->GetMedianTimePast();
1526 std::string ToString() const
1528 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
1529 pprev, pnext, nFile, nBlockPos, nHeight,
1530 hashMerkleRoot.ToString().substr(0,10).c_str(),
1531 GetBlockHash().ToString().substr(0,20).c_str());
1536 printf("%s\n", ToString().c_str());
1543 // Used to marshal pointers into hashes for db storage.
1545 class CDiskBlockIndex : public CBlockIndex
1557 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1559 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1560 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1565 if (!(nType & SER_GETHASH))
1566 READWRITE(nVersion);
1568 READWRITE(hashNext);
1570 READWRITE(nBlockPos);
1574 READWRITE(this->nVersion);
1575 READWRITE(hashPrev);
1576 READWRITE(hashMerkleRoot);
1582 uint256 GetBlockHash() const
1585 block.nVersion = nVersion;
1586 block.hashPrevBlock = hashPrev;
1587 block.hashMerkleRoot = hashMerkleRoot;
1588 block.nTime = nTime;
1589 block.nBits = nBits;
1590 block.nNonce = nNonce;
1591 return block.GetHash();
1595 std::string ToString() const
1597 std::string str = "CDiskBlockIndex(";
1598 str += CBlockIndex::ToString();
1599 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1600 GetBlockHash().ToString().c_str(),
1601 hashPrev.ToString().substr(0,20).c_str(),
1602 hashNext.ToString().substr(0,20).c_str());
1608 printf("%s\n", ToString().c_str());
1620 // Describes a place in the block chain to another node such that if the
1621 // other node doesn't have the same branch, it can find a recent common trunk.
1622 // The further back it is, the further before the fork it may be.
1627 std::vector<uint256> vHave;
1634 explicit CBlockLocator(const CBlockIndex* pindex)
1639 explicit CBlockLocator(uint256 hashBlock)
1641 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1642 if (mi != mapBlockIndex.end())
1648 if (!(nType & SER_GETHASH))
1649 READWRITE(nVersion);
1660 return vHave.empty();
1663 void Set(const CBlockIndex* pindex)
1669 vHave.push_back(pindex->GetBlockHash());
1671 // Exponentially larger steps back
1672 for (int i = 0; pindex && i < nStep; i++)
1673 pindex = pindex->pprev;
1674 if (vHave.size() > 10)
1677 vHave.push_back(hashGenesisBlock);
1680 int GetDistanceBack()
1682 // Retrace how far back it was in the sender's branch
1685 BOOST_FOREACH(const uint256& hash, vHave)
1687 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1688 if (mi != mapBlockIndex.end())
1690 CBlockIndex* pindex = (*mi).second;
1691 if (pindex->IsInMainChain())
1701 CBlockIndex* GetBlockIndex()
1703 // Find the first block the caller has in the main chain
1704 BOOST_FOREACH(const uint256& hash, vHave)
1706 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1707 if (mi != mapBlockIndex.end())
1709 CBlockIndex* pindex = (*mi).second;
1710 if (pindex->IsInMainChain())
1714 return pindexGenesisBlock;
1717 uint256 GetBlockHash()
1719 // Find the first block the caller has in the main chain
1720 BOOST_FOREACH(const uint256& hash, vHave)
1722 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1723 if (mi != mapBlockIndex.end())
1725 CBlockIndex* pindex = (*mi).second;
1726 if (pindex->IsInMainChain())
1730 return hashGenesisBlock;
1735 CBlockIndex* pindex = GetBlockIndex();
1738 return pindex->nHeight;
1748 // Private key that includes an expiration date in case it never gets used.
1753 CPrivKey vchPrivKey;
1756 std::string strComment;
1757 //// todo: add something to note what created it (user, getnewaddress, change)
1758 //// maybe should have a map<string, string> property map
1760 CWalletKey(int64 nExpires=0)
1762 nTimeCreated = (nExpires ? GetTime() : 0);
1763 nTimeExpires = nExpires;
1768 if (!(nType & SER_GETHASH))
1769 READWRITE(nVersion);
1770 READWRITE(vchPrivKey);
1771 READWRITE(nTimeCreated);
1772 READWRITE(nTimeExpires);
1773 READWRITE(strComment);
1783 // Account information.
1784 // Stored in wallet with key "acc"+string account name
1789 std::vector<unsigned char> vchPubKey;
1803 if (!(nType & SER_GETHASH))
1804 READWRITE(nVersion);
1805 READWRITE(vchPubKey);
1812 // Internal transfers.
1813 // Database key is acentry<account><counter>
1815 class CAccountingEntry
1818 std::string strAccount;
1821 std::string strOtherAccount;
1822 std::string strComment;
1834 strOtherAccount.clear();
1840 if (!(nType & SER_GETHASH))
1841 READWRITE(nVersion);
1842 // Note: strAccount is serialized as part of the key, not here.
1843 READWRITE(nCreditDebit);
1845 READWRITE(strOtherAccount);
1846 READWRITE(strComment);
1859 // Alerts are for notifying old versions if they become too obsolete and
1860 // need to upgrade. The message is displayed in the status bar.
1861 // Alert messages are broadcast as a vector of signed data. Unserializing may
1862 // not read the entire buffer if the alert is for a newer version, but older
1863 // versions can still relay the original data.
1865 class CUnsignedAlert
1869 int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
1873 std::set<int> setCancel;
1874 int nMinVer; // lowest version inclusive
1875 int nMaxVer; // highest version inclusive
1876 std::set<std::string> setSubVer; // empty matches all
1880 std::string strComment;
1881 std::string strStatusBar;
1882 std::string strReserved;
1886 READWRITE(this->nVersion);
1887 nVersion = this->nVersion;
1888 READWRITE(nRelayUntil);
1889 READWRITE(nExpiration);
1892 READWRITE(setCancel);
1895 READWRITE(setSubVer);
1896 READWRITE(nPriority);
1898 READWRITE(strComment);
1899 READWRITE(strStatusBar);
1900 READWRITE(strReserved);
1917 strStatusBar.clear();
1918 strReserved.clear();
1921 std::string ToString() const
1923 std::string strSetCancel;
1924 BOOST_FOREACH(int n, setCancel)
1925 strSetCancel += strprintf("%d ", n);
1926 std::string strSetSubVer;
1927 BOOST_FOREACH(std::string str, setSubVer)
1928 strSetSubVer += "\"" + str + "\" ";
1932 " nRelayUntil = %"PRI64d"\n"
1933 " nExpiration = %"PRI64d"\n"
1941 " strComment = \"%s\"\n"
1942 " strStatusBar = \"%s\"\n"
1949 strSetCancel.c_str(),
1952 strSetSubVer.c_str(),
1955 strStatusBar.c_str());
1960 printf("%s", ToString().c_str());
1964 class CAlert : public CUnsignedAlert
1967 std::vector<unsigned char> vchMsg;
1968 std::vector<unsigned char> vchSig;
1983 CUnsignedAlert::SetNull();
1990 return (nExpiration == 0);
1993 uint256 GetHash() const
1995 return SerializeHash(*this);
1998 bool IsInEffect() const
2000 return (GetAdjustedTime() < nExpiration);
2003 bool Cancels(const CAlert& alert) const
2006 return false; // this was a no-op before 31403
2007 return (alert.nID <= nCancel || setCancel.count(alert.nID));
2010 bool AppliesTo(int nVersion, std::string strSubVerIn) const
2012 return (IsInEffect() &&
2013 nMinVer <= nVersion && nVersion <= nMaxVer &&
2014 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
2017 bool AppliesToMe() const
2019 return AppliesTo(VERSION, ::pszSubVer);
2022 bool RelayTo(CNode* pnode) const
2026 // returns true if wasn't already contained in the set
2027 if (pnode->setKnown.insert(GetHash()).second)
2029 if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
2031 GetAdjustedTime() < nRelayUntil)
2033 pnode->PushMessage("alert", *this);
2040 bool CheckSignature()
2043 if (!key.SetPubKey(ParseHex("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284")))
2044 return error("CAlert::CheckSignature() : SetPubKey failed");
2045 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
2046 return error("CAlert::CheckSignature() : verify signature failed");
2048 // Now unserialize the data
2049 CDataStream sMsg(vchMsg);
2050 sMsg >> *(CUnsignedAlert*)this;
2054 bool ProcessAlert();
2066 extern std::map<uint256, CTransaction> mapTransactions;
2067 extern std::map<uint256, CWalletTx> mapWallet;
2068 extern std::vector<uint256> vWalletUpdated;
2069 extern CCriticalSection cs_mapWallet;
2070 extern std::map<std::vector<unsigned char>, CPrivKey> mapKeys;
2071 extern std::map<uint160, std::vector<unsigned char> > mapPubKeys;
2072 extern CCriticalSection cs_mapKeys;
2073 extern CKey keyUser;