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.
17 static const unsigned int MAX_BLOCK_SIZE = 1000000;
18 static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/2;
19 static const int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
20 static const int64 COIN = 100000000;
21 static const int64 CENT = 1000000;
22 static const int64 MAX_MONEY = 21000000 * COIN;
23 inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
24 static const int COINBASE_MATURITY = 100;
26 static const int fHaveUPnP = true;
28 static const int fHaveUPnP = false;
36 extern CCriticalSection cs_main;
37 extern map<uint256, CBlockIndex*> mapBlockIndex;
38 extern uint256 hashGenesisBlock;
39 extern CBigNum bnProofOfWorkLimit;
40 extern CBlockIndex* pindexGenesisBlock;
41 extern int nBestHeight;
42 extern CBigNum bnBestChainWork;
43 extern CBigNum bnBestInvalidWork;
44 extern uint256 hashBestChain;
45 extern CBlockIndex* pindexBest;
46 extern unsigned int nTransactionsUpdated;
47 extern map<uint256, int> mapRequestCount;
48 extern CCriticalSection cs_mapRequestCount;
49 extern map<string, string> mapAddressBook;
50 extern CCriticalSection cs_mapAddressBook;
51 extern vector<unsigned char> vchDefaultKey;
52 extern double dHashesPerSec;
53 extern int64 nHPSTimerStart;
56 extern int fGenerateBitcoins;
57 extern int64 nTransactionFee;
58 extern CAddress addrIncoming;
59 extern int fLimitProcessors;
60 extern int nLimitProcessors;
61 extern int fMinimizeToTray;
62 extern int fMinimizeOnClose;
71 bool CheckDiskSpace(uint64 nAdditionalBytes=0);
72 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
73 FILE* AppendBlockFile(unsigned int& nFileRet);
74 bool AddKey(const CKey& key);
75 vector<unsigned char> GenerateNewKey();
76 bool AddToWallet(const CWalletTx& wtxIn);
77 void WalletUpdateSpent(const COutPoint& prevout);
78 int ScanForWalletTransactions(CBlockIndex* pindexStart);
79 void ReacceptWalletTransactions();
80 bool LoadBlockIndex(bool fAllowNew=true);
81 void PrintBlockTree();
82 bool ProcessMessages(CNode* pfrom);
83 bool ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv);
84 bool SendMessages(CNode* pto, bool fSendTrickle);
86 bool CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
87 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
88 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
89 bool BroadcastTransaction(CWalletTx& wtxNew);
90 string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
91 string SendMoneyToBitcoinAddress(string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
92 void GenerateBitcoins(bool fGenerate);
93 void ThreadBitcoinMiner(void* parg);
94 CBlock* CreateNewBlock(CReserveKey& reservekey);
95 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce, int64& nPrevTime);
96 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
97 bool CheckWork(CBlock* pblock, CReserveKey& reservekey);
99 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
100 bool IsInitialBlockDownload();
101 string GetWarnings(string strFor);
118 unsigned int nBlockPos;
126 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
129 nBlockPos = nBlockPosIn;
133 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
134 void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
135 bool IsNull() const { return (nFile == -1); }
137 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
139 return (a.nFile == b.nFile &&
140 a.nBlockPos == b.nBlockPos &&
141 a.nTxPos == b.nTxPos);
144 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
149 string ToString() const
152 return strprintf("null");
154 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
159 printf("%s", ToString().c_str());
172 CInPoint() { SetNull(); }
173 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
174 void SetNull() { ptx = NULL; n = -1; }
175 bool IsNull() const { return (ptx == NULL && n == -1); }
187 COutPoint() { SetNull(); }
188 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
189 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
190 void SetNull() { hash = 0; n = -1; }
191 bool IsNull() const { return (hash == 0 && n == -1); }
193 friend bool operator<(const COutPoint& a, const COutPoint& b)
195 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
198 friend bool operator==(const COutPoint& a, const COutPoint& b)
200 return (a.hash == b.hash && a.n == b.n);
203 friend bool operator!=(const COutPoint& a, const COutPoint& b)
208 string ToString() const
210 return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,10).c_str(), n);
215 printf("%s\n", ToString().c_str());
223 // An input of a transaction. It contains the location of the previous
224 // transaction's output that it claims and a signature that matches the
225 // output's public key.
232 unsigned int nSequence;
236 nSequence = UINT_MAX;
239 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
242 scriptSig = scriptSigIn;
243 nSequence = nSequenceIn;
246 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
248 prevout = COutPoint(hashPrevTx, nOut);
249 scriptSig = scriptSigIn;
250 nSequence = nSequenceIn;
256 READWRITE(scriptSig);
257 READWRITE(nSequence);
262 return (nSequence == UINT_MAX);
265 friend bool operator==(const CTxIn& a, const CTxIn& b)
267 return (a.prevout == b.prevout &&
268 a.scriptSig == b.scriptSig &&
269 a.nSequence == b.nSequence);
272 friend bool operator!=(const CTxIn& a, const CTxIn& b)
277 string ToString() const
280 str += strprintf("CTxIn(");
281 str += prevout.ToString();
282 if (prevout.IsNull())
283 str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
285 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
286 if (nSequence != UINT_MAX)
287 str += strprintf(", nSequence=%u", nSequence);
294 printf("%s\n", ToString().c_str());
298 int64 GetDebit() const;
305 // An output of a transaction. It contains the public key that the next input
306 // must be able to sign with to claim it.
312 CScript scriptPubKey;
319 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
322 scriptPubKey = scriptPubKeyIn;
328 READWRITE(scriptPubKey);
334 scriptPubKey.clear();
339 return (nValue == -1);
342 uint256 GetHash() const
344 return SerializeHash(*this);
349 return ::IsMine(scriptPubKey);
352 int64 GetCredit() const
354 if (!MoneyRange(nValue))
355 throw runtime_error("CTxOut::GetCredit() : value out of range");
356 return (IsMine() ? nValue : 0);
359 bool IsChange() const
361 // On a debit transaction, a txout that's mine but isn't in the address book is change
362 vector<unsigned char> vchPubKey;
363 if (ExtractPubKey(scriptPubKey, true, vchPubKey))
364 CRITICAL_BLOCK(cs_mapAddressBook)
365 if (!mapAddressBook.count(PubKeyToAddress(vchPubKey)))
370 int64 GetChange() const
372 if (!MoneyRange(nValue))
373 throw runtime_error("CTxOut::GetChange() : value out of range");
374 return (IsChange() ? nValue : 0);
377 friend bool operator==(const CTxOut& a, const CTxOut& b)
379 return (a.nValue == b.nValue &&
380 a.scriptPubKey == b.scriptPubKey);
383 friend bool operator!=(const CTxOut& a, const CTxOut& b)
388 string ToString() const
390 if (scriptPubKey.size() < 6)
391 return "CTxOut(error)";
392 return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,30).c_str());
397 printf("%s\n", ToString().c_str());
405 // The basic transaction that is broadcasted on the network and contained in
406 // blocks. A transaction can contain multiple inputs and outputs.
414 unsigned int nLockTime;
424 READWRITE(this->nVersion);
425 nVersion = this->nVersion;
428 READWRITE(nLockTime);
441 return (vin.empty() && vout.empty());
444 uint256 GetHash() const
446 return SerializeHash(*this);
449 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
451 // Time based nLockTime implemented in 0.1.6
454 if (nBlockHeight == 0)
455 nBlockHeight = nBestHeight;
457 nBlockTime = GetAdjustedTime();
458 if ((int64)nLockTime < (nLockTime < 500000000 ? (int64)nBlockHeight : nBlockTime))
460 foreach(const CTxIn& txin, vin)
466 bool IsNewerThan(const CTransaction& old) const
468 if (vin.size() != old.vin.size())
470 for (int i = 0; i < vin.size(); i++)
471 if (vin[i].prevout != old.vin[i].prevout)
475 unsigned int nLowest = UINT_MAX;
476 for (int i = 0; i < vin.size(); i++)
478 if (vin[i].nSequence != old.vin[i].nSequence)
480 if (vin[i].nSequence <= nLowest)
483 nLowest = vin[i].nSequence;
485 if (old.vin[i].nSequence < nLowest)
488 nLowest = old.vin[i].nSequence;
495 bool IsCoinBase() const
497 return (vin.size() == 1 && vin[0].prevout.IsNull());
500 int GetSigOpCount() const
503 foreach(const CTxIn& txin, vin)
504 n += txin.scriptSig.GetSigOpCount();
505 foreach(const CTxOut& txout, vout)
506 n += txout.scriptPubKey.GetSigOpCount();
510 bool IsStandard() const
512 foreach(const CTxIn& txin, vin)
513 if (!txin.scriptSig.IsPushOnly())
514 return error("nonstandard txin: %s", txin.scriptSig.ToString().c_str());
515 foreach(const CTxOut& txout, vout)
516 if (!::IsStandard(txout.scriptPubKey))
517 return error("nonstandard txout: %s", txout.scriptPubKey.ToString().c_str());
523 foreach(const CTxOut& txout, vout)
529 bool IsFromMe() const
531 return (GetDebit() > 0);
534 int64 GetDebit() const
537 foreach(const CTxIn& txin, vin)
539 nDebit += txin.GetDebit();
540 if (!MoneyRange(nDebit))
541 throw runtime_error("CTransaction::GetDebit() : value out of range");
546 int64 GetCredit() const
549 foreach(const CTxOut& txout, vout)
551 nCredit += txout.GetCredit();
552 if (!MoneyRange(nCredit))
553 throw runtime_error("CTransaction::GetCredit() : value out of range");
558 int64 GetChange() const
563 foreach(const CTxOut& txout, vout)
565 nChange += txout.GetChange();
566 if (!MoneyRange(nChange))
567 throw runtime_error("CTransaction::GetChange() : value out of range");
572 int64 GetValueOut() const
575 foreach(const CTxOut& txout, vout)
577 nValueOut += txout.nValue;
578 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
579 throw runtime_error("CTransaction::GetValueOut() : value out of range");
584 static bool AllowFree(double dPriority)
586 // Large (in bytes) low-priority (new, small-coin) transactions
588 return dPriority > COIN * 144 / 250;
591 int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=true) const
593 // Base fee is 1 cent per kilobyte
594 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);
595 unsigned int nNewBlockSize = nBlockSize + nBytes;
596 int64 nMinFee = (1 + (int64)nBytes / 1000) * CENT;
602 // Transactions under 10K are free
603 // (about 4500bc if made of 50bc inputs)
609 // Free transaction area
610 if (nNewBlockSize < 27000)
615 // To limit dust spam, require a 0.01 fee if any output is less than 0.01
617 foreach(const CTxOut& txout, vout)
618 if (txout.nValue < CENT)
621 // Raise the price as the block approaches full
622 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
624 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
626 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
629 if (!MoneyRange(nMinFee))
635 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
637 CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");
639 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
642 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
643 return error("CTransaction::ReadFromDisk() : fseek failed");
646 // Return file pointer
649 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
650 return error("CTransaction::ReadFromDisk() : second fseek failed");
651 *pfileRet = filein.release();
656 friend bool operator==(const CTransaction& a, const CTransaction& b)
658 return (a.nVersion == b.nVersion &&
661 a.nLockTime == b.nLockTime);
664 friend bool operator!=(const CTransaction& a, const CTransaction& b)
670 string ToString() const
673 str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
674 GetHash().ToString().substr(0,10).c_str(),
679 for (int i = 0; i < vin.size(); i++)
680 str += " " + vin[i].ToString() + "\n";
681 for (int i = 0; i < vout.size(); i++)
682 str += " " + vout[i].ToString() + "\n";
688 printf("%s", ToString().c_str());
692 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
693 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
694 bool ReadFromDisk(COutPoint prevout);
695 bool DisconnectInputs(CTxDB& txdb);
696 bool ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
697 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee=0);
698 bool ClientConnectInputs();
699 bool CheckTransaction() const;
700 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
701 bool AcceptToMemoryPool(bool fCheckInputs=true, bool* pfMissingInputs=NULL)
704 return AcceptToMemoryPool(txdb, fCheckInputs, pfMissingInputs);
707 bool AddToMemoryPoolUnchecked();
709 bool RemoveFromMemoryPool();
717 // A transaction with a merkle branch linking it to the block chain
719 class CMerkleTx : public CTransaction
723 vector<uint256> vMerkleBranch;
727 mutable char fMerkleVerified;
735 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
744 fMerkleVerified = false;
750 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
751 nVersion = this->nVersion;
752 READWRITE(hashBlock);
753 READWRITE(vMerkleBranch);
758 int SetMerkleBranch(const CBlock* pblock=NULL);
759 int GetDepthInMainChain(int& nHeightRet) const;
760 int GetDepthInMainChain() const { int nHeight; return GetDepthInMainChain(nHeight); }
761 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
762 int GetBlocksToMaturity() const;
763 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
764 bool AcceptToMemoryPool() { CTxDB txdb("r"); return AcceptToMemoryPool(txdb); }
771 // A transaction with a bunch of additional info that only the owner cares
772 // about. It includes any unrecorded transactions needed to link it back
773 // to the block chain.
775 class CWalletTx : public CMerkleTx
778 vector<CMerkleTx> vtxPrev;
779 map<string, string> mapValue;
780 vector<pair<string, string> > vOrderForm;
781 unsigned int fTimeReceivedIsTxTime;
782 unsigned int nTimeReceived; // time received by this node
784 string strFromAccount;
785 vector<char> vfSpent;
788 mutable char fDebitCached;
789 mutable char fCreditCached;
790 mutable char fAvailableCreditCached;
791 mutable char fChangeCached;
792 mutable int64 nDebitCached;
793 mutable int64 nCreditCached;
794 mutable int64 nAvailableCreditCached;
795 mutable int64 nChangeCached;
797 // memory only UI hints
798 mutable unsigned int nTimeDisplayed;
799 mutable int nLinesDisplayed;
800 mutable char fConfirmedDisplayed;
808 CWalletTx(const CMerkleTx& txIn) : CMerkleTx(txIn)
813 CWalletTx(const CTransaction& txIn) : CMerkleTx(txIn)
823 fTimeReceivedIsTxTime = false;
826 strFromAccount.clear();
828 fDebitCached = false;
829 fCreditCached = false;
830 fAvailableCreditCached = false;
831 fChangeCached = false;
834 nAvailableCreditCached = 0;
838 fConfirmedDisplayed = false;
843 CWalletTx* pthis = const_cast<CWalletTx*>(this);
850 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
853 foreach(char f, vfSpent)
855 str += (f ? '1' : '0');
859 pthis->mapValue["spent"] = str;
862 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
865 READWRITE(vOrderForm);
866 READWRITE(fTimeReceivedIsTxTime);
867 READWRITE(nTimeReceived);
873 pthis->strFromAccount = pthis->mapValue["fromaccount"];
875 if (mapValue.count("spent"))
876 foreach(char c, pthis->mapValue["spent"])
877 pthis->vfSpent.push_back(c != '0');
879 pthis->vfSpent.assign(vout.size(), fSpent);
882 pthis->mapValue.erase("fromaccount");
883 pthis->mapValue.erase("version");
884 pthis->mapValue.erase("spent");
887 // marks certain txout's as spent
888 // returns true if any update took place
889 bool UpdateSpent(const vector<char>& vfNewSpent)
891 bool fReturn = false;
892 for (int i=0; i < vfNewSpent.size(); i++)
894 if (i == vfSpent.size())
897 if (vfNewSpent[i] && !vfSpent[i])
901 fAvailableCreditCached = false;
909 fCreditCached = false;
910 fAvailableCreditCached = false;
911 fDebitCached = false;
912 fChangeCached = false;
915 void MarkSpent(unsigned int nOut)
917 if (nOut >= vout.size())
918 throw runtime_error("CWalletTx::MarkSpent() : nOut out of range");
919 vfSpent.resize(vout.size());
922 vfSpent[nOut] = true;
923 fAvailableCreditCached = false;
927 bool IsSpent(unsigned int nOut) const
929 if (nOut >= vout.size())
930 throw runtime_error("CWalletTx::IsSpent() : nOut out of range");
931 if (nOut >= vfSpent.size())
933 return (!!vfSpent[nOut]);
936 int64 GetDebit() const
942 nDebitCached = CTransaction::GetDebit();
947 int64 GetCredit(bool fUseCache=true) const
949 // Must wait until coinbase is safely deep enough in the chain before valuing it
950 if (IsCoinBase() && GetBlocksToMaturity() > 0)
953 // GetBalance can assume transactions in mapWallet won't change
954 if (fUseCache && fCreditCached)
955 return nCreditCached;
956 nCreditCached = CTransaction::GetCredit();
957 fCreditCached = true;
958 return nCreditCached;
961 int64 GetAvailableCredit(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 if (fUseCache && fAvailableCreditCached)
968 return nAvailableCreditCached;
971 for (int i = 0; i < vout.size(); i++)
975 const CTxOut &txout = vout[i];
976 nCredit += txout.GetCredit();
977 if (!MoneyRange(nCredit))
978 throw runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
982 nAvailableCreditCached = nCredit;
983 fAvailableCreditCached = true;
988 int64 GetChange() const
991 return nChangeCached;
992 nChangeCached = CTransaction::GetChange();
993 fChangeCached = true;
994 return nChangeCached;
997 void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, list<pair<string /* address */, int64> >& listReceived,
998 list<pair<string /* address */, int64> >& listSent, int64& nFee, string& strSentAccount) const;
1000 void GetAccountAmounts(const string& strAccount, int64& nGenerated, int64& nReceived,
1001 int64& nSent, int64& nFee) const;
1003 bool IsFromMe() const
1005 return (GetDebit() > 0);
1008 bool IsConfirmed() const
1010 // Quick answer in most cases
1013 if (GetDepthInMainChain() >= 1)
1015 if (!IsFromMe()) // using wtx's cached debit
1018 // If no confirmations but it's from us, we can still
1019 // consider it confirmed if all dependencies are confirmed
1020 map<uint256, const CMerkleTx*> mapPrev;
1021 vector<const CMerkleTx*> vWorkQueue;
1022 vWorkQueue.reserve(vtxPrev.size()+1);
1023 vWorkQueue.push_back(this);
1024 for (int i = 0; i < vWorkQueue.size(); i++)
1026 const CMerkleTx* ptx = vWorkQueue[i];
1028 if (!ptx->IsFinal())
1030 if (ptx->GetDepthInMainChain() >= 1)
1032 if (!ptx->IsFromMe())
1035 if (mapPrev.empty())
1036 foreach(const CMerkleTx& tx, vtxPrev)
1037 mapPrev[tx.GetHash()] = &tx;
1039 foreach(const CTxIn& txin, ptx->vin)
1041 if (!mapPrev.count(txin.prevout.hash))
1043 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
1051 return CWalletDB().WriteTx(GetHash(), *this);
1055 int64 GetTxTime() const;
1056 int GetRequestCount() const;
1058 void AddSupportingTransactions(CTxDB& txdb);
1060 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
1061 bool AcceptWalletTransaction() { CTxDB txdb("r"); return AcceptWalletTransaction(txdb); }
1063 void RelayWalletTransaction(CTxDB& txdb);
1064 void RelayWalletTransaction() { CTxDB txdb("r"); RelayWalletTransaction(txdb); }
1071 // A txdb record that contains the disk location of a transaction and the
1072 // locations of transactions that spend its outputs. vSpent is really only
1073 // used as a flag, but having the location is very helpful for debugging.
1079 vector<CDiskTxPos> vSpent;
1086 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
1089 vSpent.resize(nOutputs);
1094 if (!(nType & SER_GETHASH))
1095 READWRITE(nVersion);
1108 return pos.IsNull();
1111 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
1113 return (a.pos == b.pos &&
1114 a.vSpent == b.vSpent);
1117 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
1121 int GetDepthInMainChain() const;
1129 // Nodes collect new transactions into a block, hash them into a hash tree,
1130 // and scan through nonce values to make the block's hash satisfy proof-of-work
1131 // requirements. When they solve the proof-of-work, they broadcast the block
1132 // to everyone and the block is added to the block chain. The first transaction
1133 // in the block is a special one that creates a new coin owned by the creator
1136 // Blocks are appended to blk0001.dat files on disk. Their location on disk
1137 // is indexed by CBlockIndex objects in memory.
1144 uint256 hashPrevBlock;
1145 uint256 hashMerkleRoot;
1148 unsigned int nNonce;
1151 vector<CTransaction> vtx;
1154 mutable vector<uint256> vMerkleTree;
1164 READWRITE(this->nVersion);
1165 nVersion = this->nVersion;
1166 READWRITE(hashPrevBlock);
1167 READWRITE(hashMerkleRoot);
1172 // ConnectBlock depends on vtx being last so it can calculate offset
1173 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
1176 const_cast<CBlock*>(this)->vtx.clear();
1188 vMerkleTree.clear();
1193 return (nBits == 0);
1196 uint256 GetHash() const
1198 return Hash(BEGIN(nVersion), END(nNonce));
1201 int64 GetBlockTime() const
1203 return (int64)nTime;
1206 int GetSigOpCount() const
1209 foreach(const CTransaction& tx, vtx)
1210 n += tx.GetSigOpCount();
1215 uint256 BuildMerkleTree() const
1217 vMerkleTree.clear();
1218 foreach(const CTransaction& tx, vtx)
1219 vMerkleTree.push_back(tx.GetHash());
1221 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1223 for (int i = 0; i < nSize; i += 2)
1225 int i2 = min(i+1, nSize-1);
1226 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
1227 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
1231 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
1234 vector<uint256> GetMerkleBranch(int nIndex) const
1236 if (vMerkleTree.empty())
1238 vector<uint256> vMerkleBranch;
1240 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1242 int i = min(nIndex^1, nSize-1);
1243 vMerkleBranch.push_back(vMerkleTree[j+i]);
1247 return vMerkleBranch;
1250 static uint256 CheckMerkleBranch(uint256 hash, const vector<uint256>& vMerkleBranch, int nIndex)
1254 foreach(const uint256& otherside, vMerkleBranch)
1257 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
1259 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
1266 bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
1268 // Open history file to append
1269 CAutoFile fileout = AppendBlockFile(nFileRet);
1271 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
1273 // Write index header
1274 unsigned int nSize = fileout.GetSerializeSize(*this);
1275 fileout << FLATDATA(pchMessageStart) << nSize;
1278 nBlockPosRet = ftell(fileout);
1279 if (nBlockPosRet == -1)
1280 return error("CBlock::WriteToDisk() : ftell failed");
1283 // Flush stdio buffers and commit to disk before returning
1285 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
1288 _commit(_fileno(fileout));
1290 fsync(fileno(fileout));
1297 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
1301 // Open history file to read
1302 CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");
1304 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1305 if (!fReadTransactions)
1306 filein.nType |= SER_BLOCKHEADERONLY;
1312 if (!CheckProofOfWork(GetHash(), nBits))
1313 return error("CBlock::ReadFromDisk() : errors in block header");
1322 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
1323 GetHash().ToString().substr(0,20).c_str(),
1325 hashPrevBlock.ToString().substr(0,20).c_str(),
1326 hashMerkleRoot.ToString().substr(0,10).c_str(),
1327 nTime, nBits, nNonce,
1329 for (int i = 0; i < vtx.size(); i++)
1334 printf(" vMerkleTree: ");
1335 for (int i = 0; i < vMerkleTree.size(); i++)
1336 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1341 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1342 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1343 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1344 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1345 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1346 bool CheckBlock() const;
1356 // The block chain is a tree shaped structure starting with the
1357 // genesis block at the root, with each block potentially having multiple
1358 // candidates to be the next block. pprev and pnext link a path through the
1359 // main/longest chain. A blockindex may have multiple pprev pointing back
1360 // to it, but pnext will only point forward to the longest branch, or will
1361 // be null if the block is not part of the longest chain.
1366 const uint256* phashBlock;
1370 unsigned int nBlockPos;
1372 CBigNum bnChainWork;
1376 uint256 hashMerkleRoot;
1379 unsigned int nNonce;
1399 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1405 nBlockPos = nBlockPosIn;
1409 nVersion = block.nVersion;
1410 hashMerkleRoot = block.hashMerkleRoot;
1411 nTime = block.nTime;
1412 nBits = block.nBits;
1413 nNonce = block.nNonce;
1416 CBlock GetBlockHeader() const
1419 block.nVersion = nVersion;
1421 block.hashPrevBlock = pprev->GetBlockHash();
1422 block.hashMerkleRoot = hashMerkleRoot;
1423 block.nTime = nTime;
1424 block.nBits = nBits;
1425 block.nNonce = nNonce;
1429 uint256 GetBlockHash() const
1434 int64 GetBlockTime() const
1436 return (int64)nTime;
1439 CBigNum GetBlockWork() const
1442 bnTarget.SetCompact(nBits);
1445 return (CBigNum(1)<<256) / (bnTarget+1);
1448 bool IsInMainChain() const
1450 return (pnext || this == pindexBest);
1453 bool CheckIndex() const
1455 return CheckProofOfWork(GetBlockHash(), nBits);
1458 bool EraseBlockFromDisk()
1460 // Open history file
1461 CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");
1465 // Overwrite with empty null block
1473 enum { nMedianTimeSpan=11 };
1475 int64 GetMedianTimePast() const
1477 int64 pmedian[nMedianTimeSpan];
1478 int64* pbegin = &pmedian[nMedianTimeSpan];
1479 int64* pend = &pmedian[nMedianTimeSpan];
1481 const CBlockIndex* pindex = this;
1482 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1483 *(--pbegin) = pindex->GetBlockTime();
1486 return pbegin[(pend - pbegin)/2];
1489 int64 GetMedianTime() const
1491 const CBlockIndex* pindex = this;
1492 for (int i = 0; i < nMedianTimeSpan/2; i++)
1495 return GetBlockTime();
1496 pindex = pindex->pnext;
1498 return pindex->GetMedianTimePast();
1503 string ToString() const
1505 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
1506 pprev, pnext, nFile, nBlockPos, nHeight,
1507 hashMerkleRoot.ToString().substr(0,10).c_str(),
1508 GetBlockHash().ToString().substr(0,20).c_str());
1513 printf("%s\n", ToString().c_str());
1520 // Used to marshal pointers into hashes for db storage.
1522 class CDiskBlockIndex : public CBlockIndex
1534 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1536 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1537 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1542 if (!(nType & SER_GETHASH))
1543 READWRITE(nVersion);
1545 READWRITE(hashNext);
1547 READWRITE(nBlockPos);
1551 READWRITE(this->nVersion);
1552 READWRITE(hashPrev);
1553 READWRITE(hashMerkleRoot);
1559 uint256 GetBlockHash() const
1562 block.nVersion = nVersion;
1563 block.hashPrevBlock = hashPrev;
1564 block.hashMerkleRoot = hashMerkleRoot;
1565 block.nTime = nTime;
1566 block.nBits = nBits;
1567 block.nNonce = nNonce;
1568 return block.GetHash();
1572 string ToString() const
1574 string str = "CDiskBlockIndex(";
1575 str += CBlockIndex::ToString();
1576 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1577 GetBlockHash().ToString().c_str(),
1578 hashPrev.ToString().substr(0,20).c_str(),
1579 hashNext.ToString().substr(0,20).c_str());
1585 printf("%s\n", ToString().c_str());
1597 // Describes a place in the block chain to another node such that if the
1598 // other node doesn't have the same branch, it can find a recent common trunk.
1599 // The further back it is, the further before the fork it may be.
1604 vector<uint256> vHave;
1611 explicit CBlockLocator(const CBlockIndex* pindex)
1616 explicit CBlockLocator(uint256 hashBlock)
1618 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1619 if (mi != mapBlockIndex.end())
1625 if (!(nType & SER_GETHASH))
1626 READWRITE(nVersion);
1637 return vHave.empty();
1640 void Set(const CBlockIndex* pindex)
1646 vHave.push_back(pindex->GetBlockHash());
1648 // Exponentially larger steps back
1649 for (int i = 0; pindex && i < nStep; i++)
1650 pindex = pindex->pprev;
1651 if (vHave.size() > 10)
1654 vHave.push_back(hashGenesisBlock);
1657 int GetDistanceBack()
1659 // Retrace how far back it was in the sender's branch
1662 foreach(const uint256& hash, vHave)
1664 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1665 if (mi != mapBlockIndex.end())
1667 CBlockIndex* pindex = (*mi).second;
1668 if (pindex->IsInMainChain())
1678 CBlockIndex* GetBlockIndex()
1680 // Find the first block the caller has in the main chain
1681 foreach(const uint256& hash, vHave)
1683 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1684 if (mi != mapBlockIndex.end())
1686 CBlockIndex* pindex = (*mi).second;
1687 if (pindex->IsInMainChain())
1691 return pindexGenesisBlock;
1694 uint256 GetBlockHash()
1696 // Find the first block the caller has in the main chain
1697 foreach(const uint256& hash, vHave)
1699 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1700 if (mi != mapBlockIndex.end())
1702 CBlockIndex* pindex = (*mi).second;
1703 if (pindex->IsInMainChain())
1707 return hashGenesisBlock;
1712 CBlockIndex* pindex = GetBlockIndex();
1715 return pindex->nHeight;
1725 // Private key that includes an expiration date in case it never gets used.
1730 CPrivKey vchPrivKey;
1734 //// todo: add something to note what created it (user, getnewaddress, change)
1735 //// maybe should have a map<string, string> property map
1737 CWalletKey(int64 nExpires=0)
1739 nTimeCreated = (nExpires ? GetTime() : 0);
1740 nTimeExpires = nExpires;
1745 if (!(nType & SER_GETHASH))
1746 READWRITE(nVersion);
1747 READWRITE(vchPrivKey);
1748 READWRITE(nTimeCreated);
1749 READWRITE(nTimeExpires);
1750 READWRITE(strComment);
1760 // Account information.
1761 // Stored in wallet with key "acc"+string account name
1766 vector<unsigned char> vchPubKey;
1780 if (!(nType & SER_GETHASH))
1781 READWRITE(nVersion);
1782 READWRITE(vchPubKey);
1789 // Internal transfers.
1790 // Database key is acentry<account><counter>
1792 class CAccountingEntry
1798 string strOtherAccount;
1811 strOtherAccount.clear();
1817 if (!(nType & SER_GETHASH))
1818 READWRITE(nVersion);
1819 // Note: strAccount is serialized as part of the key, not here.
1820 READWRITE(nCreditDebit);
1822 READWRITE(strOtherAccount);
1823 READWRITE(strComment);
1836 // Alerts are for notifying old versions if they become too obsolete and
1837 // need to upgrade. The message is displayed in the status bar.
1838 // Alert messages are broadcast as a vector of signed data. Unserializing may
1839 // not read the entire buffer if the alert is for a newer version, but older
1840 // versions can still relay the original data.
1842 class CUnsignedAlert
1846 int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
1851 int nMinVer; // lowest version inclusive
1852 int nMaxVer; // highest version inclusive
1853 set<string> setSubVer; // empty matches all
1858 string strStatusBar;
1863 READWRITE(this->nVersion);
1864 nVersion = this->nVersion;
1865 READWRITE(nRelayUntil);
1866 READWRITE(nExpiration);
1869 READWRITE(setCancel);
1872 READWRITE(setSubVer);
1873 READWRITE(nPriority);
1875 READWRITE(strComment);
1876 READWRITE(strStatusBar);
1877 READWRITE(strReserved);
1894 strStatusBar.clear();
1895 strReserved.clear();
1898 string ToString() const
1900 string strSetCancel;
1901 foreach(int n, setCancel)
1902 strSetCancel += strprintf("%d ", n);
1903 string strSetSubVer;
1904 foreach(string str, setSubVer)
1905 strSetSubVer += "\"" + str + "\" ";
1909 " nRelayUntil = %"PRI64d"\n"
1910 " nExpiration = %"PRI64d"\n"
1918 " strComment = \"%s\"\n"
1919 " strStatusBar = \"%s\"\n"
1926 strSetCancel.c_str(),
1929 strSetSubVer.c_str(),
1932 strStatusBar.c_str());
1937 printf("%s", ToString().c_str());
1941 class CAlert : public CUnsignedAlert
1944 vector<unsigned char> vchMsg;
1945 vector<unsigned char> vchSig;
1960 CUnsignedAlert::SetNull();
1967 return (nExpiration == 0);
1970 uint256 GetHash() const
1972 return SerializeHash(*this);
1975 bool IsInEffect() const
1977 return (GetAdjustedTime() < nExpiration);
1980 bool Cancels(const CAlert& alert) const
1983 return false; // this was a no-op before 31403
1984 return (alert.nID <= nCancel || setCancel.count(alert.nID));
1987 bool AppliesTo(int nVersion, string strSubVerIn) const
1989 return (IsInEffect() &&
1990 nMinVer <= nVersion && nVersion <= nMaxVer &&
1991 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1994 bool AppliesToMe() const
1996 return AppliesTo(VERSION, ::pszSubVer);
1999 bool RelayTo(CNode* pnode) const
2003 // returns true if wasn't already contained in the set
2004 if (pnode->setKnown.insert(GetHash()).second)
2006 if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
2008 GetAdjustedTime() < nRelayUntil)
2010 pnode->PushMessage("alert", *this);
2017 bool CheckSignature()
2020 if (!key.SetPubKey(ParseHex("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284")))
2021 return error("CAlert::CheckSignature() : SetPubKey failed");
2022 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
2023 return error("CAlert::CheckSignature() : verify signature failed");
2025 // Now unserialize the data
2026 CDataStream sMsg(vchMsg);
2027 sMsg >> *(CUnsignedAlert*)this;
2031 bool ProcessAlert();
2043 extern map<uint256, CTransaction> mapTransactions;
2044 extern map<uint256, CWalletTx> mapWallet;
2045 extern vector<uint256> vWalletUpdated;
2046 extern CCriticalSection cs_mapWallet;
2047 extern map<vector<unsigned char>, CPrivKey> mapKeys;
2048 extern map<uint160, vector<unsigned char> > mapPubKeys;
2049 extern CCriticalSection cs_mapKeys;
2050 extern CKey keyUser;