1 // Copyright (c) 2009-2010 Satoshi Nakamoto
\r
2 // Distributed under the MIT/X11 software license, see the accompanying
\r
3 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
\r
17 static const unsigned int MAX_BLOCK_SIZE = 1000000;
\r
18 static const int64 COIN = 100000000;
\r
19 static const int64 CENT = 1000000;
\r
20 static const int64 MAX_MONEY = 21000000 * COIN;
\r
21 inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
\r
22 static const int COINBASE_MATURITY = 100;
\r
23 static const CBigNum bnProofOfWorkLimit(~uint256(0) >> 32);
\r
30 extern CCriticalSection cs_main;
\r
31 extern map<uint256, CBlockIndex*> mapBlockIndex;
\r
32 extern const uint256 hashGenesisBlock;
\r
33 extern CBlockIndex* pindexGenesisBlock;
\r
34 extern int nBestHeight;
\r
35 extern CBigNum bnBestChainWork;
\r
36 extern CBigNum bnBestInvalidWork;
\r
37 extern uint256 hashBestChain;
\r
38 extern CBlockIndex* pindexBest;
\r
39 extern unsigned int nTransactionsUpdated;
\r
40 extern map<uint256, int> mapRequestCount;
\r
41 extern CCriticalSection cs_mapRequestCount;
\r
42 extern map<string, string> mapAddressBook;
\r
43 extern CCriticalSection cs_mapAddressBook;
\r
44 extern vector<unsigned char> vchDefaultKey;
\r
45 extern double dHashesPerSec;
\r
46 extern int64 nHPSTimerStart;
\r
49 extern int fGenerateBitcoins;
\r
50 extern int64 nTransactionFee;
\r
51 extern CAddress addrIncoming;
\r
52 extern int fLimitProcessors;
\r
53 extern int nLimitProcessors;
\r
54 extern int fMinimizeToTray;
\r
55 extern int fMinimizeOnClose;
\r
63 bool CheckDiskSpace(uint64 nAdditionalBytes=0);
\r
64 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
\r
65 FILE* AppendBlockFile(unsigned int& nFileRet);
\r
66 bool AddKey(const CKey& key);
\r
67 vector<unsigned char> GenerateNewKey();
\r
68 bool AddToWallet(const CWalletTx& wtxIn);
\r
69 void WalletUpdateSpent(const COutPoint& prevout);
\r
70 void ReacceptWalletTransactions();
\r
71 bool LoadBlockIndex(bool fAllowNew=true);
\r
72 void PrintBlockTree();
\r
73 bool ProcessMessages(CNode* pfrom);
\r
74 bool ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv);
\r
75 bool SendMessages(CNode* pto, bool fSendTrickle);
\r
77 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CKey& keyRet, int64& nFeeRequiredRet);
\r
78 bool CommitTransaction(CWalletTx& wtxNew, const CKey& key);
\r
79 bool BroadcastTransaction(CWalletTx& wtxNew);
\r
80 string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
\r
81 string SendMoneyToBitcoinAddress(string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
\r
82 void GenerateBitcoins(bool fGenerate);
\r
83 void ThreadBitcoinMiner(void* parg);
\r
84 void BitcoinMiner();
\r
85 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
\r
86 bool IsInitialBlockDownload();
\r
87 string GetWarnings(string strFor);
\r
103 unsigned int nFile;
\r
104 unsigned int nBlockPos;
\r
105 unsigned int nTxPos;
\r
112 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
\r
115 nBlockPos = nBlockPosIn;
\r
119 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
\r
120 void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
\r
121 bool IsNull() const { return (nFile == -1); }
\r
123 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
\r
125 return (a.nFile == b.nFile &&
\r
126 a.nBlockPos == b.nBlockPos &&
\r
127 a.nTxPos == b.nTxPos);
\r
130 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
\r
135 string ToString() const
\r
138 return strprintf("null");
\r
140 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
\r
145 printf("%s", ToString().c_str());
\r
158 CInPoint() { SetNull(); }
\r
159 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
\r
160 void SetNull() { ptx = NULL; n = -1; }
\r
161 bool IsNull() const { return (ptx == NULL && n == -1); }
\r
173 COutPoint() { SetNull(); }
\r
174 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
\r
175 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
\r
176 void SetNull() { hash = 0; n = -1; }
\r
177 bool IsNull() const { return (hash == 0 && n == -1); }
\r
179 friend bool operator<(const COutPoint& a, const COutPoint& b)
\r
181 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
\r
184 friend bool operator==(const COutPoint& a, const COutPoint& b)
\r
186 return (a.hash == b.hash && a.n == b.n);
\r
189 friend bool operator!=(const COutPoint& a, const COutPoint& b)
\r
194 string ToString() const
\r
196 return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,6).c_str(), n);
\r
201 printf("%s\n", ToString().c_str());
\r
209 // An input of a transaction. It contains the location of the previous
\r
210 // transaction's output that it claims and a signature that matches the
\r
211 // output's public key.
\r
218 unsigned int nSequence;
\r
222 nSequence = UINT_MAX;
\r
225 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
\r
227 prevout = prevoutIn;
\r
228 scriptSig = scriptSigIn;
\r
229 nSequence = nSequenceIn;
\r
232 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
\r
234 prevout = COutPoint(hashPrevTx, nOut);
\r
235 scriptSig = scriptSigIn;
\r
236 nSequence = nSequenceIn;
\r
239 IMPLEMENT_SERIALIZE
\r
241 READWRITE(prevout);
\r
242 READWRITE(scriptSig);
\r
243 READWRITE(nSequence);
\r
246 bool IsFinal() const
\r
248 return (nSequence == UINT_MAX);
\r
251 friend bool operator==(const CTxIn& a, const CTxIn& b)
\r
253 return (a.prevout == b.prevout &&
\r
254 a.scriptSig == b.scriptSig &&
\r
255 a.nSequence == b.nSequence);
\r
258 friend bool operator!=(const CTxIn& a, const CTxIn& b)
\r
263 string ToString() const
\r
266 str += strprintf("CTxIn(");
\r
267 str += prevout.ToString();
\r
268 if (prevout.IsNull())
\r
269 str += strprintf(", coinbase %s", HexStr(scriptSig.begin(), scriptSig.end(), false).c_str());
\r
271 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
\r
272 if (nSequence != UINT_MAX)
\r
273 str += strprintf(", nSequence=%u", nSequence);
\r
280 printf("%s\n", ToString().c_str());
\r
283 bool IsMine() const;
\r
284 int64 GetDebit() const;
\r
291 // An output of a transaction. It contains the public key that the next input
\r
292 // must be able to sign with to claim it.
\r
298 CScript scriptPubKey;
\r
305 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
\r
308 scriptPubKey = scriptPubKeyIn;
\r
311 IMPLEMENT_SERIALIZE
\r
314 READWRITE(scriptPubKey);
\r
320 scriptPubKey.clear();
\r
325 return (nValue == -1);
\r
328 uint256 GetHash() const
\r
330 return SerializeHash(*this);
\r
333 bool IsMine() const
\r
335 return ::IsMine(scriptPubKey);
\r
338 int64 GetCredit() const
\r
340 if (!MoneyRange(nValue))
\r
341 throw runtime_error("CTxOut::GetCredit() : value out of range");
\r
347 friend bool operator==(const CTxOut& a, const CTxOut& b)
\r
349 return (a.nValue == b.nValue &&
\r
350 a.scriptPubKey == b.scriptPubKey);
\r
353 friend bool operator!=(const CTxOut& a, const CTxOut& b)
\r
358 string ToString() const
\r
360 if (scriptPubKey.size() < 6)
\r
361 return "CTxOut(error)";
\r
362 return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,24).c_str());
\r
367 printf("%s\n", ToString().c_str());
\r
375 // The basic transaction that is broadcasted on the network and contained in
\r
376 // blocks. A transaction can contain multiple inputs and outputs.
\r
383 vector<CTxOut> vout;
\r
384 unsigned int nLockTime;
\r
392 IMPLEMENT_SERIALIZE
\r
394 READWRITE(this->nVersion);
\r
395 nVersion = this->nVersion;
\r
398 READWRITE(nLockTime);
\r
409 bool IsNull() const
\r
411 return (vin.empty() && vout.empty());
\r
414 uint256 GetHash() const
\r
416 return SerializeHash(*this);
\r
419 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
\r
421 // Time based nLockTime implemented in 0.1.6
\r
422 if (nLockTime == 0)
\r
424 if (nBlockHeight == 0)
\r
425 nBlockHeight = nBestHeight;
\r
426 if (nBlockTime == 0)
\r
427 nBlockTime = GetAdjustedTime();
\r
428 if ((int64)nLockTime < (nLockTime < 500000000 ? (int64)nBlockHeight : nBlockTime))
\r
430 foreach(const CTxIn& txin, vin)
\r
431 if (!txin.IsFinal())
\r
436 bool IsNewerThan(const CTransaction& old) const
\r
438 if (vin.size() != old.vin.size())
\r
440 for (int i = 0; i < vin.size(); i++)
\r
441 if (vin[i].prevout != old.vin[i].prevout)
\r
444 bool fNewer = false;
\r
445 unsigned int nLowest = UINT_MAX;
\r
446 for (int i = 0; i < vin.size(); i++)
\r
448 if (vin[i].nSequence != old.vin[i].nSequence)
\r
450 if (vin[i].nSequence <= nLowest)
\r
453 nLowest = vin[i].nSequence;
\r
455 if (old.vin[i].nSequence < nLowest)
\r
458 nLowest = old.vin[i].nSequence;
\r
465 bool IsCoinBase() const
\r
467 return (vin.size() == 1 && vin[0].prevout.IsNull());
\r
470 bool CheckTransaction() const
\r
472 // Basic checks that don't depend on any context
\r
473 if (vin.empty() || vout.empty())
\r
474 return error("CTransaction::CheckTransaction() : vin or vout empty");
\r
477 if (::GetSerializeSize(*this, SER_DISK) > MAX_SIZE)
\r
478 return error("CTransaction::CheckTransaction() : size limits failed");
\r
480 // Check for negative or overflow output values
\r
481 int64 nValueOut = 0;
\r
482 foreach(const CTxOut& txout, vout)
\r
484 if (txout.nValue < 0)
\r
485 return error("CTransaction::CheckTransaction() : txout.nValue negative");
\r
486 if (txout.nValue > MAX_MONEY)
\r
487 return error("CTransaction::CheckTransaction() : txout.nValue too high");
\r
488 nValueOut += txout.nValue;
\r
489 if (!MoneyRange(nValueOut))
\r
490 return error("CTransaction::CheckTransaction() : txout total out of range");
\r
495 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
\r
496 return error("CTransaction::CheckTransaction() : coinbase script size");
\r
500 foreach(const CTxIn& txin, vin)
\r
501 if (txin.prevout.IsNull())
\r
502 return error("CTransaction::CheckTransaction() : prevout is null");
\r
508 bool IsMine() const
\r
510 foreach(const CTxOut& txout, vout)
\r
511 if (txout.IsMine())
\r
516 int64 GetDebit() const
\r
519 foreach(const CTxIn& txin, vin)
\r
521 nDebit += txin.GetDebit();
\r
522 if (!MoneyRange(nDebit))
\r
523 throw runtime_error("CTransaction::GetDebit() : value out of range");
\r
528 int64 GetCredit() const
\r
531 foreach(const CTxOut& txout, vout)
\r
533 nCredit += txout.GetCredit();
\r
534 if (!MoneyRange(nCredit))
\r
535 throw runtime_error("CTransaction::GetCredit() : value out of range");
\r
540 int64 GetValueOut() const
\r
542 int64 nValueOut = 0;
\r
543 foreach(const CTxOut& txout, vout)
\r
545 nValueOut += txout.nValue;
\r
546 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
\r
547 throw runtime_error("CTransaction::GetValueOut() : value out of range");
\r
552 int64 GetMinFee(unsigned int nBlockSize=1) const
\r
554 // Base fee is 1 cent per kilobyte
\r
555 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);
\r
556 int64 nMinFee = (1 + (int64)nBytes / 1000) * CENT;
\r
558 // Transactions under 60K are free as long as block size is under 80K
\r
559 // (about 27,000bc if made of 50bc inputs)
\r
560 if (nBytes < 60000 && nBlockSize < 80000)
\r
563 // Transactions under 3K are free as long as block size is under 200K
\r
564 if (nBytes < 3000 && nBlockSize < 200000)
\r
567 // To limit dust spam, require a 0.01 fee if any output is less than 0.01
\r
568 if (nMinFee < CENT)
\r
569 foreach(const CTxOut& txout, vout)
\r
570 if (txout.nValue < CENT)
\r
578 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
\r
580 CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");
\r
582 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
\r
584 // Read transaction
\r
585 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
\r
586 return error("CTransaction::ReadFromDisk() : fseek failed");
\r
589 // Return file pointer
\r
592 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
\r
593 return error("CTransaction::ReadFromDisk() : second fseek failed");
\r
594 *pfileRet = filein.release();
\r
600 friend bool operator==(const CTransaction& a, const CTransaction& b)
\r
602 return (a.nVersion == b.nVersion &&
\r
604 a.vout == b.vout &&
\r
605 a.nLockTime == b.nLockTime);
\r
608 friend bool operator!=(const CTransaction& a, const CTransaction& b)
\r
614 string ToString() const
\r
617 str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
\r
618 GetHash().ToString().substr(0,6).c_str(),
\r
623 for (int i = 0; i < vin.size(); i++)
\r
624 str += " " + vin[i].ToString() + "\n";
\r
625 for (int i = 0; i < vout.size(); i++)
\r
626 str += " " + vout[i].ToString() + "\n";
\r
632 printf("%s", ToString().c_str());
\r
637 bool DisconnectInputs(CTxDB& txdb);
\r
638 bool ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
\r
639 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee=0);
\r
640 bool ClientConnectInputs();
\r
642 bool AcceptTransaction(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
\r
644 bool AcceptTransaction(bool fCheckInputs=true, bool* pfMissingInputs=NULL)
\r
647 return AcceptTransaction(txdb, fCheckInputs, pfMissingInputs);
\r
651 bool AddToMemoryPool();
\r
653 bool RemoveFromMemoryPool();
\r
661 // A transaction with a merkle branch linking it to the block chain
\r
663 class CMerkleTx : public CTransaction
\r
667 vector<uint256> vMerkleBranch;
\r
671 mutable bool fMerkleVerified;
\r
672 mutable bool fGetCreditCached;
\r
673 mutable int64 nGetCreditCached;
\r
681 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
\r
690 fMerkleVerified = false;
\r
691 fGetCreditCached = false;
\r
692 nGetCreditCached = 0;
\r
695 IMPLEMENT_SERIALIZE
\r
697 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
\r
698 nVersion = this->nVersion;
\r
699 READWRITE(hashBlock);
\r
700 READWRITE(vMerkleBranch);
\r
704 int64 GetCredit(bool fUseCache=false) const
\r
706 // Must wait until coinbase is safely deep enough in the chain before valuing it
\r
707 if (IsCoinBase() && GetBlocksToMaturity() > 0)
\r
710 // GetBalance can assume transactions in mapWallet won't change
\r
711 if (fUseCache && fGetCreditCached)
\r
712 return nGetCreditCached;
\r
713 nGetCreditCached = CTransaction::GetCredit();
\r
714 fGetCreditCached = true;
\r
715 return nGetCreditCached;
\r
719 int SetMerkleBranch(const CBlock* pblock=NULL);
\r
720 int GetDepthInMainChain(int& nHeightRet) const;
\r
721 int GetDepthInMainChain() const { int nHeight; return GetDepthInMainChain(nHeight); }
\r
722 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
\r
723 int GetBlocksToMaturity() const;
\r
724 bool AcceptTransaction(CTxDB& txdb, bool fCheckInputs=true);
\r
725 bool AcceptTransaction() { CTxDB txdb("r"); return AcceptTransaction(txdb); }
\r
732 // A transaction with a bunch of additional info that only the owner cares
\r
733 // about. It includes any unrecorded transactions needed to link it back
\r
734 // to the block chain.
\r
736 class CWalletTx : public CMerkleTx
\r
739 vector<CMerkleTx> vtxPrev;
\r
740 map<string, string> mapValue;
\r
741 vector<pair<string, string> > vOrderForm;
\r
742 unsigned int fTimeReceivedIsTxTime;
\r
743 unsigned int nTimeReceived; // time received by this node
\r
746 //// probably need to sign the order info so know it came from payer
\r
748 // memory only UI hints
\r
749 mutable unsigned int nTimeDisplayed;
\r
750 mutable int nLinesDisplayed;
\r
758 CWalletTx(const CMerkleTx& txIn) : CMerkleTx(txIn)
\r
763 CWalletTx(const CTransaction& txIn) : CMerkleTx(txIn)
\r
770 fTimeReceivedIsTxTime = false;
\r
774 nTimeDisplayed = 0;
\r
775 nLinesDisplayed = 0;
\r
778 IMPLEMENT_SERIALIZE
\r
780 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion, ser_action);
\r
781 nVersion = this->nVersion;
\r
782 READWRITE(vtxPrev);
\r
783 READWRITE(mapValue);
\r
784 READWRITE(vOrderForm);
\r
785 READWRITE(fTimeReceivedIsTxTime);
\r
786 READWRITE(nTimeReceived);
\r
787 READWRITE(fFromMe);
\r
793 return CWalletDB().WriteTx(GetHash(), *this);
\r
797 int64 GetTxTime() const;
\r
798 int GetRequestCount() const;
\r
800 void AddSupportingTransactions(CTxDB& txdb);
\r
802 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
\r
803 bool AcceptWalletTransaction() { CTxDB txdb("r"); return AcceptWalletTransaction(txdb); }
\r
805 void RelayWalletTransaction(CTxDB& txdb);
\r
806 void RelayWalletTransaction() { CTxDB txdb("r"); RelayWalletTransaction(txdb); }
\r
813 // A txdb record that contains the disk location of a transaction and the
\r
814 // locations of transactions that spend its outputs. vSpent is really only
\r
815 // used as a flag, but having the location is very helpful for debugging.
\r
821 vector<CDiskTxPos> vSpent;
\r
828 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
\r
831 vSpent.resize(nOutputs);
\r
834 IMPLEMENT_SERIALIZE
\r
836 if (!(nType & SER_GETHASH))
\r
837 READWRITE(nVersion);
\r
850 return pos.IsNull();
\r
853 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
\r
855 if (a.pos != b.pos || a.vSpent.size() != b.vSpent.size())
\r
857 for (int i = 0; i < a.vSpent.size(); i++)
\r
858 if (a.vSpent[i] != b.vSpent[i])
\r
863 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
\r
874 // Nodes collect new transactions into a block, hash them into a hash tree,
\r
875 // and scan through nonce values to make the block's hash satisfy proof-of-work
\r
876 // requirements. When they solve the proof-of-work, they broadcast the block
\r
877 // to everyone and the block is added to the block chain. The first transaction
\r
878 // in the block is a special one that creates a new coin owned by the creator
\r
881 // Blocks are appended to blk0001.dat files on disk. Their location on disk
\r
882 // is indexed by CBlockIndex objects in memory.
\r
889 uint256 hashPrevBlock;
\r
890 uint256 hashMerkleRoot;
\r
891 unsigned int nTime;
\r
892 unsigned int nBits;
\r
893 unsigned int nNonce;
\r
895 // network and disk
\r
896 vector<CTransaction> vtx;
\r
899 mutable vector<uint256> vMerkleTree;
\r
907 IMPLEMENT_SERIALIZE
\r
909 READWRITE(this->nVersion);
\r
910 nVersion = this->nVersion;
\r
911 READWRITE(hashPrevBlock);
\r
912 READWRITE(hashMerkleRoot);
\r
917 // ConnectBlock depends on vtx being last so it can calculate offset
\r
918 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
\r
921 const_cast<CBlock*>(this)->vtx.clear();
\r
928 hashMerkleRoot = 0;
\r
933 vMerkleTree.clear();
\r
936 bool IsNull() const
\r
938 return (nBits == 0);
\r
941 uint256 GetHash() const
\r
943 return Hash(BEGIN(nVersion), END(nNonce));
\r
946 int64 GetBlockTime() const
\r
948 return (int64)nTime;
\r
952 uint256 BuildMerkleTree() const
\r
954 vMerkleTree.clear();
\r
955 foreach(const CTransaction& tx, vtx)
\r
956 vMerkleTree.push_back(tx.GetHash());
\r
958 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
\r
960 for (int i = 0; i < nSize; i += 2)
\r
962 int i2 = min(i+1, nSize-1);
\r
963 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
\r
964 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
\r
968 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
\r
971 vector<uint256> GetMerkleBranch(int nIndex) const
\r
973 if (vMerkleTree.empty())
\r
975 vector<uint256> vMerkleBranch;
\r
977 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
\r
979 int i = min(nIndex^1, nSize-1);
\r
980 vMerkleBranch.push_back(vMerkleTree[j+i]);
\r
984 return vMerkleBranch;
\r
987 static uint256 CheckMerkleBranch(uint256 hash, const vector<uint256>& vMerkleBranch, int nIndex)
\r
991 foreach(const uint256& otherside, vMerkleBranch)
\r
994 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
\r
996 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
\r
1003 bool WriteToDisk(bool fWriteTransactions, unsigned int& nFileRet, unsigned int& nBlockPosRet)
\r
1005 // Open history file to append
\r
1006 CAutoFile fileout = AppendBlockFile(nFileRet);
\r
1008 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
\r
1009 if (!fWriteTransactions)
\r
1010 fileout.nType |= SER_BLOCKHEADERONLY;
\r
1012 // Write index header
\r
1013 unsigned int nSize = fileout.GetSerializeSize(*this);
\r
1014 fileout << FLATDATA(pchMessageStart) << nSize;
\r
1017 nBlockPosRet = ftell(fileout);
\r
1018 if (nBlockPosRet == -1)
\r
1019 return error("CBlock::WriteToDisk() : ftell failed");
\r
1022 // Flush stdio buffers and commit to disk before returning
\r
1024 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
\r
1027 _commit(_fileno(fileout));
\r
1029 fsync(fileno(fileout));
\r
1036 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
\r
1040 // Open history file to read
\r
1041 CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");
\r
1043 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
\r
1044 if (!fReadTransactions)
\r
1045 filein.nType |= SER_BLOCKHEADERONLY;
\r
1050 // Check the header
\r
1051 if (!CheckProofOfWork(GetHash(), nBits))
\r
1052 return error("CBlock::ReadFromDisk() : errors in block header");
\r
1059 void print() const
\r
1061 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
\r
1062 GetHash().ToString().substr(0,20).c_str(),
\r
1064 hashPrevBlock.ToString().substr(0,20).c_str(),
\r
1065 hashMerkleRoot.ToString().substr(0,6).c_str(),
\r
1066 nTime, nBits, nNonce,
\r
1068 for (int i = 0; i < vtx.size(); i++)
\r
1073 printf(" vMerkleTree: ");
\r
1074 for (int i = 0; i < vMerkleTree.size(); i++)
\r
1075 printf("%s ", vMerkleTree[i].ToString().substr(0,6).c_str());
\r
1080 int64 GetBlockValue(int nHeight, int64 nFees) const;
\r
1081 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
\r
1082 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
\r
1083 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
\r
1084 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
\r
1085 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
\r
1086 bool CheckBlock() const;
\r
1087 bool AcceptBlock();
\r
1096 // The block chain is a tree shaped structure starting with the
\r
1097 // genesis block at the root, with each block potentially having multiple
\r
1098 // candidates to be the next block. pprev and pnext link a path through the
\r
1099 // main/longest chain. A blockindex may have multiple pprev pointing back
\r
1100 // to it, but pnext will only point forward to the longest branch, or will
\r
1101 // be null if the block is not part of the longest chain.
\r
1106 const uint256* phashBlock;
\r
1107 CBlockIndex* pprev;
\r
1108 CBlockIndex* pnext;
\r
1109 unsigned int nFile;
\r
1110 unsigned int nBlockPos;
\r
1112 CBigNum bnChainWork;
\r
1116 uint256 hashMerkleRoot;
\r
1117 unsigned int nTime;
\r
1118 unsigned int nBits;
\r
1119 unsigned int nNonce;
\r
1124 phashBlock = NULL;
\r
1133 hashMerkleRoot = 0;
\r
1139 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
\r
1141 phashBlock = NULL;
\r
1145 nBlockPos = nBlockPosIn;
\r
1149 nVersion = block.nVersion;
\r
1150 hashMerkleRoot = block.hashMerkleRoot;
\r
1151 nTime = block.nTime;
\r
1152 nBits = block.nBits;
\r
1153 nNonce = block.nNonce;
\r
1156 uint256 GetBlockHash() const
\r
1158 return *phashBlock;
\r
1161 int64 GetBlockTime() const
\r
1163 return (int64)nTime;
\r
1166 CBigNum GetBlockWork() const
\r
1168 if (CBigNum().SetCompact(nBits) <= 0)
\r
1170 return (CBigNum(1)<<256) / (CBigNum().SetCompact(nBits)+1);
\r
1173 bool IsInMainChain() const
\r
1175 return (pnext || this == pindexBest);
\r
1178 bool CheckIndex() const
\r
1180 return CheckProofOfWork(GetBlockHash(), nBits);
\r
1183 bool EraseBlockFromDisk()
\r
1185 // Open history file
\r
1186 CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");
\r
1190 // Overwrite with empty null block
\r
1198 enum { nMedianTimeSpan=11 };
\r
1200 int64 GetMedianTimePast() const
\r
1202 int64 pmedian[nMedianTimeSpan];
\r
1203 int64* pbegin = &pmedian[nMedianTimeSpan];
\r
1204 int64* pend = &pmedian[nMedianTimeSpan];
\r
1206 const CBlockIndex* pindex = this;
\r
1207 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
\r
1208 *(--pbegin) = pindex->GetBlockTime();
\r
1210 sort(pbegin, pend);
\r
1211 return pbegin[(pend - pbegin)/2];
\r
1214 int64 GetMedianTime() const
\r
1216 const CBlockIndex* pindex = this;
\r
1217 for (int i = 0; i < nMedianTimeSpan/2; i++)
\r
1219 if (!pindex->pnext)
\r
1220 return GetBlockTime();
\r
1221 pindex = pindex->pnext;
\r
1223 return pindex->GetMedianTimePast();
\r
1228 string ToString() const
\r
1230 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
\r
1231 pprev, pnext, nFile, nBlockPos, nHeight,
\r
1232 hashMerkleRoot.ToString().substr(0,6).c_str(),
\r
1233 GetBlockHash().ToString().substr(0,20).c_str());
\r
1236 void print() const
\r
1238 printf("%s\n", ToString().c_str());
\r
1245 // Used to marshal pointers into hashes for db storage.
\r
1247 class CDiskBlockIndex : public CBlockIndex
\r
1259 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
\r
1261 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
\r
1262 hashNext = (pnext ? pnext->GetBlockHash() : 0);
\r
1265 IMPLEMENT_SERIALIZE
\r
1267 if (!(nType & SER_GETHASH))
\r
1268 READWRITE(nVersion);
\r
1270 READWRITE(hashNext);
\r
1272 READWRITE(nBlockPos);
\r
1273 READWRITE(nHeight);
\r
1276 READWRITE(this->nVersion);
\r
1277 READWRITE(hashPrev);
\r
1278 READWRITE(hashMerkleRoot);
\r
1281 READWRITE(nNonce);
\r
1284 uint256 GetBlockHash() const
\r
1287 block.nVersion = nVersion;
\r
1288 block.hashPrevBlock = hashPrev;
\r
1289 block.hashMerkleRoot = hashMerkleRoot;
\r
1290 block.nTime = nTime;
\r
1291 block.nBits = nBits;
\r
1292 block.nNonce = nNonce;
\r
1293 return block.GetHash();
\r
1297 string ToString() const
\r
1299 string str = "CDiskBlockIndex(";
\r
1300 str += CBlockIndex::ToString();
\r
1301 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
\r
1302 GetBlockHash().ToString().c_str(),
\r
1303 hashPrev.ToString().substr(0,20).c_str(),
\r
1304 hashNext.ToString().substr(0,20).c_str());
\r
1308 void print() const
\r
1310 printf("%s\n", ToString().c_str());
\r
1322 // Describes a place in the block chain to another node such that if the
\r
1323 // other node doesn't have the same branch, it can find a recent common trunk.
\r
1324 // The further back it is, the further before the fork it may be.
\r
1326 class CBlockLocator
\r
1329 vector<uint256> vHave;
\r
1336 explicit CBlockLocator(const CBlockIndex* pindex)
\r
1341 explicit CBlockLocator(uint256 hashBlock)
\r
1343 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
\r
1344 if (mi != mapBlockIndex.end())
\r
1345 Set((*mi).second);
\r
1348 IMPLEMENT_SERIALIZE
\r
1350 if (!(nType & SER_GETHASH))
\r
1351 READWRITE(nVersion);
\r
1355 void Set(const CBlockIndex* pindex)
\r
1361 vHave.push_back(pindex->GetBlockHash());
\r
1363 // Exponentially larger steps back
\r
1364 for (int i = 0; pindex && i < nStep; i++)
\r
1365 pindex = pindex->pprev;
\r
1366 if (vHave.size() > 10)
\r
1369 vHave.push_back(hashGenesisBlock);
\r
1372 int GetDistanceBack()
\r
1374 // Retrace how far back it was in the sender's branch
\r
1375 int nDistance = 0;
\r
1377 foreach(const uint256& hash, vHave)
\r
1379 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
\r
1380 if (mi != mapBlockIndex.end())
\r
1382 CBlockIndex* pindex = (*mi).second;
\r
1383 if (pindex->IsInMainChain())
\r
1386 nDistance += nStep;
\r
1387 if (nDistance > 10)
\r
1393 CBlockIndex* GetBlockIndex()
\r
1395 // Find the first block the caller has in the main chain
\r
1396 foreach(const uint256& hash, vHave)
\r
1398 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
\r
1399 if (mi != mapBlockIndex.end())
\r
1401 CBlockIndex* pindex = (*mi).second;
\r
1402 if (pindex->IsInMainChain())
\r
1406 return pindexGenesisBlock;
\r
1409 uint256 GetBlockHash()
\r
1411 // Find the first block the caller has in the main chain
\r
1412 foreach(const uint256& hash, vHave)
\r
1414 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
\r
1415 if (mi != mapBlockIndex.end())
\r
1417 CBlockIndex* pindex = (*mi).second;
\r
1418 if (pindex->IsInMainChain())
\r
1422 return hashGenesisBlock;
\r
1427 CBlockIndex* pindex = GetBlockIndex();
\r
1430 return pindex->nHeight;
\r
1440 // Private key that includes an expiration date in case it never gets used.
\r
1445 CPrivKey vchPrivKey;
\r
1446 int64 nTimeCreated;
\r
1447 int64 nTimeExpires;
\r
1448 string strComment;
\r
1449 //// todo: add something to note what created it (user, getnewaddress, change)
\r
1450 //// maybe should have a map<string, string> property map
\r
1452 CWalletKey(int64 nTimeExpiresIn=0)
\r
1454 nTimeCreated = (nTimeExpiresIn ? GetTime() : 0);
\r
1455 nTimeExpires = nTimeExpiresIn;
\r
1458 IMPLEMENT_SERIALIZE
\r
1460 if (!(nType & SER_GETHASH))
\r
1461 READWRITE(nVersion);
\r
1462 READWRITE(vchPrivKey);
\r
1463 READWRITE(nTimeCreated);
\r
1464 READWRITE(nTimeExpires);
\r
1465 READWRITE(strComment);
\r
1475 // Alert messages are broadcast as a vector of signed data. Unserializing may
\r
1476 // not read the entire buffer if the alert is for a newer version, but older
\r
1477 // versions can still relay the original data.
\r
1479 class CUnsignedAlert
\r
1483 int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
\r
1484 int64 nExpiration;
\r
1487 set<int> setCancel;
\r
1488 int nMinVer; // lowest version inclusive
\r
1489 int nMaxVer; // highest version inclusive
\r
1490 set<string> setSubVer; // empty matches all
\r
1494 string strComment;
\r
1495 string strStatusBar;
\r
1496 string strRPCError;
\r
1498 IMPLEMENT_SERIALIZE
\r
1500 READWRITE(this->nVersion);
\r
1501 nVersion = this->nVersion;
\r
1502 READWRITE(nRelayUntil);
\r
1503 READWRITE(nExpiration);
\r
1505 READWRITE(nCancel);
\r
1506 READWRITE(setCancel);
\r
1507 READWRITE(nMinVer);
\r
1508 READWRITE(nMaxVer);
\r
1509 READWRITE(setSubVer);
\r
1510 READWRITE(nPriority);
\r
1512 READWRITE(strComment);
\r
1513 READWRITE(strStatusBar);
\r
1514 READWRITE(strRPCError);
\r
1524 setCancel.clear();
\r
1527 setSubVer.clear();
\r
1530 strComment.clear();
\r
1531 strStatusBar.clear();
\r
1532 strRPCError.clear();
\r
1535 string ToString() const
\r
1537 string strSetCancel;
\r
1538 foreach(int n, setCancel)
\r
1539 strSetCancel += strprintf("%d ", n);
\r
1540 string strSetSubVer;
\r
1541 foreach(string str, setSubVer)
\r
1542 strSetSubVer += "\"" + str + "\" ";
\r
1545 " nVersion = %d\n"
\r
1546 " nRelayUntil = %"PRI64d"\n"
\r
1547 " nExpiration = %"PRI64d"\n"
\r
1550 " setCancel = %s\n"
\r
1553 " setSubVer = %s\n"
\r
1554 " nPriority = %d\n"
\r
1555 " strComment = \"%s\"\n"
\r
1556 " strStatusBar = \"%s\"\n"
\r
1557 " strRPCError = \"%s\"\n"
\r
1564 strSetCancel.c_str(),
\r
1567 strSetSubVer.c_str(),
\r
1569 strComment.c_str(),
\r
1570 strStatusBar.c_str(),
\r
1571 strRPCError.c_str());
\r
1574 void print() const
\r
1576 printf("%s", ToString().c_str());
\r
1580 class CAlert : public CUnsignedAlert
\r
1583 vector<unsigned char> vchMsg;
\r
1584 vector<unsigned char> vchSig;
\r
1591 IMPLEMENT_SERIALIZE
\r
1593 READWRITE(vchMsg);
\r
1594 READWRITE(vchSig);
\r
1599 CUnsignedAlert::SetNull();
\r
1604 bool IsNull() const
\r
1606 return (nExpiration == 0);
\r
1609 uint256 GetHash() const
\r
1611 return SerializeHash(*this);
\r
1614 bool IsInEffect() const
\r
1616 return (GetAdjustedTime() < nExpiration);
\r
1619 bool Cancels(const CAlert& alert) const
\r
1621 if (!IsInEffect())
\r
1623 return (alert.nID <= nCancel || setCancel.count(alert.nID));
\r
1626 bool AppliesTo(int nVersion, string strSubVerIn) const
\r
1628 return (IsInEffect() &&
\r
1629 nMinVer <= nVersion && nVersion <= nMaxVer &&
\r
1630 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
\r
1633 bool AppliesToMe() const
\r
1635 return AppliesTo(VERSION, ::pszSubVer);
\r
1638 bool RelayTo(CNode* pnode) const
\r
1640 if (!IsInEffect())
\r
1642 // returns true if wasn't already contained in the set
\r
1643 if (pnode->setKnown.insert(GetHash()).second)
\r
1645 if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
\r
1647 GetAdjustedTime() < nRelayUntil)
\r
1649 pnode->PushMessage("alert", *this);
\r
1656 bool CheckSignature()
\r
1659 if (!key.SetPubKey(ParseHex("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284")))
\r
1660 return error("CAlert::CheckSignature() : SetPubKey failed");
\r
1661 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
\r
1662 return error("CAlert::CheckSignature() : verify signature failed");
\r
1664 // Now unserialize the data
\r
1665 CDataStream sMsg(vchMsg);
\r
1666 sMsg >> *(CUnsignedAlert*)this;
\r
1670 bool ProcessAlert();
\r
1682 extern map<uint256, CTransaction> mapTransactions;
\r
1683 extern map<uint256, CWalletTx> mapWallet;
\r
1684 extern vector<uint256> vWalletUpdated;
\r
1685 extern CCriticalSection cs_mapWallet;
\r
1686 extern map<vector<unsigned char>, CPrivKey> mapKeys;
\r
1687 extern map<uint160, vector<unsigned char> > mapPubKeys;
\r
1688 extern CCriticalSection cs_mapKeys;
\r
1689 extern CKey keyUser;
\r