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.
27 static const unsigned int MAX_BLOCK_SIZE = 1000000;
28 static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/2;
29 static const int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
30 static const int64 COIN = 100000000;
31 static const int64 CENT = 1000000;
32 static const int64 MIN_TX_FEE = CENT;
33 static const int64 MIN_RELAY_TX_FEE = 50000;
34 static const int64 MAX_MONEY = 21000000 * COIN;
35 inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
36 static const int COINBASE_MATURITY = 100;
38 static const int fHaveUPnP = true;
40 static const int fHaveUPnP = false;
48 extern CCriticalSection cs_main;
49 extern std::map<uint256, CBlockIndex*> mapBlockIndex;
50 extern uint256 hashGenesisBlock;
51 extern CBigNum bnProofOfWorkLimit;
52 extern CBlockIndex* pindexGenesisBlock;
53 extern int nBestHeight;
54 extern CBigNum bnBestChainWork;
55 extern CBigNum bnBestInvalidWork;
56 extern uint256 hashBestChain;
57 extern CBlockIndex* pindexBest;
58 extern unsigned int nTransactionsUpdated;
59 extern std::map<uint256, int> mapRequestCount;
60 extern CCriticalSection cs_mapRequestCount;
61 extern std::map<std::string, std::string> mapAddressBook;
62 extern CCriticalSection cs_mapAddressBook;
63 extern std::vector<unsigned char> vchDefaultKey;
64 extern double dHashesPerSec;
65 extern int64 nHPSTimerStart;
68 extern int fGenerateBitcoins;
69 extern int64 nTransactionFee;
70 extern CAddress addrIncoming;
71 extern int fLimitProcessors;
72 extern int nLimitProcessors;
73 extern int fMinimizeToTray;
74 extern int fMinimizeOnClose;
83 bool CheckDiskSpace(uint64 nAdditionalBytes=0);
84 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
85 FILE* AppendBlockFile(unsigned int& nFileRet);
86 bool AddKey(const CKey& key);
87 std::vector<unsigned char> GenerateNewKey();
88 bool AddToWallet(const CWalletTx& wtxIn);
89 void WalletUpdateSpent(const COutPoint& prevout);
90 int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
91 void ReacceptWalletTransactions();
92 bool LoadBlockIndex(bool fAllowNew=true);
93 void PrintBlockTree();
94 bool ProcessMessages(CNode* pfrom);
95 bool ProcessMessage(CNode* pfrom, std::string strCommand, CDataStream& vRecv);
96 bool SendMessages(CNode* pto, bool fSendTrickle);
98 bool CreateTransaction(const std::vector<std::pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
99 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
100 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
101 bool BroadcastTransaction(CWalletTx& wtxNew);
102 std::string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
103 std::string SendMoneyToBitcoinAddress(std::string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
104 void GenerateBitcoins(bool fGenerate);
105 void ThreadBitcoinMiner(void* parg);
106 CBlock* CreateNewBlock(CReserveKey& reservekey);
107 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce, int64& nPrevTime);
108 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
109 bool CheckWork(CBlock* pblock, CReserveKey& reservekey);
111 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
112 bool IsInitialBlockDownload();
113 std::string GetWarnings(std::string strFor);
130 unsigned int nBlockPos;
138 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
141 nBlockPos = nBlockPosIn;
145 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
146 void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
147 bool IsNull() const { return (nFile == -1); }
149 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
151 return (a.nFile == b.nFile &&
152 a.nBlockPos == b.nBlockPos &&
153 a.nTxPos == b.nTxPos);
156 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
161 std::string ToString() const
164 return strprintf("null");
166 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
171 printf("%s", ToString().c_str());
184 CInPoint() { SetNull(); }
185 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
186 void SetNull() { ptx = NULL; n = -1; }
187 bool IsNull() const { return (ptx == NULL && n == -1); }
199 COutPoint() { SetNull(); }
200 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
201 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
202 void SetNull() { hash = 0; n = -1; }
203 bool IsNull() const { return (hash == 0 && n == -1); }
205 friend bool operator<(const COutPoint& a, const COutPoint& b)
207 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
210 friend bool operator==(const COutPoint& a, const COutPoint& b)
212 return (a.hash == b.hash && a.n == b.n);
215 friend bool operator!=(const COutPoint& a, const COutPoint& b)
220 std::string ToString() const
222 return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,10).c_str(), n);
227 printf("%s\n", ToString().c_str());
235 // An input of a transaction. It contains the location of the previous
236 // transaction's output that it claims and a signature that matches the
237 // output's public key.
244 unsigned int nSequence;
248 nSequence = UINT_MAX;
251 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
254 scriptSig = scriptSigIn;
255 nSequence = nSequenceIn;
258 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
260 prevout = COutPoint(hashPrevTx, nOut);
261 scriptSig = scriptSigIn;
262 nSequence = nSequenceIn;
268 READWRITE(scriptSig);
269 READWRITE(nSequence);
274 return (nSequence == UINT_MAX);
277 friend bool operator==(const CTxIn& a, const CTxIn& b)
279 return (a.prevout == b.prevout &&
280 a.scriptSig == b.scriptSig &&
281 a.nSequence == b.nSequence);
284 friend bool operator!=(const CTxIn& a, const CTxIn& b)
289 std::string ToString() const
292 str += strprintf("CTxIn(");
293 str += prevout.ToString();
294 if (prevout.IsNull())
295 str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
297 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
298 if (nSequence != UINT_MAX)
299 str += strprintf(", nSequence=%u", nSequence);
306 printf("%s\n", ToString().c_str());
310 int64 GetDebit() const;
317 // An output of a transaction. It contains the public key that the next input
318 // must be able to sign with to claim it.
324 CScript scriptPubKey;
331 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
334 scriptPubKey = scriptPubKeyIn;
340 READWRITE(scriptPubKey);
346 scriptPubKey.clear();
351 return (nValue == -1);
354 uint256 GetHash() const
356 return SerializeHash(*this);
361 return ::IsMine(scriptPubKey);
364 int64 GetCredit() const
366 if (!MoneyRange(nValue))
367 throw std::runtime_error("CTxOut::GetCredit() : value out of range");
368 return (IsMine() ? nValue : 0);
371 bool IsChange() const
373 // On a debit transaction, a txout that's mine but isn't in the address book is change
374 std::vector<unsigned char> vchPubKey;
375 if (ExtractPubKey(scriptPubKey, true, vchPubKey))
376 CRITICAL_BLOCK(cs_mapAddressBook)
377 if (!mapAddressBook.count(PubKeyToAddress(vchPubKey)))
382 int64 GetChange() const
384 if (!MoneyRange(nValue))
385 throw std::runtime_error("CTxOut::GetChange() : value out of range");
386 return (IsChange() ? nValue : 0);
389 friend bool operator==(const CTxOut& a, const CTxOut& b)
391 return (a.nValue == b.nValue &&
392 a.scriptPubKey == b.scriptPubKey);
395 friend bool operator!=(const CTxOut& a, const CTxOut& b)
400 std::string ToString() const
402 if (scriptPubKey.size() < 6)
403 return "CTxOut(error)";
404 return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,30).c_str());
409 printf("%s\n", ToString().c_str());
417 // The basic transaction that is broadcasted on the network and contained in
418 // blocks. A transaction can contain multiple inputs and outputs.
424 std::vector<CTxIn> vin;
425 std::vector<CTxOut> vout;
426 unsigned int nLockTime;
436 READWRITE(this->nVersion);
437 nVersion = this->nVersion;
440 READWRITE(nLockTime);
453 return (vin.empty() && vout.empty());
456 uint256 GetHash() const
458 return SerializeHash(*this);
461 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
463 // Time based nLockTime implemented in 0.1.6
466 if (nBlockHeight == 0)
467 nBlockHeight = nBestHeight;
469 nBlockTime = GetAdjustedTime();
470 if ((int64)nLockTime < (nLockTime < 500000000 ? (int64)nBlockHeight : nBlockTime))
472 BOOST_FOREACH(const CTxIn& txin, vin)
478 bool IsNewerThan(const CTransaction& old) const
480 if (vin.size() != old.vin.size())
482 for (int i = 0; i < vin.size(); i++)
483 if (vin[i].prevout != old.vin[i].prevout)
487 unsigned int nLowest = UINT_MAX;
488 for (int i = 0; i < vin.size(); i++)
490 if (vin[i].nSequence != old.vin[i].nSequence)
492 if (vin[i].nSequence <= nLowest)
495 nLowest = vin[i].nSequence;
497 if (old.vin[i].nSequence < nLowest)
500 nLowest = old.vin[i].nSequence;
507 bool IsCoinBase() const
509 return (vin.size() == 1 && vin[0].prevout.IsNull());
512 int GetSigOpCount() const
515 BOOST_FOREACH(const CTxIn& txin, vin)
516 n += txin.scriptSig.GetSigOpCount();
517 BOOST_FOREACH(const CTxOut& txout, vout)
518 n += txout.scriptPubKey.GetSigOpCount();
522 bool IsStandard() const
524 BOOST_FOREACH(const CTxIn& txin, vin)
525 if (!txin.scriptSig.IsPushOnly())
526 return error("nonstandard txin: %s", txin.scriptSig.ToString().c_str());
527 BOOST_FOREACH(const CTxOut& txout, vout)
528 if (!::IsStandard(txout.scriptPubKey))
529 return error("nonstandard txout: %s", txout.scriptPubKey.ToString().c_str());
535 BOOST_FOREACH(const CTxOut& txout, vout)
541 bool IsFromMe() const
543 return (GetDebit() > 0);
546 int64 GetDebit() const
549 BOOST_FOREACH(const CTxIn& txin, vin)
551 nDebit += txin.GetDebit();
552 if (!MoneyRange(nDebit))
553 throw std::runtime_error("CTransaction::GetDebit() : value out of range");
558 int64 GetCredit() const
561 BOOST_FOREACH(const CTxOut& txout, vout)
563 nCredit += txout.GetCredit();
564 if (!MoneyRange(nCredit))
565 throw std::runtime_error("CTransaction::GetCredit() : value out of range");
570 int64 GetChange() const
575 BOOST_FOREACH(const CTxOut& txout, vout)
577 nChange += txout.GetChange();
578 if (!MoneyRange(nChange))
579 throw std::runtime_error("CTransaction::GetChange() : value out of range");
584 int64 GetValueOut() const
587 BOOST_FOREACH(const CTxOut& txout, vout)
589 nValueOut += txout.nValue;
590 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
591 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
596 static bool AllowFree(double dPriority)
598 // Large (in bytes) low-priority (new, small-coin) transactions
600 return dPriority > COIN * 144 / 250;
603 int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=true, bool fForRelay=false) const
605 // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
606 int64 nBaseFee = fForRelay ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
608 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);
609 unsigned int nNewBlockSize = nBlockSize + nBytes;
610 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
616 // Transactions under 10K are free
617 // (about 4500bc if made of 50bc inputs)
623 // Free transaction area
624 if (nNewBlockSize < 27000)
629 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
630 if (nMinFee < nBaseFee)
631 BOOST_FOREACH(const CTxOut& txout, vout)
632 if (txout.nValue < CENT)
635 // Raise the price as the block approaches full
636 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
638 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
640 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
643 if (!MoneyRange(nMinFee))
649 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
651 CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");
653 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
656 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
657 return error("CTransaction::ReadFromDisk() : fseek failed");
660 // Return file pointer
663 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
664 return error("CTransaction::ReadFromDisk() : second fseek failed");
665 *pfileRet = filein.release();
670 friend bool operator==(const CTransaction& a, const CTransaction& b)
672 return (a.nVersion == b.nVersion &&
675 a.nLockTime == b.nLockTime);
678 friend bool operator!=(const CTransaction& a, const CTransaction& b)
684 std::string ToString() const
687 str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
688 GetHash().ToString().substr(0,10).c_str(),
693 for (int i = 0; i < vin.size(); i++)
694 str += " " + vin[i].ToString() + "\n";
695 for (int i = 0; i < vout.size(); i++)
696 str += " " + vout[i].ToString() + "\n";
702 printf("%s", ToString().c_str());
706 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
707 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
708 bool ReadFromDisk(COutPoint prevout);
709 bool DisconnectInputs(CTxDB& txdb);
710 bool ConnectInputs(CTxDB& txdb, std::map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
711 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee=0);
712 bool ClientConnectInputs();
713 bool CheckTransaction() const;
714 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
715 bool AcceptToMemoryPool(bool fCheckInputs=true, bool* pfMissingInputs=NULL)
718 return AcceptToMemoryPool(txdb, fCheckInputs, pfMissingInputs);
721 bool AddToMemoryPoolUnchecked();
723 bool RemoveFromMemoryPool();
731 // A transaction with a merkle branch linking it to the block chain
733 class CMerkleTx : public CTransaction
737 std::vector<uint256> vMerkleBranch;
741 mutable char fMerkleVerified;
749 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
758 fMerkleVerified = false;
764 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
765 nVersion = this->nVersion;
766 READWRITE(hashBlock);
767 READWRITE(vMerkleBranch);
772 int SetMerkleBranch(const CBlock* pblock=NULL);
773 int GetDepthInMainChain(int& nHeightRet) const;
774 int GetDepthInMainChain() const { int nHeight; return GetDepthInMainChain(nHeight); }
775 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
776 int GetBlocksToMaturity() const;
777 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
778 bool AcceptToMemoryPool() { CTxDB txdb("r"); return AcceptToMemoryPool(txdb); }
785 // A transaction with a bunch of additional info that only the owner cares
786 // about. It includes any unrecorded transactions needed to link it back
787 // to the block chain.
789 class CWalletTx : public CMerkleTx
792 std::vector<CMerkleTx> vtxPrev;
793 std::map<std::string, std::string> mapValue;
794 std::vector<std::pair<std::string, std::string> > vOrderForm;
795 unsigned int fTimeReceivedIsTxTime;
796 unsigned int nTimeReceived; // time received by this node
798 std::string strFromAccount;
799 std::vector<char> vfSpent;
802 mutable char fDebitCached;
803 mutable char fCreditCached;
804 mutable char fAvailableCreditCached;
805 mutable char fChangeCached;
806 mutable int64 nDebitCached;
807 mutable int64 nCreditCached;
808 mutable int64 nAvailableCreditCached;
809 mutable int64 nChangeCached;
811 // memory only UI hints
812 mutable unsigned int nTimeDisplayed;
813 mutable int nLinesDisplayed;
814 mutable char fConfirmedDisplayed;
822 CWalletTx(const CMerkleTx& txIn) : CMerkleTx(txIn)
827 CWalletTx(const CTransaction& txIn) : CMerkleTx(txIn)
837 fTimeReceivedIsTxTime = false;
840 strFromAccount.clear();
842 fDebitCached = false;
843 fCreditCached = false;
844 fAvailableCreditCached = false;
845 fChangeCached = false;
848 nAvailableCreditCached = 0;
852 fConfirmedDisplayed = false;
857 CWalletTx* pthis = const_cast<CWalletTx*>(this);
864 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
867 BOOST_FOREACH(char f, vfSpent)
869 str += (f ? '1' : '0');
873 pthis->mapValue["spent"] = str;
876 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
879 READWRITE(vOrderForm);
880 READWRITE(fTimeReceivedIsTxTime);
881 READWRITE(nTimeReceived);
887 pthis->strFromAccount = pthis->mapValue["fromaccount"];
889 if (mapValue.count("spent"))
890 BOOST_FOREACH(char c, pthis->mapValue["spent"])
891 pthis->vfSpent.push_back(c != '0');
893 pthis->vfSpent.assign(vout.size(), fSpent);
896 pthis->mapValue.erase("fromaccount");
897 pthis->mapValue.erase("version");
898 pthis->mapValue.erase("spent");
901 // marks certain txout's as spent
902 // returns true if any update took place
903 bool UpdateSpent(const std::vector<char>& vfNewSpent)
905 bool fReturn = false;
906 for (int i=0; i < vfNewSpent.size(); i++)
908 if (i == vfSpent.size())
911 if (vfNewSpent[i] && !vfSpent[i])
915 fAvailableCreditCached = false;
923 fCreditCached = false;
924 fAvailableCreditCached = false;
925 fDebitCached = false;
926 fChangeCached = false;
929 void MarkSpent(unsigned int nOut)
931 if (nOut >= vout.size())
932 throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
933 vfSpent.resize(vout.size());
936 vfSpent[nOut] = true;
937 fAvailableCreditCached = false;
941 bool IsSpent(unsigned int nOut) const
943 if (nOut >= vout.size())
944 throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
945 if (nOut >= vfSpent.size())
947 return (!!vfSpent[nOut]);
950 int64 GetDebit() const
956 nDebitCached = CTransaction::GetDebit();
961 int64 GetCredit(bool fUseCache=true) const
963 // Must wait until coinbase is safely deep enough in the chain before valuing it
964 if (IsCoinBase() && GetBlocksToMaturity() > 0)
967 // GetBalance can assume transactions in mapWallet won't change
968 if (fUseCache && fCreditCached)
969 return nCreditCached;
970 nCreditCached = CTransaction::GetCredit();
971 fCreditCached = true;
972 return nCreditCached;
975 int64 GetAvailableCredit(bool fUseCache=true) const
977 // Must wait until coinbase is safely deep enough in the chain before valuing it
978 if (IsCoinBase() && GetBlocksToMaturity() > 0)
981 if (fUseCache && fAvailableCreditCached)
982 return nAvailableCreditCached;
985 for (int i = 0; i < vout.size(); i++)
989 const CTxOut &txout = vout[i];
990 nCredit += txout.GetCredit();
991 if (!MoneyRange(nCredit))
992 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
996 nAvailableCreditCached = nCredit;
997 fAvailableCreditCached = true;
1002 int64 GetChange() const
1005 return nChangeCached;
1006 nChangeCached = CTransaction::GetChange();
1007 fChangeCached = true;
1008 return nChangeCached;
1011 void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<std::string /* address */, int64> >& listReceived,
1012 std::list<std::pair<std::string /* address */, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
1014 void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,
1015 int64& nSent, int64& nFee) const;
1017 bool IsFromMe() const
1019 return (GetDebit() > 0);
1022 bool IsConfirmed() const
1024 // Quick answer in most cases
1027 if (GetDepthInMainChain() >= 1)
1029 if (!IsFromMe()) // using wtx's cached debit
1032 // If no confirmations but it's from us, we can still
1033 // consider it confirmed if all dependencies are confirmed
1034 std::map<uint256, const CMerkleTx*> mapPrev;
1035 std::vector<const CMerkleTx*> vWorkQueue;
1036 vWorkQueue.reserve(vtxPrev.size()+1);
1037 vWorkQueue.push_back(this);
1038 for (int i = 0; i < vWorkQueue.size(); i++)
1040 const CMerkleTx* ptx = vWorkQueue[i];
1042 if (!ptx->IsFinal())
1044 if (ptx->GetDepthInMainChain() >= 1)
1046 if (!ptx->IsFromMe())
1049 if (mapPrev.empty())
1050 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
1051 mapPrev[tx.GetHash()] = &tx;
1053 BOOST_FOREACH(const CTxIn& txin, ptx->vin)
1055 if (!mapPrev.count(txin.prevout.hash))
1057 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
1065 return CWalletDB().WriteTx(GetHash(), *this);
1069 int64 GetTxTime() const;
1070 int GetRequestCount() const;
1072 void AddSupportingTransactions(CTxDB& txdb);
1074 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
1075 bool AcceptWalletTransaction() { CTxDB txdb("r"); return AcceptWalletTransaction(txdb); }
1077 void RelayWalletTransaction(CTxDB& txdb);
1078 void RelayWalletTransaction() { CTxDB txdb("r"); RelayWalletTransaction(txdb); }
1085 // A txdb record that contains the disk location of a transaction and the
1086 // locations of transactions that spend its outputs. vSpent is really only
1087 // used as a flag, but having the location is very helpful for debugging.
1093 std::vector<CDiskTxPos> vSpent;
1100 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
1103 vSpent.resize(nOutputs);
1108 if (!(nType & SER_GETHASH))
1109 READWRITE(nVersion);
1122 return pos.IsNull();
1125 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
1127 return (a.pos == b.pos &&
1128 a.vSpent == b.vSpent);
1131 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
1135 int GetDepthInMainChain() const;
1143 // Nodes collect new transactions into a block, hash them into a hash tree,
1144 // and scan through nonce values to make the block's hash satisfy proof-of-work
1145 // requirements. When they solve the proof-of-work, they broadcast the block
1146 // to everyone and the block is added to the block chain. The first transaction
1147 // in the block is a special one that creates a new coin owned by the creator
1150 // Blocks are appended to blk0001.dat files on disk. Their location on disk
1151 // is indexed by CBlockIndex objects in memory.
1158 uint256 hashPrevBlock;
1159 uint256 hashMerkleRoot;
1162 unsigned int nNonce;
1165 std::vector<CTransaction> vtx;
1168 mutable std::vector<uint256> vMerkleTree;
1178 READWRITE(this->nVersion);
1179 nVersion = this->nVersion;
1180 READWRITE(hashPrevBlock);
1181 READWRITE(hashMerkleRoot);
1186 // ConnectBlock depends on vtx being last so it can calculate offset
1187 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
1190 const_cast<CBlock*>(this)->vtx.clear();
1202 vMerkleTree.clear();
1207 return (nBits == 0);
1210 uint256 GetHash() const
1212 return Hash(BEGIN(nVersion), END(nNonce));
1215 int64 GetBlockTime() const
1217 return (int64)nTime;
1220 int GetSigOpCount() const
1223 BOOST_FOREACH(const CTransaction& tx, vtx)
1224 n += tx.GetSigOpCount();
1229 uint256 BuildMerkleTree() const
1231 vMerkleTree.clear();
1232 BOOST_FOREACH(const CTransaction& tx, vtx)
1233 vMerkleTree.push_back(tx.GetHash());
1235 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1237 for (int i = 0; i < nSize; i += 2)
1239 int i2 = std::min(i+1, nSize-1);
1240 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
1241 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
1245 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
1248 std::vector<uint256> GetMerkleBranch(int nIndex) const
1250 if (vMerkleTree.empty())
1252 std::vector<uint256> vMerkleBranch;
1254 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1256 int i = std::min(nIndex^1, nSize-1);
1257 vMerkleBranch.push_back(vMerkleTree[j+i]);
1261 return vMerkleBranch;
1264 static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
1268 BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
1271 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
1273 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
1280 bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
1282 // Open history file to append
1283 CAutoFile fileout = AppendBlockFile(nFileRet);
1285 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
1287 // Write index header
1288 unsigned int nSize = fileout.GetSerializeSize(*this);
1289 fileout << FLATDATA(pchMessageStart) << nSize;
1292 nBlockPosRet = ftell(fileout);
1293 if (nBlockPosRet == -1)
1294 return error("CBlock::WriteToDisk() : ftell failed");
1297 // Flush stdio buffers and commit to disk before returning
1299 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
1302 _commit(_fileno(fileout));
1304 fsync(fileno(fileout));
1311 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
1315 // Open history file to read
1316 CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");
1318 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1319 if (!fReadTransactions)
1320 filein.nType |= SER_BLOCKHEADERONLY;
1326 if (!CheckProofOfWork(GetHash(), nBits))
1327 return error("CBlock::ReadFromDisk() : errors in block header");
1336 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
1337 GetHash().ToString().substr(0,20).c_str(),
1339 hashPrevBlock.ToString().substr(0,20).c_str(),
1340 hashMerkleRoot.ToString().substr(0,10).c_str(),
1341 nTime, nBits, nNonce,
1343 for (int i = 0; i < vtx.size(); i++)
1348 printf(" vMerkleTree: ");
1349 for (int i = 0; i < vMerkleTree.size(); i++)
1350 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1355 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1356 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1357 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1358 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1359 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1360 bool CheckBlock() const;
1370 // The block chain is a tree shaped structure starting with the
1371 // genesis block at the root, with each block potentially having multiple
1372 // candidates to be the next block. pprev and pnext link a path through the
1373 // main/longest chain. A blockindex may have multiple pprev pointing back
1374 // to it, but pnext will only point forward to the longest branch, or will
1375 // be null if the block is not part of the longest chain.
1380 const uint256* phashBlock;
1384 unsigned int nBlockPos;
1386 CBigNum bnChainWork;
1390 uint256 hashMerkleRoot;
1393 unsigned int nNonce;
1413 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1419 nBlockPos = nBlockPosIn;
1423 nVersion = block.nVersion;
1424 hashMerkleRoot = block.hashMerkleRoot;
1425 nTime = block.nTime;
1426 nBits = block.nBits;
1427 nNonce = block.nNonce;
1430 CBlock GetBlockHeader() const
1433 block.nVersion = nVersion;
1435 block.hashPrevBlock = pprev->GetBlockHash();
1436 block.hashMerkleRoot = hashMerkleRoot;
1437 block.nTime = nTime;
1438 block.nBits = nBits;
1439 block.nNonce = nNonce;
1443 uint256 GetBlockHash() const
1448 int64 GetBlockTime() const
1450 return (int64)nTime;
1453 CBigNum GetBlockWork() const
1456 bnTarget.SetCompact(nBits);
1459 return (CBigNum(1)<<256) / (bnTarget+1);
1462 bool IsInMainChain() const
1464 return (pnext || this == pindexBest);
1467 bool CheckIndex() const
1469 return CheckProofOfWork(GetBlockHash(), nBits);
1472 bool EraseBlockFromDisk()
1474 // Open history file
1475 CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");
1479 // Overwrite with empty null block
1487 enum { nMedianTimeSpan=11 };
1489 int64 GetMedianTimePast() const
1491 int64 pmedian[nMedianTimeSpan];
1492 int64* pbegin = &pmedian[nMedianTimeSpan];
1493 int64* pend = &pmedian[nMedianTimeSpan];
1495 const CBlockIndex* pindex = this;
1496 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1497 *(--pbegin) = pindex->GetBlockTime();
1499 std::sort(pbegin, pend);
1500 return pbegin[(pend - pbegin)/2];
1503 int64 GetMedianTime() const
1505 const CBlockIndex* pindex = this;
1506 for (int i = 0; i < nMedianTimeSpan/2; i++)
1509 return GetBlockTime();
1510 pindex = pindex->pnext;
1512 return pindex->GetMedianTimePast();
1517 std::string ToString() const
1519 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
1520 pprev, pnext, nFile, nBlockPos, nHeight,
1521 hashMerkleRoot.ToString().substr(0,10).c_str(),
1522 GetBlockHash().ToString().substr(0,20).c_str());
1527 printf("%s\n", ToString().c_str());
1534 // Used to marshal pointers into hashes for db storage.
1536 class CDiskBlockIndex : public CBlockIndex
1548 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1550 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1551 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1556 if (!(nType & SER_GETHASH))
1557 READWRITE(nVersion);
1559 READWRITE(hashNext);
1561 READWRITE(nBlockPos);
1565 READWRITE(this->nVersion);
1566 READWRITE(hashPrev);
1567 READWRITE(hashMerkleRoot);
1573 uint256 GetBlockHash() const
1576 block.nVersion = nVersion;
1577 block.hashPrevBlock = hashPrev;
1578 block.hashMerkleRoot = hashMerkleRoot;
1579 block.nTime = nTime;
1580 block.nBits = nBits;
1581 block.nNonce = nNonce;
1582 return block.GetHash();
1586 std::string ToString() const
1588 std::string str = "CDiskBlockIndex(";
1589 str += CBlockIndex::ToString();
1590 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1591 GetBlockHash().ToString().c_str(),
1592 hashPrev.ToString().substr(0,20).c_str(),
1593 hashNext.ToString().substr(0,20).c_str());
1599 printf("%s\n", ToString().c_str());
1611 // Describes a place in the block chain to another node such that if the
1612 // other node doesn't have the same branch, it can find a recent common trunk.
1613 // The further back it is, the further before the fork it may be.
1618 std::vector<uint256> vHave;
1625 explicit CBlockLocator(const CBlockIndex* pindex)
1630 explicit CBlockLocator(uint256 hashBlock)
1632 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1633 if (mi != mapBlockIndex.end())
1639 if (!(nType & SER_GETHASH))
1640 READWRITE(nVersion);
1651 return vHave.empty();
1654 void Set(const CBlockIndex* pindex)
1660 vHave.push_back(pindex->GetBlockHash());
1662 // Exponentially larger steps back
1663 for (int i = 0; pindex && i < nStep; i++)
1664 pindex = pindex->pprev;
1665 if (vHave.size() > 10)
1668 vHave.push_back(hashGenesisBlock);
1671 int GetDistanceBack()
1673 // Retrace how far back it was in the sender's branch
1676 BOOST_FOREACH(const uint256& hash, vHave)
1678 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1679 if (mi != mapBlockIndex.end())
1681 CBlockIndex* pindex = (*mi).second;
1682 if (pindex->IsInMainChain())
1692 CBlockIndex* GetBlockIndex()
1694 // Find the first block the caller has in the main chain
1695 BOOST_FOREACH(const uint256& hash, vHave)
1697 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1698 if (mi != mapBlockIndex.end())
1700 CBlockIndex* pindex = (*mi).second;
1701 if (pindex->IsInMainChain())
1705 return pindexGenesisBlock;
1708 uint256 GetBlockHash()
1710 // Find the first block the caller has in the main chain
1711 BOOST_FOREACH(const uint256& hash, vHave)
1713 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1714 if (mi != mapBlockIndex.end())
1716 CBlockIndex* pindex = (*mi).second;
1717 if (pindex->IsInMainChain())
1721 return hashGenesisBlock;
1726 CBlockIndex* pindex = GetBlockIndex();
1729 return pindex->nHeight;
1739 // Private key that includes an expiration date in case it never gets used.
1744 CPrivKey vchPrivKey;
1747 std::string strComment;
1748 //// todo: add something to note what created it (user, getnewaddress, change)
1749 //// maybe should have a map<string, string> property map
1751 CWalletKey(int64 nExpires=0)
1753 nTimeCreated = (nExpires ? GetTime() : 0);
1754 nTimeExpires = nExpires;
1759 if (!(nType & SER_GETHASH))
1760 READWRITE(nVersion);
1761 READWRITE(vchPrivKey);
1762 READWRITE(nTimeCreated);
1763 READWRITE(nTimeExpires);
1764 READWRITE(strComment);
1774 // Account information.
1775 // Stored in wallet with key "acc"+string account name
1780 std::vector<unsigned char> vchPubKey;
1794 if (!(nType & SER_GETHASH))
1795 READWRITE(nVersion);
1796 READWRITE(vchPubKey);
1803 // Internal transfers.
1804 // Database key is acentry<account><counter>
1806 class CAccountingEntry
1809 std::string strAccount;
1812 std::string strOtherAccount;
1813 std::string strComment;
1825 strOtherAccount.clear();
1831 if (!(nType & SER_GETHASH))
1832 READWRITE(nVersion);
1833 // Note: strAccount is serialized as part of the key, not here.
1834 READWRITE(nCreditDebit);
1836 READWRITE(strOtherAccount);
1837 READWRITE(strComment);
1850 // Alerts are for notifying old versions if they become too obsolete and
1851 // need to upgrade. The message is displayed in the status bar.
1852 // Alert messages are broadcast as a vector of signed data. Unserializing may
1853 // not read the entire buffer if the alert is for a newer version, but older
1854 // versions can still relay the original data.
1856 class CUnsignedAlert
1860 int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
1864 std::set<int> setCancel;
1865 int nMinVer; // lowest version inclusive
1866 int nMaxVer; // highest version inclusive
1867 std::set<std::string> setSubVer; // empty matches all
1871 std::string strComment;
1872 std::string strStatusBar;
1873 std::string strReserved;
1877 READWRITE(this->nVersion);
1878 nVersion = this->nVersion;
1879 READWRITE(nRelayUntil);
1880 READWRITE(nExpiration);
1883 READWRITE(setCancel);
1886 READWRITE(setSubVer);
1887 READWRITE(nPriority);
1889 READWRITE(strComment);
1890 READWRITE(strStatusBar);
1891 READWRITE(strReserved);
1908 strStatusBar.clear();
1909 strReserved.clear();
1912 std::string ToString() const
1914 std::string strSetCancel;
1915 BOOST_FOREACH(int n, setCancel)
1916 strSetCancel += strprintf("%d ", n);
1917 std::string strSetSubVer;
1918 BOOST_FOREACH(std::string str, setSubVer)
1919 strSetSubVer += "\"" + str + "\" ";
1923 " nRelayUntil = %"PRI64d"\n"
1924 " nExpiration = %"PRI64d"\n"
1932 " strComment = \"%s\"\n"
1933 " strStatusBar = \"%s\"\n"
1940 strSetCancel.c_str(),
1943 strSetSubVer.c_str(),
1946 strStatusBar.c_str());
1951 printf("%s", ToString().c_str());
1955 class CAlert : public CUnsignedAlert
1958 std::vector<unsigned char> vchMsg;
1959 std::vector<unsigned char> vchSig;
1974 CUnsignedAlert::SetNull();
1981 return (nExpiration == 0);
1984 uint256 GetHash() const
1986 return SerializeHash(*this);
1989 bool IsInEffect() const
1991 return (GetAdjustedTime() < nExpiration);
1994 bool Cancels(const CAlert& alert) const
1997 return false; // this was a no-op before 31403
1998 return (alert.nID <= nCancel || setCancel.count(alert.nID));
2001 bool AppliesTo(int nVersion, std::string strSubVerIn) const
2003 return (IsInEffect() &&
2004 nMinVer <= nVersion && nVersion <= nMaxVer &&
2005 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
2008 bool AppliesToMe() const
2010 return AppliesTo(VERSION, ::pszSubVer);
2013 bool RelayTo(CNode* pnode) const
2017 // returns true if wasn't already contained in the set
2018 if (pnode->setKnown.insert(GetHash()).second)
2020 if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
2022 GetAdjustedTime() < nRelayUntil)
2024 pnode->PushMessage("alert", *this);
2031 bool CheckSignature()
2034 if (!key.SetPubKey(ParseHex("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284")))
2035 return error("CAlert::CheckSignature() : SetPubKey failed");
2036 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
2037 return error("CAlert::CheckSignature() : verify signature failed");
2039 // Now unserialize the data
2040 CDataStream sMsg(vchMsg);
2041 sMsg >> *(CUnsignedAlert*)this;
2045 bool ProcessAlert();
2057 extern std::map<uint256, CTransaction> mapTransactions;
2058 extern std::map<uint256, CWalletTx> mapWallet;
2059 extern std::vector<uint256> vWalletUpdated;
2060 extern CCriticalSection cs_mapWallet;
2061 extern std::map<std::vector<unsigned char>, CPrivKey> mapKeys;
2062 extern std::map<uint160, std::vector<unsigned char> > mapPubKeys;
2063 extern CCriticalSection cs_mapKeys;
2064 extern CKey keyUser;