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 MIN_RELAY_TX_FEE = 10000;
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;
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, bool fForRelay=false) const
604 // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
605 int64 nBaseFee = fForRelay ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
607 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);
608 unsigned int nNewBlockSize = nBlockSize + nBytes;
609 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
615 // Transactions under 10K are free
616 // (about 4500bc if made of 50bc inputs)
622 // Free transaction area
623 if (nNewBlockSize < 27000)
628 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
629 if (nMinFee < nBaseFee)
630 BOOST_FOREACH(const CTxOut& txout, vout)
631 if (txout.nValue < CENT)
634 // Raise the price as the block approaches full
635 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
637 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
639 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
642 if (!MoneyRange(nMinFee))
648 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
650 CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");
652 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
655 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
656 return error("CTransaction::ReadFromDisk() : fseek failed");
659 // Return file pointer
662 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
663 return error("CTransaction::ReadFromDisk() : second fseek failed");
664 *pfileRet = filein.release();
669 friend bool operator==(const CTransaction& a, const CTransaction& b)
671 return (a.nVersion == b.nVersion &&
674 a.nLockTime == b.nLockTime);
677 friend bool operator!=(const CTransaction& a, const CTransaction& b)
683 std::string ToString() const
686 str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
687 GetHash().ToString().substr(0,10).c_str(),
692 for (int i = 0; i < vin.size(); i++)
693 str += " " + vin[i].ToString() + "\n";
694 for (int i = 0; i < vout.size(); i++)
695 str += " " + vout[i].ToString() + "\n";
701 printf("%s", ToString().c_str());
705 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
706 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
707 bool ReadFromDisk(COutPoint prevout);
708 bool DisconnectInputs(CTxDB& txdb);
709 bool ConnectInputs(CTxDB& txdb, std::map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
710 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee=0);
711 bool ClientConnectInputs();
712 bool CheckTransaction() const;
713 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
714 bool AcceptToMemoryPool(bool fCheckInputs=true, bool* pfMissingInputs=NULL)
717 return AcceptToMemoryPool(txdb, fCheckInputs, pfMissingInputs);
720 bool AddToMemoryPoolUnchecked();
722 bool RemoveFromMemoryPool();
730 // A transaction with a merkle branch linking it to the block chain
732 class CMerkleTx : public CTransaction
736 std::vector<uint256> vMerkleBranch;
740 mutable char fMerkleVerified;
748 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
757 fMerkleVerified = false;
763 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
764 nVersion = this->nVersion;
765 READWRITE(hashBlock);
766 READWRITE(vMerkleBranch);
771 int SetMerkleBranch(const CBlock* pblock=NULL);
772 int GetDepthInMainChain(int& nHeightRet) const;
773 int GetDepthInMainChain() const { int nHeight; return GetDepthInMainChain(nHeight); }
774 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
775 int GetBlocksToMaturity() const;
776 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
777 bool AcceptToMemoryPool() { CTxDB txdb("r"); return AcceptToMemoryPool(txdb); }
784 // A transaction with a bunch of additional info that only the owner cares
785 // about. It includes any unrecorded transactions needed to link it back
786 // to the block chain.
788 class CWalletTx : public CMerkleTx
791 std::vector<CMerkleTx> vtxPrev;
792 std::map<std::string, std::string> mapValue;
793 std::vector<std::pair<std::string, std::string> > vOrderForm;
794 unsigned int fTimeReceivedIsTxTime;
795 unsigned int nTimeReceived; // time received by this node
797 std::string strFromAccount;
798 std::vector<char> vfSpent;
801 mutable char fDebitCached;
802 mutable char fCreditCached;
803 mutable char fAvailableCreditCached;
804 mutable char fChangeCached;
805 mutable int64 nDebitCached;
806 mutable int64 nCreditCached;
807 mutable int64 nAvailableCreditCached;
808 mutable int64 nChangeCached;
810 // memory only UI hints
811 mutable unsigned int nTimeDisplayed;
812 mutable int nLinesDisplayed;
813 mutable char fConfirmedDisplayed;
821 CWalletTx(const CMerkleTx& txIn) : CMerkleTx(txIn)
826 CWalletTx(const CTransaction& txIn) : CMerkleTx(txIn)
836 fTimeReceivedIsTxTime = false;
839 strFromAccount.clear();
841 fDebitCached = false;
842 fCreditCached = false;
843 fAvailableCreditCached = false;
844 fChangeCached = false;
847 nAvailableCreditCached = 0;
851 fConfirmedDisplayed = false;
856 CWalletTx* pthis = const_cast<CWalletTx*>(this);
863 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
866 BOOST_FOREACH(char f, vfSpent)
868 str += (f ? '1' : '0');
872 pthis->mapValue["spent"] = str;
875 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
878 READWRITE(vOrderForm);
879 READWRITE(fTimeReceivedIsTxTime);
880 READWRITE(nTimeReceived);
886 pthis->strFromAccount = pthis->mapValue["fromaccount"];
888 if (mapValue.count("spent"))
889 BOOST_FOREACH(char c, pthis->mapValue["spent"])
890 pthis->vfSpent.push_back(c != '0');
892 pthis->vfSpent.assign(vout.size(), fSpent);
895 pthis->mapValue.erase("fromaccount");
896 pthis->mapValue.erase("version");
897 pthis->mapValue.erase("spent");
900 // marks certain txout's as spent
901 // returns true if any update took place
902 bool UpdateSpent(const std::vector<char>& vfNewSpent)
904 bool fReturn = false;
905 for (int i=0; i < vfNewSpent.size(); i++)
907 if (i == vfSpent.size())
910 if (vfNewSpent[i] && !vfSpent[i])
914 fAvailableCreditCached = false;
922 fCreditCached = false;
923 fAvailableCreditCached = false;
924 fDebitCached = false;
925 fChangeCached = false;
928 void MarkSpent(unsigned int nOut)
930 if (nOut >= vout.size())
931 throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
932 vfSpent.resize(vout.size());
935 vfSpent[nOut] = true;
936 fAvailableCreditCached = false;
940 bool IsSpent(unsigned int nOut) const
942 if (nOut >= vout.size())
943 throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
944 if (nOut >= vfSpent.size())
946 return (!!vfSpent[nOut]);
949 int64 GetDebit() const
955 nDebitCached = CTransaction::GetDebit();
960 int64 GetCredit(bool fUseCache=true) const
962 // Must wait until coinbase is safely deep enough in the chain before valuing it
963 if (IsCoinBase() && GetBlocksToMaturity() > 0)
966 // GetBalance can assume transactions in mapWallet won't change
967 if (fUseCache && fCreditCached)
968 return nCreditCached;
969 nCreditCached = CTransaction::GetCredit();
970 fCreditCached = true;
971 return nCreditCached;
974 int64 GetAvailableCredit(bool fUseCache=true) const
976 // Must wait until coinbase is safely deep enough in the chain before valuing it
977 if (IsCoinBase() && GetBlocksToMaturity() > 0)
980 if (fUseCache && fAvailableCreditCached)
981 return nAvailableCreditCached;
984 for (int i = 0; i < vout.size(); i++)
988 const CTxOut &txout = vout[i];
989 nCredit += txout.GetCredit();
990 if (!MoneyRange(nCredit))
991 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
995 nAvailableCreditCached = nCredit;
996 fAvailableCreditCached = true;
1001 int64 GetChange() const
1004 return nChangeCached;
1005 nChangeCached = CTransaction::GetChange();
1006 fChangeCached = true;
1007 return nChangeCached;
1010 void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<std::string /* address */, int64> >& listReceived,
1011 std::list<std::pair<std::string /* address */, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
1013 void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,
1014 int64& nSent, int64& nFee) const;
1016 bool IsFromMe() const
1018 return (GetDebit() > 0);
1021 bool IsConfirmed() const
1023 // Quick answer in most cases
1026 if (GetDepthInMainChain() >= 1)
1028 if (!IsFromMe()) // using wtx's cached debit
1031 // If no confirmations but it's from us, we can still
1032 // consider it confirmed if all dependencies are confirmed
1033 std::map<uint256, const CMerkleTx*> mapPrev;
1034 std::vector<const CMerkleTx*> vWorkQueue;
1035 vWorkQueue.reserve(vtxPrev.size()+1);
1036 vWorkQueue.push_back(this);
1037 for (int i = 0; i < vWorkQueue.size(); i++)
1039 const CMerkleTx* ptx = vWorkQueue[i];
1041 if (!ptx->IsFinal())
1043 if (ptx->GetDepthInMainChain() >= 1)
1045 if (!ptx->IsFromMe())
1048 if (mapPrev.empty())
1049 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
1050 mapPrev[tx.GetHash()] = &tx;
1052 BOOST_FOREACH(const CTxIn& txin, ptx->vin)
1054 if (!mapPrev.count(txin.prevout.hash))
1056 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
1064 return CWalletDB().WriteTx(GetHash(), *this);
1068 int64 GetTxTime() const;
1069 int GetRequestCount() const;
1071 void AddSupportingTransactions(CTxDB& txdb);
1073 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
1074 bool AcceptWalletTransaction() { CTxDB txdb("r"); return AcceptWalletTransaction(txdb); }
1076 void RelayWalletTransaction(CTxDB& txdb);
1077 void RelayWalletTransaction() { CTxDB txdb("r"); RelayWalletTransaction(txdb); }
1084 // A txdb record that contains the disk location of a transaction and the
1085 // locations of transactions that spend its outputs. vSpent is really only
1086 // used as a flag, but having the location is very helpful for debugging.
1092 std::vector<CDiskTxPos> vSpent;
1099 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
1102 vSpent.resize(nOutputs);
1107 if (!(nType & SER_GETHASH))
1108 READWRITE(nVersion);
1121 return pos.IsNull();
1124 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
1126 return (a.pos == b.pos &&
1127 a.vSpent == b.vSpent);
1130 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
1134 int GetDepthInMainChain() const;
1142 // Nodes collect new transactions into a block, hash them into a hash tree,
1143 // and scan through nonce values to make the block's hash satisfy proof-of-work
1144 // requirements. When they solve the proof-of-work, they broadcast the block
1145 // to everyone and the block is added to the block chain. The first transaction
1146 // in the block is a special one that creates a new coin owned by the creator
1149 // Blocks are appended to blk0001.dat files on disk. Their location on disk
1150 // is indexed by CBlockIndex objects in memory.
1157 uint256 hashPrevBlock;
1158 uint256 hashMerkleRoot;
1161 unsigned int nNonce;
1164 std::vector<CTransaction> vtx;
1167 mutable std::vector<uint256> vMerkleTree;
1177 READWRITE(this->nVersion);
1178 nVersion = this->nVersion;
1179 READWRITE(hashPrevBlock);
1180 READWRITE(hashMerkleRoot);
1185 // ConnectBlock depends on vtx being last so it can calculate offset
1186 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
1189 const_cast<CBlock*>(this)->vtx.clear();
1201 vMerkleTree.clear();
1206 return (nBits == 0);
1209 uint256 GetHash() const
1211 return Hash(BEGIN(nVersion), END(nNonce));
1214 int64 GetBlockTime() const
1216 return (int64)nTime;
1219 int GetSigOpCount() const
1222 BOOST_FOREACH(const CTransaction& tx, vtx)
1223 n += tx.GetSigOpCount();
1228 uint256 BuildMerkleTree() const
1230 vMerkleTree.clear();
1231 BOOST_FOREACH(const CTransaction& tx, vtx)
1232 vMerkleTree.push_back(tx.GetHash());
1234 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1236 for (int i = 0; i < nSize; i += 2)
1238 int i2 = std::min(i+1, nSize-1);
1239 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
1240 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
1244 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
1247 std::vector<uint256> GetMerkleBranch(int nIndex) const
1249 if (vMerkleTree.empty())
1251 std::vector<uint256> vMerkleBranch;
1253 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1255 int i = std::min(nIndex^1, nSize-1);
1256 vMerkleBranch.push_back(vMerkleTree[j+i]);
1260 return vMerkleBranch;
1263 static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
1267 BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
1270 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
1272 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
1279 bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
1281 // Open history file to append
1282 CAutoFile fileout = AppendBlockFile(nFileRet);
1284 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
1286 // Write index header
1287 unsigned int nSize = fileout.GetSerializeSize(*this);
1288 fileout << FLATDATA(pchMessageStart) << nSize;
1291 nBlockPosRet = ftell(fileout);
1292 if (nBlockPosRet == -1)
1293 return error("CBlock::WriteToDisk() : ftell failed");
1296 // Flush stdio buffers and commit to disk before returning
1298 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
1301 _commit(_fileno(fileout));
1303 fsync(fileno(fileout));
1310 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
1314 // Open history file to read
1315 CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");
1317 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1318 if (!fReadTransactions)
1319 filein.nType |= SER_BLOCKHEADERONLY;
1325 if (!CheckProofOfWork(GetHash(), nBits))
1326 return error("CBlock::ReadFromDisk() : errors in block header");
1335 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
1336 GetHash().ToString().substr(0,20).c_str(),
1338 hashPrevBlock.ToString().substr(0,20).c_str(),
1339 hashMerkleRoot.ToString().substr(0,10).c_str(),
1340 nTime, nBits, nNonce,
1342 for (int i = 0; i < vtx.size(); i++)
1347 printf(" vMerkleTree: ");
1348 for (int i = 0; i < vMerkleTree.size(); i++)
1349 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1354 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1355 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1356 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1357 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1358 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1359 bool CheckBlock() const;
1369 // The block chain is a tree shaped structure starting with the
1370 // genesis block at the root, with each block potentially having multiple
1371 // candidates to be the next block. pprev and pnext link a path through the
1372 // main/longest chain. A blockindex may have multiple pprev pointing back
1373 // to it, but pnext will only point forward to the longest branch, or will
1374 // be null if the block is not part of the longest chain.
1379 const uint256* phashBlock;
1383 unsigned int nBlockPos;
1385 CBigNum bnChainWork;
1389 uint256 hashMerkleRoot;
1392 unsigned int nNonce;
1412 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1418 nBlockPos = nBlockPosIn;
1422 nVersion = block.nVersion;
1423 hashMerkleRoot = block.hashMerkleRoot;
1424 nTime = block.nTime;
1425 nBits = block.nBits;
1426 nNonce = block.nNonce;
1429 CBlock GetBlockHeader() const
1432 block.nVersion = nVersion;
1434 block.hashPrevBlock = pprev->GetBlockHash();
1435 block.hashMerkleRoot = hashMerkleRoot;
1436 block.nTime = nTime;
1437 block.nBits = nBits;
1438 block.nNonce = nNonce;
1442 uint256 GetBlockHash() const
1447 int64 GetBlockTime() const
1449 return (int64)nTime;
1452 CBigNum GetBlockWork() const
1455 bnTarget.SetCompact(nBits);
1458 return (CBigNum(1)<<256) / (bnTarget+1);
1461 bool IsInMainChain() const
1463 return (pnext || this == pindexBest);
1466 bool CheckIndex() const
1468 return CheckProofOfWork(GetBlockHash(), nBits);
1471 bool EraseBlockFromDisk()
1473 // Open history file
1474 CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");
1478 // Overwrite with empty null block
1486 enum { nMedianTimeSpan=11 };
1488 int64 GetMedianTimePast() const
1490 int64 pmedian[nMedianTimeSpan];
1491 int64* pbegin = &pmedian[nMedianTimeSpan];
1492 int64* pend = &pmedian[nMedianTimeSpan];
1494 const CBlockIndex* pindex = this;
1495 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1496 *(--pbegin) = pindex->GetBlockTime();
1498 std::sort(pbegin, pend);
1499 return pbegin[(pend - pbegin)/2];
1502 int64 GetMedianTime() const
1504 const CBlockIndex* pindex = this;
1505 for (int i = 0; i < nMedianTimeSpan/2; i++)
1508 return GetBlockTime();
1509 pindex = pindex->pnext;
1511 return pindex->GetMedianTimePast();
1516 std::string ToString() const
1518 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
1519 pprev, pnext, nFile, nBlockPos, nHeight,
1520 hashMerkleRoot.ToString().substr(0,10).c_str(),
1521 GetBlockHash().ToString().substr(0,20).c_str());
1526 printf("%s\n", ToString().c_str());
1533 // Used to marshal pointers into hashes for db storage.
1535 class CDiskBlockIndex : public CBlockIndex
1547 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1549 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1550 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1555 if (!(nType & SER_GETHASH))
1556 READWRITE(nVersion);
1558 READWRITE(hashNext);
1560 READWRITE(nBlockPos);
1564 READWRITE(this->nVersion);
1565 READWRITE(hashPrev);
1566 READWRITE(hashMerkleRoot);
1572 uint256 GetBlockHash() const
1575 block.nVersion = nVersion;
1576 block.hashPrevBlock = hashPrev;
1577 block.hashMerkleRoot = hashMerkleRoot;
1578 block.nTime = nTime;
1579 block.nBits = nBits;
1580 block.nNonce = nNonce;
1581 return block.GetHash();
1585 std::string ToString() const
1587 std::string str = "CDiskBlockIndex(";
1588 str += CBlockIndex::ToString();
1589 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1590 GetBlockHash().ToString().c_str(),
1591 hashPrev.ToString().substr(0,20).c_str(),
1592 hashNext.ToString().substr(0,20).c_str());
1598 printf("%s\n", ToString().c_str());
1610 // Describes a place in the block chain to another node such that if the
1611 // other node doesn't have the same branch, it can find a recent common trunk.
1612 // The further back it is, the further before the fork it may be.
1617 std::vector<uint256> vHave;
1624 explicit CBlockLocator(const CBlockIndex* pindex)
1629 explicit CBlockLocator(uint256 hashBlock)
1631 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1632 if (mi != mapBlockIndex.end())
1638 if (!(nType & SER_GETHASH))
1639 READWRITE(nVersion);
1650 return vHave.empty();
1653 void Set(const CBlockIndex* pindex)
1659 vHave.push_back(pindex->GetBlockHash());
1661 // Exponentially larger steps back
1662 for (int i = 0; pindex && i < nStep; i++)
1663 pindex = pindex->pprev;
1664 if (vHave.size() > 10)
1667 vHave.push_back(hashGenesisBlock);
1670 int GetDistanceBack()
1672 // Retrace how far back it was in the sender's branch
1675 BOOST_FOREACH(const uint256& hash, vHave)
1677 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1678 if (mi != mapBlockIndex.end())
1680 CBlockIndex* pindex = (*mi).second;
1681 if (pindex->IsInMainChain())
1691 CBlockIndex* GetBlockIndex()
1693 // Find the first block the caller has in the main chain
1694 BOOST_FOREACH(const uint256& hash, vHave)
1696 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1697 if (mi != mapBlockIndex.end())
1699 CBlockIndex* pindex = (*mi).second;
1700 if (pindex->IsInMainChain())
1704 return pindexGenesisBlock;
1707 uint256 GetBlockHash()
1709 // Find the first block the caller has in the main chain
1710 BOOST_FOREACH(const uint256& hash, vHave)
1712 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1713 if (mi != mapBlockIndex.end())
1715 CBlockIndex* pindex = (*mi).second;
1716 if (pindex->IsInMainChain())
1720 return hashGenesisBlock;
1725 CBlockIndex* pindex = GetBlockIndex();
1728 return pindex->nHeight;
1738 // Private key that includes an expiration date in case it never gets used.
1743 CPrivKey vchPrivKey;
1746 std::string strComment;
1747 //// todo: add something to note what created it (user, getnewaddress, change)
1748 //// maybe should have a map<string, string> property map
1750 CWalletKey(int64 nExpires=0)
1752 nTimeCreated = (nExpires ? GetTime() : 0);
1753 nTimeExpires = nExpires;
1758 if (!(nType & SER_GETHASH))
1759 READWRITE(nVersion);
1760 READWRITE(vchPrivKey);
1761 READWRITE(nTimeCreated);
1762 READWRITE(nTimeExpires);
1763 READWRITE(strComment);
1773 // Account information.
1774 // Stored in wallet with key "acc"+string account name
1779 std::vector<unsigned char> vchPubKey;
1793 if (!(nType & SER_GETHASH))
1794 READWRITE(nVersion);
1795 READWRITE(vchPubKey);
1802 // Internal transfers.
1803 // Database key is acentry<account><counter>
1805 class CAccountingEntry
1808 std::string strAccount;
1811 std::string strOtherAccount;
1812 std::string strComment;
1824 strOtherAccount.clear();
1830 if (!(nType & SER_GETHASH))
1831 READWRITE(nVersion);
1832 // Note: strAccount is serialized as part of the key, not here.
1833 READWRITE(nCreditDebit);
1835 READWRITE(strOtherAccount);
1836 READWRITE(strComment);
1849 // Alerts are for notifying old versions if they become too obsolete and
1850 // need to upgrade. The message is displayed in the status bar.
1851 // Alert messages are broadcast as a vector of signed data. Unserializing may
1852 // not read the entire buffer if the alert is for a newer version, but older
1853 // versions can still relay the original data.
1855 class CUnsignedAlert
1859 int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
1863 std::set<int> setCancel;
1864 int nMinVer; // lowest version inclusive
1865 int nMaxVer; // highest version inclusive
1866 std::set<std::string> setSubVer; // empty matches all
1870 std::string strComment;
1871 std::string strStatusBar;
1872 std::string strReserved;
1876 READWRITE(this->nVersion);
1877 nVersion = this->nVersion;
1878 READWRITE(nRelayUntil);
1879 READWRITE(nExpiration);
1882 READWRITE(setCancel);
1885 READWRITE(setSubVer);
1886 READWRITE(nPriority);
1888 READWRITE(strComment);
1889 READWRITE(strStatusBar);
1890 READWRITE(strReserved);
1907 strStatusBar.clear();
1908 strReserved.clear();
1911 std::string ToString() const
1913 std::string strSetCancel;
1914 BOOST_FOREACH(int n, setCancel)
1915 strSetCancel += strprintf("%d ", n);
1916 std::string strSetSubVer;
1917 BOOST_FOREACH(std::string str, setSubVer)
1918 strSetSubVer += "\"" + str + "\" ";
1922 " nRelayUntil = %"PRI64d"\n"
1923 " nExpiration = %"PRI64d"\n"
1931 " strComment = \"%s\"\n"
1932 " strStatusBar = \"%s\"\n"
1939 strSetCancel.c_str(),
1942 strSetSubVer.c_str(),
1945 strStatusBar.c_str());
1950 printf("%s", ToString().c_str());
1954 class CAlert : public CUnsignedAlert
1957 std::vector<unsigned char> vchMsg;
1958 std::vector<unsigned char> vchSig;
1973 CUnsignedAlert::SetNull();
1980 return (nExpiration == 0);
1983 uint256 GetHash() const
1985 return SerializeHash(*this);
1988 bool IsInEffect() const
1990 return (GetAdjustedTime() < nExpiration);
1993 bool Cancels(const CAlert& alert) const
1996 return false; // this was a no-op before 31403
1997 return (alert.nID <= nCancel || setCancel.count(alert.nID));
2000 bool AppliesTo(int nVersion, std::string strSubVerIn) const
2002 return (IsInEffect() &&
2003 nMinVer <= nVersion && nVersion <= nMaxVer &&
2004 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
2007 bool AppliesToMe() const
2009 return AppliesTo(VERSION, ::pszSubVer);
2012 bool RelayTo(CNode* pnode) const
2016 // returns true if wasn't already contained in the set
2017 if (pnode->setKnown.insert(GetHash()).second)
2019 if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
2021 GetAdjustedTime() < nRelayUntil)
2023 pnode->PushMessage("alert", *this);
2030 bool CheckSignature()
2033 if (!key.SetPubKey(ParseHex("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284")))
2034 return error("CAlert::CheckSignature() : SetPubKey failed");
2035 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
2036 return error("CAlert::CheckSignature() : verify signature failed");
2038 // Now unserialize the data
2039 CDataStream sMsg(vchMsg);
2040 sMsg >> *(CUnsignedAlert*)this;
2044 bool ProcessAlert();
2056 extern std::map<uint256, CTransaction> mapTransactions;
2057 extern std::map<uint256, CWalletTx> mapWallet;
2058 extern std::vector<uint256> vWalletUpdated;
2059 extern CCriticalSection cs_mapWallet;
2060 extern std::map<std::vector<unsigned char>, CPrivKey> mapKeys;
2061 extern std::map<uint160, std::vector<unsigned char> > mapPubKeys;
2062 extern CCriticalSection cs_mapKeys;
2063 extern CKey keyUser;