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;
31 extern CCriticalSection cs_main;
32 extern map<uint256, CBlockIndex*> mapBlockIndex;
33 extern uint256 hashGenesisBlock;
34 extern CBigNum bnProofOfWorkLimit;
35 extern CBlockIndex* pindexGenesisBlock;
36 extern int nBestHeight;
37 extern CBigNum bnBestChainWork;
38 extern CBigNum bnBestInvalidWork;
39 extern uint256 hashBestChain;
40 extern CBlockIndex* pindexBest;
41 extern unsigned int nTransactionsUpdated;
42 extern map<uint256, int> mapRequestCount;
43 extern CCriticalSection cs_mapRequestCount;
44 extern map<string, string> mapAddressBook;
45 extern CCriticalSection cs_mapAddressBook;
46 extern vector<unsigned char> vchDefaultKey;
47 extern double dHashesPerSec;
48 extern int64 nHPSTimerStart;
51 extern int fGenerateBitcoins;
52 extern int64 nTransactionFee;
53 extern CAddress addrIncoming;
54 extern int fLimitProcessors;
55 extern int nLimitProcessors;
56 extern int fMinimizeToTray;
57 extern int fMinimizeOnClose;
65 bool CheckDiskSpace(uint64 nAdditionalBytes=0);
66 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
67 FILE* AppendBlockFile(unsigned int& nFileRet);
68 bool AddKey(const CKey& key);
69 vector<unsigned char> GenerateNewKey();
70 bool AddToWallet(const CWalletTx& wtxIn);
71 void WalletUpdateSpent(const COutPoint& prevout);
72 int ScanForWalletTransactions(CBlockIndex* pindexStart);
73 void ReacceptWalletTransactions();
74 bool LoadBlockIndex(bool fAllowNew=true);
75 void PrintBlockTree();
76 bool ProcessMessages(CNode* pfrom);
77 bool ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv);
78 bool SendMessages(CNode* pto, bool fSendTrickle);
80 bool CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
81 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
82 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
83 bool BroadcastTransaction(CWalletTx& wtxNew);
84 string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
85 string SendMoneyToBitcoinAddress(string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
86 void GenerateBitcoins(bool fGenerate);
87 void ThreadBitcoinMiner(void* parg);
88 CBlock* CreateNewBlock(CReserveKey& reservekey);
89 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce, int64& nPrevTime);
90 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
91 bool CheckWork(CBlock* pblock, CReserveKey& reservekey);
93 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
94 bool IsInitialBlockDownload();
95 string GetWarnings(string strFor);
112 unsigned int nBlockPos;
120 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
123 nBlockPos = nBlockPosIn;
127 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
128 void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
129 bool IsNull() const { return (nFile == -1); }
131 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
133 return (a.nFile == b.nFile &&
134 a.nBlockPos == b.nBlockPos &&
135 a.nTxPos == b.nTxPos);
138 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
143 string ToString() const
146 return strprintf("null");
148 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
153 printf("%s", ToString().c_str());
166 CInPoint() { SetNull(); }
167 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
168 void SetNull() { ptx = NULL; n = -1; }
169 bool IsNull() const { return (ptx == NULL && n == -1); }
181 COutPoint() { SetNull(); }
182 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
183 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
184 void SetNull() { hash = 0; n = -1; }
185 bool IsNull() const { return (hash == 0 && n == -1); }
187 friend bool operator<(const COutPoint& a, const COutPoint& b)
189 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
192 friend bool operator==(const COutPoint& a, const COutPoint& b)
194 return (a.hash == b.hash && a.n == b.n);
197 friend bool operator!=(const COutPoint& a, const COutPoint& b)
202 string ToString() const
204 return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,10).c_str(), n);
209 printf("%s\n", ToString().c_str());
217 // An input of a transaction. It contains the location of the previous
218 // transaction's output that it claims and a signature that matches the
219 // output's public key.
226 unsigned int nSequence;
230 nSequence = UINT_MAX;
233 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
236 scriptSig = scriptSigIn;
237 nSequence = nSequenceIn;
240 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
242 prevout = COutPoint(hashPrevTx, nOut);
243 scriptSig = scriptSigIn;
244 nSequence = nSequenceIn;
250 READWRITE(scriptSig);
251 READWRITE(nSequence);
256 return (nSequence == UINT_MAX);
259 friend bool operator==(const CTxIn& a, const CTxIn& b)
261 return (a.prevout == b.prevout &&
262 a.scriptSig == b.scriptSig &&
263 a.nSequence == b.nSequence);
266 friend bool operator!=(const CTxIn& a, const CTxIn& b)
271 string ToString() const
274 str += strprintf("CTxIn(");
275 str += prevout.ToString();
276 if (prevout.IsNull())
277 str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
279 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
280 if (nSequence != UINT_MAX)
281 str += strprintf(", nSequence=%u", nSequence);
288 printf("%s\n", ToString().c_str());
292 int64 GetDebit() const;
299 // An output of a transaction. It contains the public key that the next input
300 // must be able to sign with to claim it.
306 CScript scriptPubKey;
313 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
316 scriptPubKey = scriptPubKeyIn;
322 READWRITE(scriptPubKey);
328 scriptPubKey.clear();
333 return (nValue == -1);
336 uint256 GetHash() const
338 return SerializeHash(*this);
343 return ::IsMine(scriptPubKey);
346 int64 GetCredit() const
348 if (!MoneyRange(nValue))
349 throw runtime_error("CTxOut::GetCredit() : value out of range");
350 return (IsMine() ? nValue : 0);
353 bool IsChange() const
355 // On a debit transaction, a txout that's mine but isn't in the address book is change
356 vector<unsigned char> vchPubKey;
357 if (ExtractPubKey(scriptPubKey, true, vchPubKey))
358 CRITICAL_BLOCK(cs_mapAddressBook)
359 if (!mapAddressBook.count(PubKeyToAddress(vchPubKey)))
364 int64 GetChange() const
366 if (!MoneyRange(nValue))
367 throw runtime_error("CTxOut::GetChange() : value out of range");
368 return (IsChange() ? nValue : 0);
371 friend bool operator==(const CTxOut& a, const CTxOut& b)
373 return (a.nValue == b.nValue &&
374 a.scriptPubKey == b.scriptPubKey);
377 friend bool operator!=(const CTxOut& a, const CTxOut& b)
382 string ToString() const
384 if (scriptPubKey.size() < 6)
385 return "CTxOut(error)";
386 return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,30).c_str());
391 printf("%s\n", ToString().c_str());
399 // The basic transaction that is broadcasted on the network and contained in
400 // blocks. A transaction can contain multiple inputs and outputs.
408 unsigned int nLockTime;
418 READWRITE(this->nVersion);
419 nVersion = this->nVersion;
422 READWRITE(nLockTime);
435 return (vin.empty() && vout.empty());
438 uint256 GetHash() const
440 return SerializeHash(*this);
443 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
445 // Time based nLockTime implemented in 0.1.6
448 if (nBlockHeight == 0)
449 nBlockHeight = nBestHeight;
451 nBlockTime = GetAdjustedTime();
452 if ((int64)nLockTime < (nLockTime < 500000000 ? (int64)nBlockHeight : nBlockTime))
454 foreach(const CTxIn& txin, vin)
460 bool IsNewerThan(const CTransaction& old) const
462 if (vin.size() != old.vin.size())
464 for (int i = 0; i < vin.size(); i++)
465 if (vin[i].prevout != old.vin[i].prevout)
469 unsigned int nLowest = UINT_MAX;
470 for (int i = 0; i < vin.size(); i++)
472 if (vin[i].nSequence != old.vin[i].nSequence)
474 if (vin[i].nSequence <= nLowest)
477 nLowest = vin[i].nSequence;
479 if (old.vin[i].nSequence < nLowest)
482 nLowest = old.vin[i].nSequence;
489 bool IsCoinBase() const
491 return (vin.size() == 1 && vin[0].prevout.IsNull());
494 int GetSigOpCount() const
497 foreach(const CTxIn& txin, vin)
498 n += txin.scriptSig.GetSigOpCount();
499 foreach(const CTxOut& txout, vout)
500 n += txout.scriptPubKey.GetSigOpCount();
504 bool IsStandard() const
506 foreach(const CTxIn& txin, vin)
507 if (!txin.scriptSig.IsPushOnly())
508 return error("nonstandard txin: %s", txin.scriptSig.ToString().c_str());
509 foreach(const CTxOut& txout, vout)
510 if (!::IsStandard(txout.scriptPubKey))
511 return error("nonstandard txout: %s", txout.scriptPubKey.ToString().c_str());
517 foreach(const CTxOut& txout, vout)
523 bool IsFromMe() const
525 return (GetDebit() > 0);
528 int64 GetDebit() const
531 foreach(const CTxIn& txin, vin)
533 nDebit += txin.GetDebit();
534 if (!MoneyRange(nDebit))
535 throw runtime_error("CTransaction::GetDebit() : value out of range");
540 int64 GetCredit() const
543 foreach(const CTxOut& txout, vout)
545 nCredit += txout.GetCredit();
546 if (!MoneyRange(nCredit))
547 throw runtime_error("CTransaction::GetCredit() : value out of range");
552 int64 GetChange() const
557 foreach(const CTxOut& txout, vout)
559 nChange += txout.GetChange();
560 if (!MoneyRange(nChange))
561 throw runtime_error("CTransaction::GetChange() : value out of range");
566 int64 GetValueOut() const
569 foreach(const CTxOut& txout, vout)
571 nValueOut += txout.nValue;
572 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
573 throw runtime_error("CTransaction::GetValueOut() : value out of range");
578 static bool AllowFree(double dPriority)
580 // Large (in bytes) low-priority (new, small-coin) transactions
582 return dPriority > COIN * 144 / 250;
585 int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=true) const
587 // Base fee is 1 cent per kilobyte
588 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);
589 unsigned int nNewBlockSize = nBlockSize + nBytes;
590 int64 nMinFee = (1 + (int64)nBytes / 1000) * CENT;
596 // Transactions under 10K are free
597 // (about 4500bc if made of 50bc inputs)
603 // Free transaction area
604 if (nNewBlockSize < 27000)
609 // To limit dust spam, require a 0.01 fee if any output is less than 0.01
611 foreach(const CTxOut& txout, vout)
612 if (txout.nValue < CENT)
615 // Raise the price as the block approaches full
616 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
618 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
620 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
623 if (!MoneyRange(nMinFee))
629 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
631 CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");
633 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
636 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
637 return error("CTransaction::ReadFromDisk() : fseek failed");
640 // Return file pointer
643 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
644 return error("CTransaction::ReadFromDisk() : second fseek failed");
645 *pfileRet = filein.release();
650 friend bool operator==(const CTransaction& a, const CTransaction& b)
652 return (a.nVersion == b.nVersion &&
655 a.nLockTime == b.nLockTime);
658 friend bool operator!=(const CTransaction& a, const CTransaction& b)
664 string ToString() const
667 str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
668 GetHash().ToString().substr(0,10).c_str(),
673 for (int i = 0; i < vin.size(); i++)
674 str += " " + vin[i].ToString() + "\n";
675 for (int i = 0; i < vout.size(); i++)
676 str += " " + vout[i].ToString() + "\n";
682 printf("%s", ToString().c_str());
686 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
687 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
688 bool ReadFromDisk(COutPoint prevout);
689 bool DisconnectInputs(CTxDB& txdb);
690 bool ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
691 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee=0);
692 bool ClientConnectInputs();
693 bool CheckTransaction() const;
694 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
695 bool AcceptToMemoryPool(bool fCheckInputs=true, bool* pfMissingInputs=NULL)
698 return AcceptToMemoryPool(txdb, fCheckInputs, pfMissingInputs);
701 bool AddToMemoryPoolUnchecked();
703 bool RemoveFromMemoryPool();
711 // A transaction with a merkle branch linking it to the block chain
713 class CMerkleTx : public CTransaction
717 vector<uint256> vMerkleBranch;
721 mutable char fMerkleVerified;
729 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
738 fMerkleVerified = false;
744 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
745 nVersion = this->nVersion;
746 READWRITE(hashBlock);
747 READWRITE(vMerkleBranch);
752 int SetMerkleBranch(const CBlock* pblock=NULL);
753 int GetDepthInMainChain(int& nHeightRet) const;
754 int GetDepthInMainChain() const { int nHeight; return GetDepthInMainChain(nHeight); }
755 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
756 int GetBlocksToMaturity() const;
757 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
758 bool AcceptToMemoryPool() { CTxDB txdb("r"); return AcceptToMemoryPool(txdb); }
765 // A transaction with a bunch of additional info that only the owner cares
766 // about. It includes any unrecorded transactions needed to link it back
767 // to the block chain.
769 class CWalletTx : public CMerkleTx
772 vector<CMerkleTx> vtxPrev;
773 map<string, string> mapValue;
774 vector<pair<string, string> > vOrderForm;
775 unsigned int fTimeReceivedIsTxTime;
776 unsigned int nTimeReceived; // time received by this node
778 string strFromAccount;
779 vector<char> vfSpent;
782 mutable char fDebitCached;
783 mutable char fCreditCached;
784 mutable char fAvailableCreditCached;
785 mutable char fChangeCached;
786 mutable int64 nDebitCached;
787 mutable int64 nCreditCached;
788 mutable int64 nAvailableCreditCached;
789 mutable int64 nChangeCached;
791 // memory only UI hints
792 mutable unsigned int nTimeDisplayed;
793 mutable int nLinesDisplayed;
794 mutable char fConfirmedDisplayed;
802 CWalletTx(const CMerkleTx& txIn) : CMerkleTx(txIn)
807 CWalletTx(const CTransaction& txIn) : CMerkleTx(txIn)
817 fTimeReceivedIsTxTime = false;
820 strFromAccount.clear();
822 fDebitCached = false;
823 fCreditCached = false;
824 fAvailableCreditCached = false;
825 fChangeCached = false;
828 nAvailableCreditCached = 0;
832 fConfirmedDisplayed = false;
837 CWalletTx* pthis = const_cast<CWalletTx*>(this);
844 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
847 foreach(char f, vfSpent)
849 str += (f ? '1' : '0');
853 pthis->mapValue["spent"] = str;
856 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
859 READWRITE(vOrderForm);
860 READWRITE(fTimeReceivedIsTxTime);
861 READWRITE(nTimeReceived);
867 pthis->strFromAccount = pthis->mapValue["fromaccount"];
869 if (mapValue.count("spent"))
870 foreach(char c, pthis->mapValue["spent"])
871 pthis->vfSpent.push_back(c != '0');
873 pthis->vfSpent.assign(vout.size(), fSpent);
876 pthis->mapValue.erase("fromaccount");
877 pthis->mapValue.erase("version");
878 pthis->mapValue.erase("spent");
881 // marks certain txout's as spent
882 // returns true if any update took place
883 bool UpdateSpent(const vector<char>& vfNewSpent)
885 bool fReturn = false;
886 for (int i=0; i < vfNewSpent.size(); i++)
888 if (i == vfSpent.size())
891 if (vfNewSpent[i] && !vfSpent[i])
895 fAvailableCreditCached = false;
903 fCreditCached = false;
904 fAvailableCreditCached = false;
905 fDebitCached = false;
906 fChangeCached = false;
909 void MarkSpent(unsigned int nOut)
911 if (nOut >= vout.size())
912 throw runtime_error("CWalletTx::MarkSpent() : nOut out of range");
913 vfSpent.resize(vout.size());
916 vfSpent[nOut] = true;
917 fAvailableCreditCached = false;
921 bool IsSpent(unsigned int nOut) const
923 if (nOut >= vout.size())
924 throw runtime_error("CWalletTx::IsSpent() : nOut out of range");
925 if (nOut >= vfSpent.size())
927 return (!!vfSpent[nOut]);
930 int64 GetDebit() const
936 nDebitCached = CTransaction::GetDebit();
941 int64 GetCredit(bool fUseCache=true) const
943 // Must wait until coinbase is safely deep enough in the chain before valuing it
944 if (IsCoinBase() && GetBlocksToMaturity() > 0)
947 // GetBalance can assume transactions in mapWallet won't change
948 if (fUseCache && fCreditCached)
949 return nCreditCached;
950 nCreditCached = CTransaction::GetCredit();
951 fCreditCached = true;
952 return nCreditCached;
955 int64 GetAvailableCredit(bool fUseCache=true) const
957 // Must wait until coinbase is safely deep enough in the chain before valuing it
958 if (IsCoinBase() && GetBlocksToMaturity() > 0)
961 if (fUseCache && fAvailableCreditCached)
962 return nAvailableCreditCached;
965 for (int i = 0; i < vout.size(); i++)
969 const CTxOut &txout = vout[i];
970 nCredit += txout.GetCredit();
971 if (!MoneyRange(nCredit))
972 throw runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
976 nAvailableCreditCached = nCredit;
977 fAvailableCreditCached = true;
982 int64 GetChange() const
985 return nChangeCached;
986 nChangeCached = CTransaction::GetChange();
987 fChangeCached = true;
988 return nChangeCached;
991 void GetAmounts(int64& nGenerated, list<pair<string /* address */, int64> >& listReceived,
992 list<pair<string /* address */, int64> >& listSent, int64& nFee, string& strSentAccount) const;
994 void GetAccountAmounts(const string& strAccount, int64& nGenerated, int64& nReceived,
995 int64& nSent, int64& nFee) const;
997 bool IsFromMe() const
999 return (GetDebit() > 0);
1002 bool IsConfirmed() const
1004 // Quick answer in most cases
1007 if (GetDepthInMainChain() >= 1)
1009 if (!IsFromMe()) // using wtx's cached debit
1012 // If no confirmations but it's from us, we can still
1013 // consider it confirmed if all dependencies are confirmed
1014 map<uint256, const CMerkleTx*> mapPrev;
1015 vector<const CMerkleTx*> vWorkQueue;
1016 vWorkQueue.reserve(vtxPrev.size()+1);
1017 vWorkQueue.push_back(this);
1018 for (int i = 0; i < vWorkQueue.size(); i++)
1020 const CMerkleTx* ptx = vWorkQueue[i];
1022 if (!ptx->IsFinal())
1024 if (ptx->GetDepthInMainChain() >= 1)
1026 if (!ptx->IsFromMe())
1029 if (mapPrev.empty())
1030 foreach(const CMerkleTx& tx, vtxPrev)
1031 mapPrev[tx.GetHash()] = &tx;
1033 foreach(const CTxIn& txin, ptx->vin)
1035 if (!mapPrev.count(txin.prevout.hash))
1037 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
1045 return CWalletDB().WriteTx(GetHash(), *this);
1049 int64 GetTxTime() const;
1050 int GetRequestCount() const;
1052 void AddSupportingTransactions(CTxDB& txdb);
1054 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
1055 bool AcceptWalletTransaction() { CTxDB txdb("r"); return AcceptWalletTransaction(txdb); }
1057 void RelayWalletTransaction(CTxDB& txdb);
1058 void RelayWalletTransaction() { CTxDB txdb("r"); RelayWalletTransaction(txdb); }
1065 // A txdb record that contains the disk location of a transaction and the
1066 // locations of transactions that spend its outputs. vSpent is really only
1067 // used as a flag, but having the location is very helpful for debugging.
1073 vector<CDiskTxPos> vSpent;
1080 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
1083 vSpent.resize(nOutputs);
1088 if (!(nType & SER_GETHASH))
1089 READWRITE(nVersion);
1102 return pos.IsNull();
1105 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
1107 return (a.pos == b.pos &&
1108 a.vSpent == b.vSpent);
1111 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
1115 int GetDepthInMainChain() const;
1123 // Nodes collect new transactions into a block, hash them into a hash tree,
1124 // and scan through nonce values to make the block's hash satisfy proof-of-work
1125 // requirements. When they solve the proof-of-work, they broadcast the block
1126 // to everyone and the block is added to the block chain. The first transaction
1127 // in the block is a special one that creates a new coin owned by the creator
1130 // Blocks are appended to blk0001.dat files on disk. Their location on disk
1131 // is indexed by CBlockIndex objects in memory.
1138 uint256 hashPrevBlock;
1139 uint256 hashMerkleRoot;
1142 unsigned int nNonce;
1145 vector<CTransaction> vtx;
1148 mutable vector<uint256> vMerkleTree;
1158 READWRITE(this->nVersion);
1159 nVersion = this->nVersion;
1160 READWRITE(hashPrevBlock);
1161 READWRITE(hashMerkleRoot);
1166 // ConnectBlock depends on vtx being last so it can calculate offset
1167 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
1170 const_cast<CBlock*>(this)->vtx.clear();
1182 vMerkleTree.clear();
1187 return (nBits == 0);
1190 uint256 GetHash() const
1192 return Hash(BEGIN(nVersion), END(nNonce));
1195 int64 GetBlockTime() const
1197 return (int64)nTime;
1200 int GetSigOpCount() const
1203 foreach(const CTransaction& tx, vtx)
1204 n += tx.GetSigOpCount();
1209 uint256 BuildMerkleTree() const
1211 vMerkleTree.clear();
1212 foreach(const CTransaction& tx, vtx)
1213 vMerkleTree.push_back(tx.GetHash());
1215 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1217 for (int i = 0; i < nSize; i += 2)
1219 int i2 = min(i+1, nSize-1);
1220 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
1221 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
1225 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
1228 vector<uint256> GetMerkleBranch(int nIndex) const
1230 if (vMerkleTree.empty())
1232 vector<uint256> vMerkleBranch;
1234 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1236 int i = min(nIndex^1, nSize-1);
1237 vMerkleBranch.push_back(vMerkleTree[j+i]);
1241 return vMerkleBranch;
1244 static uint256 CheckMerkleBranch(uint256 hash, const vector<uint256>& vMerkleBranch, int nIndex)
1248 foreach(const uint256& otherside, vMerkleBranch)
1251 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
1253 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
1260 bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
1262 // Open history file to append
1263 CAutoFile fileout = AppendBlockFile(nFileRet);
1265 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
1267 // Write index header
1268 unsigned int nSize = fileout.GetSerializeSize(*this);
1269 fileout << FLATDATA(pchMessageStart) << nSize;
1272 nBlockPosRet = ftell(fileout);
1273 if (nBlockPosRet == -1)
1274 return error("CBlock::WriteToDisk() : ftell failed");
1277 // Flush stdio buffers and commit to disk before returning
1279 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
1282 _commit(_fileno(fileout));
1284 fsync(fileno(fileout));
1291 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
1295 // Open history file to read
1296 CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");
1298 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1299 if (!fReadTransactions)
1300 filein.nType |= SER_BLOCKHEADERONLY;
1306 if (!CheckProofOfWork(GetHash(), nBits))
1307 return error("CBlock::ReadFromDisk() : errors in block header");
1316 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
1317 GetHash().ToString().substr(0,20).c_str(),
1319 hashPrevBlock.ToString().substr(0,20).c_str(),
1320 hashMerkleRoot.ToString().substr(0,10).c_str(),
1321 nTime, nBits, nNonce,
1323 for (int i = 0; i < vtx.size(); i++)
1328 printf(" vMerkleTree: ");
1329 for (int i = 0; i < vMerkleTree.size(); i++)
1330 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1335 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1336 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1337 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1338 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1339 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1340 bool CheckBlock() const;
1350 // The block chain is a tree shaped structure starting with the
1351 // genesis block at the root, with each block potentially having multiple
1352 // candidates to be the next block. pprev and pnext link a path through the
1353 // main/longest chain. A blockindex may have multiple pprev pointing back
1354 // to it, but pnext will only point forward to the longest branch, or will
1355 // be null if the block is not part of the longest chain.
1360 const uint256* phashBlock;
1364 unsigned int nBlockPos;
1366 CBigNum bnChainWork;
1370 uint256 hashMerkleRoot;
1373 unsigned int nNonce;
1393 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1399 nBlockPos = nBlockPosIn;
1403 nVersion = block.nVersion;
1404 hashMerkleRoot = block.hashMerkleRoot;
1405 nTime = block.nTime;
1406 nBits = block.nBits;
1407 nNonce = block.nNonce;
1410 CBlock GetBlockHeader() const
1413 block.nVersion = nVersion;
1415 block.hashPrevBlock = pprev->GetBlockHash();
1416 block.hashMerkleRoot = hashMerkleRoot;
1417 block.nTime = nTime;
1418 block.nBits = nBits;
1419 block.nNonce = nNonce;
1423 uint256 GetBlockHash() const
1428 int64 GetBlockTime() const
1430 return (int64)nTime;
1433 CBigNum GetBlockWork() const
1436 bnTarget.SetCompact(nBits);
1439 return (CBigNum(1)<<256) / (bnTarget+1);
1442 bool IsInMainChain() const
1444 return (pnext || this == pindexBest);
1447 bool CheckIndex() const
1449 return CheckProofOfWork(GetBlockHash(), nBits);
1452 bool EraseBlockFromDisk()
1454 // Open history file
1455 CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");
1459 // Overwrite with empty null block
1467 enum { nMedianTimeSpan=11 };
1469 int64 GetMedianTimePast() const
1471 int64 pmedian[nMedianTimeSpan];
1472 int64* pbegin = &pmedian[nMedianTimeSpan];
1473 int64* pend = &pmedian[nMedianTimeSpan];
1475 const CBlockIndex* pindex = this;
1476 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1477 *(--pbegin) = pindex->GetBlockTime();
1480 return pbegin[(pend - pbegin)/2];
1483 int64 GetMedianTime() const
1485 const CBlockIndex* pindex = this;
1486 for (int i = 0; i < nMedianTimeSpan/2; i++)
1489 return GetBlockTime();
1490 pindex = pindex->pnext;
1492 return pindex->GetMedianTimePast();
1497 string ToString() const
1499 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
1500 pprev, pnext, nFile, nBlockPos, nHeight,
1501 hashMerkleRoot.ToString().substr(0,10).c_str(),
1502 GetBlockHash().ToString().substr(0,20).c_str());
1507 printf("%s\n", ToString().c_str());
1514 // Used to marshal pointers into hashes for db storage.
1516 class CDiskBlockIndex : public CBlockIndex
1528 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1530 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1531 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1536 if (!(nType & SER_GETHASH))
1537 READWRITE(nVersion);
1539 READWRITE(hashNext);
1541 READWRITE(nBlockPos);
1545 READWRITE(this->nVersion);
1546 READWRITE(hashPrev);
1547 READWRITE(hashMerkleRoot);
1553 uint256 GetBlockHash() const
1556 block.nVersion = nVersion;
1557 block.hashPrevBlock = hashPrev;
1558 block.hashMerkleRoot = hashMerkleRoot;
1559 block.nTime = nTime;
1560 block.nBits = nBits;
1561 block.nNonce = nNonce;
1562 return block.GetHash();
1566 string ToString() const
1568 string str = "CDiskBlockIndex(";
1569 str += CBlockIndex::ToString();
1570 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1571 GetBlockHash().ToString().c_str(),
1572 hashPrev.ToString().substr(0,20).c_str(),
1573 hashNext.ToString().substr(0,20).c_str());
1579 printf("%s\n", ToString().c_str());
1591 // Describes a place in the block chain to another node such that if the
1592 // other node doesn't have the same branch, it can find a recent common trunk.
1593 // The further back it is, the further before the fork it may be.
1598 vector<uint256> vHave;
1605 explicit CBlockLocator(const CBlockIndex* pindex)
1610 explicit CBlockLocator(uint256 hashBlock)
1612 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1613 if (mi != mapBlockIndex.end())
1619 if (!(nType & SER_GETHASH))
1620 READWRITE(nVersion);
1631 return vHave.empty();
1634 void Set(const CBlockIndex* pindex)
1640 vHave.push_back(pindex->GetBlockHash());
1642 // Exponentially larger steps back
1643 for (int i = 0; pindex && i < nStep; i++)
1644 pindex = pindex->pprev;
1645 if (vHave.size() > 10)
1648 vHave.push_back(hashGenesisBlock);
1651 int GetDistanceBack()
1653 // Retrace how far back it was in the sender's branch
1656 foreach(const uint256& hash, vHave)
1658 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1659 if (mi != mapBlockIndex.end())
1661 CBlockIndex* pindex = (*mi).second;
1662 if (pindex->IsInMainChain())
1672 CBlockIndex* GetBlockIndex()
1674 // Find the first block the caller has in the main chain
1675 foreach(const uint256& hash, vHave)
1677 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1678 if (mi != mapBlockIndex.end())
1680 CBlockIndex* pindex = (*mi).second;
1681 if (pindex->IsInMainChain())
1685 return pindexGenesisBlock;
1688 uint256 GetBlockHash()
1690 // Find the first block the caller has in the main chain
1691 foreach(const uint256& hash, vHave)
1693 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1694 if (mi != mapBlockIndex.end())
1696 CBlockIndex* pindex = (*mi).second;
1697 if (pindex->IsInMainChain())
1701 return hashGenesisBlock;
1706 CBlockIndex* pindex = GetBlockIndex();
1709 return pindex->nHeight;
1719 // Private key that includes an expiration date in case it never gets used.
1724 CPrivKey vchPrivKey;
1728 //// todo: add something to note what created it (user, getnewaddress, change)
1729 //// maybe should have a map<string, string> property map
1731 CWalletKey(int64 nExpires=0)
1733 nTimeCreated = (nExpires ? GetTime() : 0);
1734 nTimeExpires = nExpires;
1739 if (!(nType & SER_GETHASH))
1740 READWRITE(nVersion);
1741 READWRITE(vchPrivKey);
1742 READWRITE(nTimeCreated);
1743 READWRITE(nTimeExpires);
1744 READWRITE(strComment);
1754 // Account information.
1755 // Stored in wallet with key "acc"+string account name
1760 vector<unsigned char> vchPubKey;
1774 if (!(nType & SER_GETHASH))
1775 READWRITE(nVersion);
1776 READWRITE(vchPubKey);
1783 // Internal transfers.
1784 // Database key is acentry<account><counter>
1786 class CAccountingEntry
1792 string strOtherAccount;
1805 strOtherAccount.clear();
1811 if (!(nType & SER_GETHASH))
1812 READWRITE(nVersion);
1813 // Note: strAccount is serialized as part of the key, not here.
1814 READWRITE(nCreditDebit);
1816 READWRITE(strOtherAccount);
1817 READWRITE(strComment);
1830 // Alerts are for notifying old versions if they become too obsolete and
1831 // need to upgrade. The message is displayed in the status bar.
1832 // Alert messages are broadcast as a vector of signed data. Unserializing may
1833 // not read the entire buffer if the alert is for a newer version, but older
1834 // versions can still relay the original data.
1836 class CUnsignedAlert
1840 int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
1845 int nMinVer; // lowest version inclusive
1846 int nMaxVer; // highest version inclusive
1847 set<string> setSubVer; // empty matches all
1852 string strStatusBar;
1857 READWRITE(this->nVersion);
1858 nVersion = this->nVersion;
1859 READWRITE(nRelayUntil);
1860 READWRITE(nExpiration);
1863 READWRITE(setCancel);
1866 READWRITE(setSubVer);
1867 READWRITE(nPriority);
1869 READWRITE(strComment);
1870 READWRITE(strStatusBar);
1871 READWRITE(strReserved);
1888 strStatusBar.clear();
1889 strReserved.clear();
1892 string ToString() const
1894 string strSetCancel;
1895 foreach(int n, setCancel)
1896 strSetCancel += strprintf("%d ", n);
1897 string strSetSubVer;
1898 foreach(string str, setSubVer)
1899 strSetSubVer += "\"" + str + "\" ";
1903 " nRelayUntil = %"PRI64d"\n"
1904 " nExpiration = %"PRI64d"\n"
1912 " strComment = \"%s\"\n"
1913 " strStatusBar = \"%s\"\n"
1920 strSetCancel.c_str(),
1923 strSetSubVer.c_str(),
1926 strStatusBar.c_str());
1931 printf("%s", ToString().c_str());
1935 class CAlert : public CUnsignedAlert
1938 vector<unsigned char> vchMsg;
1939 vector<unsigned char> vchSig;
1954 CUnsignedAlert::SetNull();
1961 return (nExpiration == 0);
1964 uint256 GetHash() const
1966 return SerializeHash(*this);
1969 bool IsInEffect() const
1971 return (GetAdjustedTime() < nExpiration);
1974 bool Cancels(const CAlert& alert) const
1977 return false; // this was a no-op before 31403
1978 return (alert.nID <= nCancel || setCancel.count(alert.nID));
1981 bool AppliesTo(int nVersion, string strSubVerIn) const
1983 return (IsInEffect() &&
1984 nMinVer <= nVersion && nVersion <= nMaxVer &&
1985 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1988 bool AppliesToMe() const
1990 return AppliesTo(VERSION, ::pszSubVer);
1993 bool RelayTo(CNode* pnode) const
1997 // returns true if wasn't already contained in the set
1998 if (pnode->setKnown.insert(GetHash()).second)
2000 if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
2002 GetAdjustedTime() < nRelayUntil)
2004 pnode->PushMessage("alert", *this);
2011 bool CheckSignature()
2014 if (!key.SetPubKey(ParseHex("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284")))
2015 return error("CAlert::CheckSignature() : SetPubKey failed");
2016 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
2017 return error("CAlert::CheckSignature() : verify signature failed");
2019 // Now unserialize the data
2020 CDataStream sMsg(vchMsg);
2021 sMsg >> *(CUnsignedAlert*)this;
2025 bool ProcessAlert();
2037 extern map<uint256, CTransaction> mapTransactions;
2038 extern map<uint256, CWalletTx> mapWallet;
2039 extern vector<uint256> vWalletUpdated;
2040 extern CCriticalSection cs_mapWallet;
2041 extern map<vector<unsigned char>, CPrivKey> mapKeys;
2042 extern map<uint160, vector<unsigned char> > mapPubKeys;
2043 extern CCriticalSection cs_mapKeys;
2044 extern CKey keyUser;