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 = 50000;
33 static const int64 MAX_MONEY = 21000000 * COIN;
34 inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
35 static const int COINBASE_MATURITY = 100;
37 static const int fHaveUPnP = true;
39 static const int fHaveUPnP = false;
47 extern CCriticalSection cs_main;
48 extern std::map<uint256, CBlockIndex*> mapBlockIndex;
49 extern uint256 hashGenesisBlock;
50 extern CBigNum bnProofOfWorkLimit;
51 extern CBlockIndex* pindexGenesisBlock;
52 extern int nBestHeight;
53 extern CBigNum bnBestChainWork;
54 extern CBigNum bnBestInvalidWork;
55 extern uint256 hashBestChain;
56 extern CBlockIndex* pindexBest;
57 extern unsigned int nTransactionsUpdated;
58 extern std::map<uint256, int> mapRequestCount;
59 extern CCriticalSection cs_mapRequestCount;
60 extern std::map<std::string, std::string> mapAddressBook;
61 extern CCriticalSection cs_mapAddressBook;
62 extern std::vector<unsigned char> vchDefaultKey;
63 extern double dHashesPerSec;
64 extern int64 nHPSTimerStart;
67 extern int fGenerateBitcoins;
68 extern int64 nTransactionFee;
69 extern CAddress addrIncoming;
70 extern int fLimitProcessors;
71 extern int nLimitProcessors;
72 extern int fMinimizeToTray;
73 extern int fMinimizeOnClose;
82 bool CheckDiskSpace(uint64 nAdditionalBytes=0);
83 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
84 FILE* AppendBlockFile(unsigned int& nFileRet);
85 bool AddKey(const CKey& key);
86 std::vector<unsigned char> GenerateNewKey();
87 bool AddToWallet(const CWalletTx& wtxIn);
88 void WalletUpdateSpent(const COutPoint& prevout);
89 int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
90 void ReacceptWalletTransactions();
91 bool LoadBlockIndex(bool fAllowNew=true);
92 void PrintBlockTree();
93 bool ProcessMessages(CNode* pfrom);
94 bool ProcessMessage(CNode* pfrom, std::string strCommand, CDataStream& vRecv);
95 bool SendMessages(CNode* pto, bool fSendTrickle);
97 bool CreateTransaction(const std::vector<std::pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
98 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
99 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
100 bool BroadcastTransaction(CWalletTx& wtxNew);
101 std::string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
102 std::string SendMoneyToBitcoinAddress(std::string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
103 void GenerateBitcoins(bool fGenerate);
104 void ThreadBitcoinMiner(void* parg);
105 CBlock* CreateNewBlock(CReserveKey& reservekey);
106 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce, int64& nPrevTime);
107 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
108 bool CheckWork(CBlock* pblock, CReserveKey& reservekey);
110 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
111 bool IsInitialBlockDownload();
112 std::string GetWarnings(std::string strFor);
129 unsigned int nBlockPos;
137 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
140 nBlockPos = nBlockPosIn;
144 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
145 void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
146 bool IsNull() const { return (nFile == -1); }
148 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
150 return (a.nFile == b.nFile &&
151 a.nBlockPos == b.nBlockPos &&
152 a.nTxPos == b.nTxPos);
155 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
160 std::string ToString() const
163 return strprintf("null");
165 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
170 printf("%s", ToString().c_str());
183 CInPoint() { SetNull(); }
184 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
185 void SetNull() { ptx = NULL; n = -1; }
186 bool IsNull() const { return (ptx == NULL && n == -1); }
198 COutPoint() { SetNull(); }
199 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
200 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
201 void SetNull() { hash = 0; n = -1; }
202 bool IsNull() const { return (hash == 0 && n == -1); }
204 friend bool operator<(const COutPoint& a, const COutPoint& b)
206 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
209 friend bool operator==(const COutPoint& a, const COutPoint& b)
211 return (a.hash == b.hash && a.n == b.n);
214 friend bool operator!=(const COutPoint& a, const COutPoint& b)
219 std::string ToString() const
221 return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,10).c_str(), n);
226 printf("%s\n", ToString().c_str());
234 // An input of a transaction. It contains the location of the previous
235 // transaction's output that it claims and a signature that matches the
236 // output's public key.
243 unsigned int nSequence;
247 nSequence = UINT_MAX;
250 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
253 scriptSig = scriptSigIn;
254 nSequence = nSequenceIn;
257 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
259 prevout = COutPoint(hashPrevTx, nOut);
260 scriptSig = scriptSigIn;
261 nSequence = nSequenceIn;
267 READWRITE(scriptSig);
268 READWRITE(nSequence);
273 return (nSequence == UINT_MAX);
276 friend bool operator==(const CTxIn& a, const CTxIn& b)
278 return (a.prevout == b.prevout &&
279 a.scriptSig == b.scriptSig &&
280 a.nSequence == b.nSequence);
283 friend bool operator!=(const CTxIn& a, const CTxIn& b)
288 std::string ToString() const
291 str += strprintf("CTxIn(");
292 str += prevout.ToString();
293 if (prevout.IsNull())
294 str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
296 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
297 if (nSequence != UINT_MAX)
298 str += strprintf(", nSequence=%u", nSequence);
305 printf("%s\n", ToString().c_str());
309 int64 GetDebit() const;
316 // An output of a transaction. It contains the public key that the next input
317 // must be able to sign with to claim it.
323 CScript scriptPubKey;
330 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
333 scriptPubKey = scriptPubKeyIn;
339 READWRITE(scriptPubKey);
345 scriptPubKey.clear();
350 return (nValue == -1);
353 uint256 GetHash() const
355 return SerializeHash(*this);
360 return ::IsMine(scriptPubKey);
363 int64 GetCredit() const
365 if (!MoneyRange(nValue))
366 throw std::runtime_error("CTxOut::GetCredit() : value out of range");
367 return (IsMine() ? nValue : 0);
370 bool IsChange() const
372 // On a debit transaction, a txout that's mine but isn't in the address book is change
373 std::vector<unsigned char> vchPubKey;
374 if (ExtractPubKey(scriptPubKey, true, vchPubKey))
375 CRITICAL_BLOCK(cs_mapAddressBook)
376 if (!mapAddressBook.count(PubKeyToAddress(vchPubKey)))
381 int64 GetChange() const
383 if (!MoneyRange(nValue))
384 throw std::runtime_error("CTxOut::GetChange() : value out of range");
385 return (IsChange() ? nValue : 0);
388 friend bool operator==(const CTxOut& a, const CTxOut& b)
390 return (a.nValue == b.nValue &&
391 a.scriptPubKey == b.scriptPubKey);
394 friend bool operator!=(const CTxOut& a, const CTxOut& b)
399 std::string ToString() const
401 if (scriptPubKey.size() < 6)
402 return "CTxOut(error)";
403 return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,30).c_str());
408 printf("%s\n", ToString().c_str());
416 // The basic transaction that is broadcasted on the network and contained in
417 // blocks. A transaction can contain multiple inputs and outputs.
423 std::vector<CTxIn> vin;
424 std::vector<CTxOut> vout;
425 unsigned int nLockTime;
435 READWRITE(this->nVersion);
436 nVersion = this->nVersion;
439 READWRITE(nLockTime);
452 return (vin.empty() && vout.empty());
455 uint256 GetHash() const
457 return SerializeHash(*this);
460 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
462 // Time based nLockTime implemented in 0.1.6
465 if (nBlockHeight == 0)
466 nBlockHeight = nBestHeight;
468 nBlockTime = GetAdjustedTime();
469 if ((int64)nLockTime < (nLockTime < 500000000 ? (int64)nBlockHeight : nBlockTime))
471 BOOST_FOREACH(const CTxIn& txin, vin)
477 bool IsNewerThan(const CTransaction& old) const
479 if (vin.size() != old.vin.size())
481 for (int i = 0; i < vin.size(); i++)
482 if (vin[i].prevout != old.vin[i].prevout)
486 unsigned int nLowest = UINT_MAX;
487 for (int i = 0; i < vin.size(); i++)
489 if (vin[i].nSequence != old.vin[i].nSequence)
491 if (vin[i].nSequence <= nLowest)
494 nLowest = vin[i].nSequence;
496 if (old.vin[i].nSequence < nLowest)
499 nLowest = old.vin[i].nSequence;
506 bool IsCoinBase() const
508 return (vin.size() == 1 && vin[0].prevout.IsNull());
511 int GetSigOpCount() const
514 BOOST_FOREACH(const CTxIn& txin, vin)
515 n += txin.scriptSig.GetSigOpCount();
516 BOOST_FOREACH(const CTxOut& txout, vout)
517 n += txout.scriptPubKey.GetSigOpCount();
521 bool IsStandard() const
523 BOOST_FOREACH(const CTxIn& txin, vin)
524 if (!txin.scriptSig.IsPushOnly())
525 return error("nonstandard txin: %s", txin.scriptSig.ToString().c_str());
526 BOOST_FOREACH(const CTxOut& txout, vout)
527 if (!::IsStandard(txout.scriptPubKey))
528 return error("nonstandard txout: %s", txout.scriptPubKey.ToString().c_str());
534 BOOST_FOREACH(const CTxOut& txout, vout)
540 bool IsFromMe() const
542 return (GetDebit() > 0);
545 int64 GetDebit() const
548 BOOST_FOREACH(const CTxIn& txin, vin)
550 nDebit += txin.GetDebit();
551 if (!MoneyRange(nDebit))
552 throw std::runtime_error("CTransaction::GetDebit() : value out of range");
557 int64 GetCredit() const
560 BOOST_FOREACH(const CTxOut& txout, vout)
562 nCredit += txout.GetCredit();
563 if (!MoneyRange(nCredit))
564 throw std::runtime_error("CTransaction::GetCredit() : value out of range");
569 int64 GetChange() const
574 BOOST_FOREACH(const CTxOut& txout, vout)
576 nChange += txout.GetChange();
577 if (!MoneyRange(nChange))
578 throw std::runtime_error("CTransaction::GetChange() : value out of range");
583 int64 GetValueOut() const
586 BOOST_FOREACH(const CTxOut& txout, vout)
588 nValueOut += txout.nValue;
589 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
590 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
595 static bool AllowFree(double dPriority)
597 // Large (in bytes) low-priority (new, small-coin) transactions
599 return dPriority > COIN * 144 / 250;
602 int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=true) const
604 // Base fee is 1 cent per kilobyte
605 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);
606 unsigned int nNewBlockSize = nBlockSize + nBytes;
607 int64 nMinFee = (1 + (int64)nBytes / 1000) * MIN_TX_FEE;
613 // Transactions under 10K are free
614 // (about 4500bc if made of 50bc inputs)
620 // Free transaction area
621 if (nNewBlockSize < 27000)
626 // To limit dust spam, require MIN_TX_FEE if any output is less than 0.01
627 if (nMinFee < MIN_TX_FEE)
628 BOOST_FOREACH(const CTxOut& txout, vout)
629 if (txout.nValue < CENT)
630 nMinFee = MIN_TX_FEE;
632 // Raise the price as the block approaches full
633 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
635 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
637 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
640 if (!MoneyRange(nMinFee))
646 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
648 CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");
650 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
653 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
654 return error("CTransaction::ReadFromDisk() : fseek failed");
657 // Return file pointer
660 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
661 return error("CTransaction::ReadFromDisk() : second fseek failed");
662 *pfileRet = filein.release();
667 friend bool operator==(const CTransaction& a, const CTransaction& b)
669 return (a.nVersion == b.nVersion &&
672 a.nLockTime == b.nLockTime);
675 friend bool operator!=(const CTransaction& a, const CTransaction& b)
681 std::string ToString() const
684 str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
685 GetHash().ToString().substr(0,10).c_str(),
690 for (int i = 0; i < vin.size(); i++)
691 str += " " + vin[i].ToString() + "\n";
692 for (int i = 0; i < vout.size(); i++)
693 str += " " + vout[i].ToString() + "\n";
699 printf("%s", ToString().c_str());
703 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
704 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
705 bool ReadFromDisk(COutPoint prevout);
706 bool DisconnectInputs(CTxDB& txdb);
707 bool ConnectInputs(CTxDB& txdb, std::map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
708 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee=0);
709 bool ClientConnectInputs();
710 bool CheckTransaction() const;
711 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
712 bool AcceptToMemoryPool(bool fCheckInputs=true, bool* pfMissingInputs=NULL)
715 return AcceptToMemoryPool(txdb, fCheckInputs, pfMissingInputs);
718 bool AddToMemoryPoolUnchecked();
720 bool RemoveFromMemoryPool();
728 // A transaction with a merkle branch linking it to the block chain
730 class CMerkleTx : public CTransaction
734 std::vector<uint256> vMerkleBranch;
738 mutable char fMerkleVerified;
746 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
755 fMerkleVerified = false;
761 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
762 nVersion = this->nVersion;
763 READWRITE(hashBlock);
764 READWRITE(vMerkleBranch);
769 int SetMerkleBranch(const CBlock* pblock=NULL);
770 int GetDepthInMainChain(int& nHeightRet) const;
771 int GetDepthInMainChain() const { int nHeight; return GetDepthInMainChain(nHeight); }
772 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
773 int GetBlocksToMaturity() const;
774 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
775 bool AcceptToMemoryPool() { CTxDB txdb("r"); return AcceptToMemoryPool(txdb); }
782 // A transaction with a bunch of additional info that only the owner cares
783 // about. It includes any unrecorded transactions needed to link it back
784 // to the block chain.
786 class CWalletTx : public CMerkleTx
789 std::vector<CMerkleTx> vtxPrev;
790 std::map<std::string, std::string> mapValue;
791 std::vector<std::pair<std::string, std::string> > vOrderForm;
792 unsigned int fTimeReceivedIsTxTime;
793 unsigned int nTimeReceived; // time received by this node
795 std::string strFromAccount;
796 std::vector<char> vfSpent;
799 mutable char fDebitCached;
800 mutable char fCreditCached;
801 mutable char fAvailableCreditCached;
802 mutable char fChangeCached;
803 mutable int64 nDebitCached;
804 mutable int64 nCreditCached;
805 mutable int64 nAvailableCreditCached;
806 mutable int64 nChangeCached;
808 // memory only UI hints
809 mutable unsigned int nTimeDisplayed;
810 mutable int nLinesDisplayed;
811 mutable char fConfirmedDisplayed;
819 CWalletTx(const CMerkleTx& txIn) : CMerkleTx(txIn)
824 CWalletTx(const CTransaction& txIn) : CMerkleTx(txIn)
834 fTimeReceivedIsTxTime = false;
837 strFromAccount.clear();
839 fDebitCached = false;
840 fCreditCached = false;
841 fAvailableCreditCached = false;
842 fChangeCached = false;
845 nAvailableCreditCached = 0;
849 fConfirmedDisplayed = false;
854 CWalletTx* pthis = const_cast<CWalletTx*>(this);
861 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
864 BOOST_FOREACH(char f, vfSpent)
866 str += (f ? '1' : '0');
870 pthis->mapValue["spent"] = str;
873 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
876 READWRITE(vOrderForm);
877 READWRITE(fTimeReceivedIsTxTime);
878 READWRITE(nTimeReceived);
884 pthis->strFromAccount = pthis->mapValue["fromaccount"];
886 if (mapValue.count("spent"))
887 BOOST_FOREACH(char c, pthis->mapValue["spent"])
888 pthis->vfSpent.push_back(c != '0');
890 pthis->vfSpent.assign(vout.size(), fSpent);
893 pthis->mapValue.erase("fromaccount");
894 pthis->mapValue.erase("version");
895 pthis->mapValue.erase("spent");
898 // marks certain txout's as spent
899 // returns true if any update took place
900 bool UpdateSpent(const std::vector<char>& vfNewSpent)
902 bool fReturn = false;
903 for (int i=0; i < vfNewSpent.size(); i++)
905 if (i == vfSpent.size())
908 if (vfNewSpent[i] && !vfSpent[i])
912 fAvailableCreditCached = false;
920 fCreditCached = false;
921 fAvailableCreditCached = false;
922 fDebitCached = false;
923 fChangeCached = false;
926 void MarkSpent(unsigned int nOut)
928 if (nOut >= vout.size())
929 throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
930 vfSpent.resize(vout.size());
933 vfSpent[nOut] = true;
934 fAvailableCreditCached = false;
938 bool IsSpent(unsigned int nOut) const
940 if (nOut >= vout.size())
941 throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
942 if (nOut >= vfSpent.size())
944 return (!!vfSpent[nOut]);
947 int64 GetDebit() const
953 nDebitCached = CTransaction::GetDebit();
958 int64 GetCredit(bool fUseCache=true) const
960 // Must wait until coinbase is safely deep enough in the chain before valuing it
961 if (IsCoinBase() && GetBlocksToMaturity() > 0)
964 // GetBalance can assume transactions in mapWallet won't change
965 if (fUseCache && fCreditCached)
966 return nCreditCached;
967 nCreditCached = CTransaction::GetCredit();
968 fCreditCached = true;
969 return nCreditCached;
972 int64 GetAvailableCredit(bool fUseCache=true) const
974 // Must wait until coinbase is safely deep enough in the chain before valuing it
975 if (IsCoinBase() && GetBlocksToMaturity() > 0)
978 if (fUseCache && fAvailableCreditCached)
979 return nAvailableCreditCached;
982 for (int i = 0; i < vout.size(); i++)
986 const CTxOut &txout = vout[i];
987 nCredit += txout.GetCredit();
988 if (!MoneyRange(nCredit))
989 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
993 nAvailableCreditCached = nCredit;
994 fAvailableCreditCached = true;
999 int64 GetChange() const
1002 return nChangeCached;
1003 nChangeCached = CTransaction::GetChange();
1004 fChangeCached = true;
1005 return nChangeCached;
1008 void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<std::string /* address */, int64> >& listReceived,
1009 std::list<std::pair<std::string /* address */, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
1011 void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,
1012 int64& nSent, int64& nFee) const;
1014 bool IsFromMe() const
1016 return (GetDebit() > 0);
1019 bool IsConfirmed() const
1021 // Quick answer in most cases
1024 if (GetDepthInMainChain() >= 1)
1026 if (!IsFromMe()) // using wtx's cached debit
1029 // If no confirmations but it's from us, we can still
1030 // consider it confirmed if all dependencies are confirmed
1031 std::map<uint256, const CMerkleTx*> mapPrev;
1032 std::vector<const CMerkleTx*> vWorkQueue;
1033 vWorkQueue.reserve(vtxPrev.size()+1);
1034 vWorkQueue.push_back(this);
1035 for (int i = 0; i < vWorkQueue.size(); i++)
1037 const CMerkleTx* ptx = vWorkQueue[i];
1039 if (!ptx->IsFinal())
1041 if (ptx->GetDepthInMainChain() >= 1)
1043 if (!ptx->IsFromMe())
1046 if (mapPrev.empty())
1047 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
1048 mapPrev[tx.GetHash()] = &tx;
1050 BOOST_FOREACH(const CTxIn& txin, ptx->vin)
1052 if (!mapPrev.count(txin.prevout.hash))
1054 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
1062 return CWalletDB().WriteTx(GetHash(), *this);
1066 int64 GetTxTime() const;
1067 int GetRequestCount() const;
1069 void AddSupportingTransactions(CTxDB& txdb);
1071 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
1072 bool AcceptWalletTransaction() { CTxDB txdb("r"); return AcceptWalletTransaction(txdb); }
1074 void RelayWalletTransaction(CTxDB& txdb);
1075 void RelayWalletTransaction() { CTxDB txdb("r"); RelayWalletTransaction(txdb); }
1082 // A txdb record that contains the disk location of a transaction and the
1083 // locations of transactions that spend its outputs. vSpent is really only
1084 // used as a flag, but having the location is very helpful for debugging.
1090 std::vector<CDiskTxPos> vSpent;
1097 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
1100 vSpent.resize(nOutputs);
1105 if (!(nType & SER_GETHASH))
1106 READWRITE(nVersion);
1119 return pos.IsNull();
1122 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
1124 return (a.pos == b.pos &&
1125 a.vSpent == b.vSpent);
1128 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
1132 int GetDepthInMainChain() const;
1140 // Nodes collect new transactions into a block, hash them into a hash tree,
1141 // and scan through nonce values to make the block's hash satisfy proof-of-work
1142 // requirements. When they solve the proof-of-work, they broadcast the block
1143 // to everyone and the block is added to the block chain. The first transaction
1144 // in the block is a special one that creates a new coin owned by the creator
1147 // Blocks are appended to blk0001.dat files on disk. Their location on disk
1148 // is indexed by CBlockIndex objects in memory.
1155 uint256 hashPrevBlock;
1156 uint256 hashMerkleRoot;
1159 unsigned int nNonce;
1162 std::vector<CTransaction> vtx;
1165 mutable std::vector<uint256> vMerkleTree;
1175 READWRITE(this->nVersion);
1176 nVersion = this->nVersion;
1177 READWRITE(hashPrevBlock);
1178 READWRITE(hashMerkleRoot);
1183 // ConnectBlock depends on vtx being last so it can calculate offset
1184 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
1187 const_cast<CBlock*>(this)->vtx.clear();
1199 vMerkleTree.clear();
1204 return (nBits == 0);
1207 uint256 GetHash() const
1209 return Hash(BEGIN(nVersion), END(nNonce));
1212 int64 GetBlockTime() const
1214 return (int64)nTime;
1217 int GetSigOpCount() const
1220 BOOST_FOREACH(const CTransaction& tx, vtx)
1221 n += tx.GetSigOpCount();
1226 uint256 BuildMerkleTree() const
1228 vMerkleTree.clear();
1229 BOOST_FOREACH(const CTransaction& tx, vtx)
1230 vMerkleTree.push_back(tx.GetHash());
1232 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1234 for (int i = 0; i < nSize; i += 2)
1236 int i2 = std::min(i+1, nSize-1);
1237 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
1238 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
1242 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
1245 std::vector<uint256> GetMerkleBranch(int nIndex) const
1247 if (vMerkleTree.empty())
1249 std::vector<uint256> vMerkleBranch;
1251 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1253 int i = std::min(nIndex^1, nSize-1);
1254 vMerkleBranch.push_back(vMerkleTree[j+i]);
1258 return vMerkleBranch;
1261 static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
1265 BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
1268 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
1270 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
1277 bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
1279 // Open history file to append
1280 CAutoFile fileout = AppendBlockFile(nFileRet);
1282 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
1284 // Write index header
1285 unsigned int nSize = fileout.GetSerializeSize(*this);
1286 fileout << FLATDATA(pchMessageStart) << nSize;
1289 nBlockPosRet = ftell(fileout);
1290 if (nBlockPosRet == -1)
1291 return error("CBlock::WriteToDisk() : ftell failed");
1294 // Flush stdio buffers and commit to disk before returning
1296 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
1299 _commit(_fileno(fileout));
1301 fsync(fileno(fileout));
1308 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
1312 // Open history file to read
1313 CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");
1315 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1316 if (!fReadTransactions)
1317 filein.nType |= SER_BLOCKHEADERONLY;
1323 if (!CheckProofOfWork(GetHash(), nBits))
1324 return error("CBlock::ReadFromDisk() : errors in block header");
1333 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
1334 GetHash().ToString().substr(0,20).c_str(),
1336 hashPrevBlock.ToString().substr(0,20).c_str(),
1337 hashMerkleRoot.ToString().substr(0,10).c_str(),
1338 nTime, nBits, nNonce,
1340 for (int i = 0; i < vtx.size(); i++)
1345 printf(" vMerkleTree: ");
1346 for (int i = 0; i < vMerkleTree.size(); i++)
1347 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1352 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1353 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1354 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1355 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1356 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1357 bool CheckBlock() const;
1367 // The block chain is a tree shaped structure starting with the
1368 // genesis block at the root, with each block potentially having multiple
1369 // candidates to be the next block. pprev and pnext link a path through the
1370 // main/longest chain. A blockindex may have multiple pprev pointing back
1371 // to it, but pnext will only point forward to the longest branch, or will
1372 // be null if the block is not part of the longest chain.
1377 const uint256* phashBlock;
1381 unsigned int nBlockPos;
1383 CBigNum bnChainWork;
1387 uint256 hashMerkleRoot;
1390 unsigned int nNonce;
1410 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1416 nBlockPos = nBlockPosIn;
1420 nVersion = block.nVersion;
1421 hashMerkleRoot = block.hashMerkleRoot;
1422 nTime = block.nTime;
1423 nBits = block.nBits;
1424 nNonce = block.nNonce;
1427 CBlock GetBlockHeader() const
1430 block.nVersion = nVersion;
1432 block.hashPrevBlock = pprev->GetBlockHash();
1433 block.hashMerkleRoot = hashMerkleRoot;
1434 block.nTime = nTime;
1435 block.nBits = nBits;
1436 block.nNonce = nNonce;
1440 uint256 GetBlockHash() const
1445 int64 GetBlockTime() const
1447 return (int64)nTime;
1450 CBigNum GetBlockWork() const
1453 bnTarget.SetCompact(nBits);
1456 return (CBigNum(1)<<256) / (bnTarget+1);
1459 bool IsInMainChain() const
1461 return (pnext || this == pindexBest);
1464 bool CheckIndex() const
1466 return CheckProofOfWork(GetBlockHash(), nBits);
1469 bool EraseBlockFromDisk()
1471 // Open history file
1472 CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");
1476 // Overwrite with empty null block
1484 enum { nMedianTimeSpan=11 };
1486 int64 GetMedianTimePast() const
1488 int64 pmedian[nMedianTimeSpan];
1489 int64* pbegin = &pmedian[nMedianTimeSpan];
1490 int64* pend = &pmedian[nMedianTimeSpan];
1492 const CBlockIndex* pindex = this;
1493 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1494 *(--pbegin) = pindex->GetBlockTime();
1496 std::sort(pbegin, pend);
1497 return pbegin[(pend - pbegin)/2];
1500 int64 GetMedianTime() const
1502 const CBlockIndex* pindex = this;
1503 for (int i = 0; i < nMedianTimeSpan/2; i++)
1506 return GetBlockTime();
1507 pindex = pindex->pnext;
1509 return pindex->GetMedianTimePast();
1514 std::string ToString() const
1516 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
1517 pprev, pnext, nFile, nBlockPos, nHeight,
1518 hashMerkleRoot.ToString().substr(0,10).c_str(),
1519 GetBlockHash().ToString().substr(0,20).c_str());
1524 printf("%s\n", ToString().c_str());
1531 // Used to marshal pointers into hashes for db storage.
1533 class CDiskBlockIndex : public CBlockIndex
1545 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1547 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1548 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1553 if (!(nType & SER_GETHASH))
1554 READWRITE(nVersion);
1556 READWRITE(hashNext);
1558 READWRITE(nBlockPos);
1562 READWRITE(this->nVersion);
1563 READWRITE(hashPrev);
1564 READWRITE(hashMerkleRoot);
1570 uint256 GetBlockHash() const
1573 block.nVersion = nVersion;
1574 block.hashPrevBlock = hashPrev;
1575 block.hashMerkleRoot = hashMerkleRoot;
1576 block.nTime = nTime;
1577 block.nBits = nBits;
1578 block.nNonce = nNonce;
1579 return block.GetHash();
1583 std::string ToString() const
1585 std::string str = "CDiskBlockIndex(";
1586 str += CBlockIndex::ToString();
1587 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1588 GetBlockHash().ToString().c_str(),
1589 hashPrev.ToString().substr(0,20).c_str(),
1590 hashNext.ToString().substr(0,20).c_str());
1596 printf("%s\n", ToString().c_str());
1608 // Describes a place in the block chain to another node such that if the
1609 // other node doesn't have the same branch, it can find a recent common trunk.
1610 // The further back it is, the further before the fork it may be.
1615 std::vector<uint256> vHave;
1622 explicit CBlockLocator(const CBlockIndex* pindex)
1627 explicit CBlockLocator(uint256 hashBlock)
1629 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1630 if (mi != mapBlockIndex.end())
1636 if (!(nType & SER_GETHASH))
1637 READWRITE(nVersion);
1648 return vHave.empty();
1651 void Set(const CBlockIndex* pindex)
1657 vHave.push_back(pindex->GetBlockHash());
1659 // Exponentially larger steps back
1660 for (int i = 0; pindex && i < nStep; i++)
1661 pindex = pindex->pprev;
1662 if (vHave.size() > 10)
1665 vHave.push_back(hashGenesisBlock);
1668 int GetDistanceBack()
1670 // Retrace how far back it was in the sender's branch
1673 BOOST_FOREACH(const uint256& hash, vHave)
1675 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1676 if (mi != mapBlockIndex.end())
1678 CBlockIndex* pindex = (*mi).second;
1679 if (pindex->IsInMainChain())
1689 CBlockIndex* GetBlockIndex()
1691 // Find the first block the caller has in the main chain
1692 BOOST_FOREACH(const uint256& hash, vHave)
1694 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1695 if (mi != mapBlockIndex.end())
1697 CBlockIndex* pindex = (*mi).second;
1698 if (pindex->IsInMainChain())
1702 return pindexGenesisBlock;
1705 uint256 GetBlockHash()
1707 // Find the first block the caller has in the main chain
1708 BOOST_FOREACH(const uint256& hash, vHave)
1710 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1711 if (mi != mapBlockIndex.end())
1713 CBlockIndex* pindex = (*mi).second;
1714 if (pindex->IsInMainChain())
1718 return hashGenesisBlock;
1723 CBlockIndex* pindex = GetBlockIndex();
1726 return pindex->nHeight;
1736 // Private key that includes an expiration date in case it never gets used.
1741 CPrivKey vchPrivKey;
1744 std::string strComment;
1745 //// todo: add something to note what created it (user, getnewaddress, change)
1746 //// maybe should have a map<string, string> property map
1748 CWalletKey(int64 nExpires=0)
1750 nTimeCreated = (nExpires ? GetTime() : 0);
1751 nTimeExpires = nExpires;
1756 if (!(nType & SER_GETHASH))
1757 READWRITE(nVersion);
1758 READWRITE(vchPrivKey);
1759 READWRITE(nTimeCreated);
1760 READWRITE(nTimeExpires);
1761 READWRITE(strComment);
1771 // Account information.
1772 // Stored in wallet with key "acc"+string account name
1777 std::vector<unsigned char> vchPubKey;
1791 if (!(nType & SER_GETHASH))
1792 READWRITE(nVersion);
1793 READWRITE(vchPubKey);
1800 // Internal transfers.
1801 // Database key is acentry<account><counter>
1803 class CAccountingEntry
1806 std::string strAccount;
1809 std::string strOtherAccount;
1810 std::string strComment;
1822 strOtherAccount.clear();
1828 if (!(nType & SER_GETHASH))
1829 READWRITE(nVersion);
1830 // Note: strAccount is serialized as part of the key, not here.
1831 READWRITE(nCreditDebit);
1833 READWRITE(strOtherAccount);
1834 READWRITE(strComment);
1847 // Alerts are for notifying old versions if they become too obsolete and
1848 // need to upgrade. The message is displayed in the status bar.
1849 // Alert messages are broadcast as a vector of signed data. Unserializing may
1850 // not read the entire buffer if the alert is for a newer version, but older
1851 // versions can still relay the original data.
1853 class CUnsignedAlert
1857 int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
1861 std::set<int> setCancel;
1862 int nMinVer; // lowest version inclusive
1863 int nMaxVer; // highest version inclusive
1864 std::set<std::string> setSubVer; // empty matches all
1868 std::string strComment;
1869 std::string strStatusBar;
1870 std::string strReserved;
1874 READWRITE(this->nVersion);
1875 nVersion = this->nVersion;
1876 READWRITE(nRelayUntil);
1877 READWRITE(nExpiration);
1880 READWRITE(setCancel);
1883 READWRITE(setSubVer);
1884 READWRITE(nPriority);
1886 READWRITE(strComment);
1887 READWRITE(strStatusBar);
1888 READWRITE(strReserved);
1905 strStatusBar.clear();
1906 strReserved.clear();
1909 std::string ToString() const
1911 std::string strSetCancel;
1912 BOOST_FOREACH(int n, setCancel)
1913 strSetCancel += strprintf("%d ", n);
1914 std::string strSetSubVer;
1915 BOOST_FOREACH(std::string str, setSubVer)
1916 strSetSubVer += "\"" + str + "\" ";
1920 " nRelayUntil = %"PRI64d"\n"
1921 " nExpiration = %"PRI64d"\n"
1929 " strComment = \"%s\"\n"
1930 " strStatusBar = \"%s\"\n"
1937 strSetCancel.c_str(),
1940 strSetSubVer.c_str(),
1943 strStatusBar.c_str());
1948 printf("%s", ToString().c_str());
1952 class CAlert : public CUnsignedAlert
1955 std::vector<unsigned char> vchMsg;
1956 std::vector<unsigned char> vchSig;
1971 CUnsignedAlert::SetNull();
1978 return (nExpiration == 0);
1981 uint256 GetHash() const
1983 return SerializeHash(*this);
1986 bool IsInEffect() const
1988 return (GetAdjustedTime() < nExpiration);
1991 bool Cancels(const CAlert& alert) const
1994 return false; // this was a no-op before 31403
1995 return (alert.nID <= nCancel || setCancel.count(alert.nID));
1998 bool AppliesTo(int nVersion, std::string strSubVerIn) const
2000 return (IsInEffect() &&
2001 nMinVer <= nVersion && nVersion <= nMaxVer &&
2002 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
2005 bool AppliesToMe() const
2007 return AppliesTo(VERSION, ::pszSubVer);
2010 bool RelayTo(CNode* pnode) const
2014 // returns true if wasn't already contained in the set
2015 if (pnode->setKnown.insert(GetHash()).second)
2017 if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
2019 GetAdjustedTime() < nRelayUntil)
2021 pnode->PushMessage("alert", *this);
2028 bool CheckSignature()
2031 if (!key.SetPubKey(ParseHex("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284")))
2032 return error("CAlert::CheckSignature() : SetPubKey failed");
2033 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
2034 return error("CAlert::CheckSignature() : verify signature failed");
2036 // Now unserialize the data
2037 CDataStream sMsg(vchMsg);
2038 sMsg >> *(CUnsignedAlert*)this;
2042 bool ProcessAlert();
2054 extern std::map<uint256, CTransaction> mapTransactions;
2055 extern std::map<uint256, CWalletTx> mapWallet;
2056 extern std::vector<uint256> vWalletUpdated;
2057 extern CCriticalSection cs_mapWallet;
2058 extern std::map<std::vector<unsigned char>, CPrivKey> mapKeys;
2059 extern std::map<uint160, std::vector<unsigned char> > mapPubKeys;
2060 extern CCriticalSection cs_mapKeys;
2061 extern CKey keyUser;