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 void ReacceptWalletTransactions();
73 bool LoadBlockIndex(bool fAllowNew=true);
74 void PrintBlockTree();
75 bool ProcessMessages(CNode* pfrom);
76 bool ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv);
77 bool SendMessages(CNode* pto, bool fSendTrickle);
79 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
80 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
81 bool BroadcastTransaction(CWalletTx& wtxNew);
82 string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
83 string SendMoneyToBitcoinAddress(string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
84 void GenerateBitcoins(bool fGenerate);
85 void ThreadBitcoinMiner(void* parg);
86 CBlock* CreateNewBlock(CReserveKey& reservekey);
87 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce, int64& nPrevTime);
88 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
89 bool CheckWork(CBlock* pblock, CReserveKey& reservekey);
91 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
92 bool IsInitialBlockDownload();
93 string GetWarnings(string strFor);
110 unsigned int nBlockPos;
118 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
121 nBlockPos = nBlockPosIn;
125 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
126 void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
127 bool IsNull() const { return (nFile == -1); }
129 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
131 return (a.nFile == b.nFile &&
132 a.nBlockPos == b.nBlockPos &&
133 a.nTxPos == b.nTxPos);
136 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
141 string ToString() const
144 return strprintf("null");
146 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
151 printf("%s", ToString().c_str());
164 CInPoint() { SetNull(); }
165 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
166 void SetNull() { ptx = NULL; n = -1; }
167 bool IsNull() const { return (ptx == NULL && n == -1); }
179 COutPoint() { SetNull(); }
180 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
181 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
182 void SetNull() { hash = 0; n = -1; }
183 bool IsNull() const { return (hash == 0 && n == -1); }
185 friend bool operator<(const COutPoint& a, const COutPoint& b)
187 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
190 friend bool operator==(const COutPoint& a, const COutPoint& b)
192 return (a.hash == b.hash && a.n == b.n);
195 friend bool operator!=(const COutPoint& a, const COutPoint& b)
200 string ToString() const
202 return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,10).c_str(), n);
207 printf("%s\n", ToString().c_str());
215 // An input of a transaction. It contains the location of the previous
216 // transaction's output that it claims and a signature that matches the
217 // output's public key.
224 unsigned int nSequence;
228 nSequence = UINT_MAX;
231 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
234 scriptSig = scriptSigIn;
235 nSequence = nSequenceIn;
238 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
240 prevout = COutPoint(hashPrevTx, nOut);
241 scriptSig = scriptSigIn;
242 nSequence = nSequenceIn;
248 READWRITE(scriptSig);
249 READWRITE(nSequence);
254 return (nSequence == UINT_MAX);
257 friend bool operator==(const CTxIn& a, const CTxIn& b)
259 return (a.prevout == b.prevout &&
260 a.scriptSig == b.scriptSig &&
261 a.nSequence == b.nSequence);
264 friend bool operator!=(const CTxIn& a, const CTxIn& b)
269 string ToString() const
272 str += strprintf("CTxIn(");
273 str += prevout.ToString();
274 if (prevout.IsNull())
275 str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
277 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
278 if (nSequence != UINT_MAX)
279 str += strprintf(", nSequence=%u", nSequence);
286 printf("%s\n", ToString().c_str());
290 int64 GetDebit() const;
297 // An output of a transaction. It contains the public key that the next input
298 // must be able to sign with to claim it.
304 CScript scriptPubKey;
311 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
314 scriptPubKey = scriptPubKeyIn;
320 READWRITE(scriptPubKey);
326 scriptPubKey.clear();
331 return (nValue == -1);
334 uint256 GetHash() const
336 return SerializeHash(*this);
341 return ::IsMine(scriptPubKey);
344 int64 GetCredit() const
346 if (!MoneyRange(nValue))
347 throw runtime_error("CTxOut::GetCredit() : value out of range");
348 return (IsMine() ? nValue : 0);
351 bool IsChange() const
353 // On a debit transaction, a txout that's mine but isn't in the address book is change
354 vector<unsigned char> vchPubKey;
355 if (ExtractPubKey(scriptPubKey, true, vchPubKey))
356 CRITICAL_BLOCK(cs_mapAddressBook)
357 if (!mapAddressBook.count(PubKeyToAddress(vchPubKey)))
362 int64 GetChange() const
364 if (!MoneyRange(nValue))
365 throw runtime_error("CTxOut::GetChange() : value out of range");
366 return (IsChange() ? nValue : 0);
369 friend bool operator==(const CTxOut& a, const CTxOut& b)
371 return (a.nValue == b.nValue &&
372 a.scriptPubKey == b.scriptPubKey);
375 friend bool operator!=(const CTxOut& a, const CTxOut& b)
380 string ToString() const
382 if (scriptPubKey.size() < 6)
383 return "CTxOut(error)";
384 return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,30).c_str());
389 printf("%s\n", ToString().c_str());
397 // The basic transaction that is broadcasted on the network and contained in
398 // blocks. A transaction can contain multiple inputs and outputs.
406 unsigned int nLockTime;
416 READWRITE(this->nVersion);
417 nVersion = this->nVersion;
420 READWRITE(nLockTime);
433 return (vin.empty() && vout.empty());
436 uint256 GetHash() const
438 return SerializeHash(*this);
441 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
443 // Time based nLockTime implemented in 0.1.6
446 if (nBlockHeight == 0)
447 nBlockHeight = nBestHeight;
449 nBlockTime = GetAdjustedTime();
450 if ((int64)nLockTime < (nLockTime < 500000000 ? (int64)nBlockHeight : nBlockTime))
452 foreach(const CTxIn& txin, vin)
458 bool IsNewerThan(const CTransaction& old) const
460 if (vin.size() != old.vin.size())
462 for (int i = 0; i < vin.size(); i++)
463 if (vin[i].prevout != old.vin[i].prevout)
467 unsigned int nLowest = UINT_MAX;
468 for (int i = 0; i < vin.size(); i++)
470 if (vin[i].nSequence != old.vin[i].nSequence)
472 if (vin[i].nSequence <= nLowest)
475 nLowest = vin[i].nSequence;
477 if (old.vin[i].nSequence < nLowest)
480 nLowest = old.vin[i].nSequence;
487 bool IsCoinBase() const
489 return (vin.size() == 1 && vin[0].prevout.IsNull());
492 int GetSigOpCount() const
495 foreach(const CTxIn& txin, vin)
496 n += txin.scriptSig.GetSigOpCount();
497 foreach(const CTxOut& txout, vout)
498 n += txout.scriptPubKey.GetSigOpCount();
502 bool IsStandard() const
504 foreach(const CTxIn& txin, vin)
505 if (!txin.scriptSig.IsPushOnly())
506 return error("nonstandard txin: %s", txin.scriptSig.ToString().c_str());
507 foreach(const CTxOut& txout, vout)
508 if (!::IsStandard(txout.scriptPubKey))
509 return error("nonstandard txout: %s", txout.scriptPubKey.ToString().c_str());
515 foreach(const CTxOut& txout, vout)
521 bool IsFromMe() const
523 return (GetDebit() > 0);
526 int64 GetDebit() const
529 foreach(const CTxIn& txin, vin)
531 nDebit += txin.GetDebit();
532 if (!MoneyRange(nDebit))
533 throw runtime_error("CTransaction::GetDebit() : value out of range");
538 int64 GetCredit() const
541 foreach(const CTxOut& txout, vout)
543 nCredit += txout.GetCredit();
544 if (!MoneyRange(nCredit))
545 throw runtime_error("CTransaction::GetCredit() : value out of range");
550 int64 GetChange() const
555 foreach(const CTxOut& txout, vout)
557 nChange += txout.GetChange();
558 if (!MoneyRange(nChange))
559 throw runtime_error("CTransaction::GetChange() : value out of range");
564 int64 GetValueOut() const
567 foreach(const CTxOut& txout, vout)
569 nValueOut += txout.nValue;
570 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
571 throw runtime_error("CTransaction::GetValueOut() : value out of range");
576 int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=true) const
578 // Base fee is 1 cent per kilobyte
579 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);
580 unsigned int nNewBlockSize = nBlockSize + nBytes;
581 int64 nMinFee = (1 + (int64)nBytes / 1000) * CENT;
587 // Transactions under 10K are free
588 // (about 4500bc if made of 50bc inputs)
594 // Free transaction area
595 if (nNewBlockSize < 27000)
600 // To limit dust spam, require a 0.01 fee if any output is less than 0.01
602 foreach(const CTxOut& txout, vout)
603 if (txout.nValue < CENT)
606 // Raise the price as the block approaches full
607 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
609 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
611 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
614 if (!MoneyRange(nMinFee))
620 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
622 CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");
624 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
627 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
628 return error("CTransaction::ReadFromDisk() : fseek failed");
631 // Return file pointer
634 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
635 return error("CTransaction::ReadFromDisk() : second fseek failed");
636 *pfileRet = filein.release();
641 friend bool operator==(const CTransaction& a, const CTransaction& b)
643 return (a.nVersion == b.nVersion &&
646 a.nLockTime == b.nLockTime);
649 friend bool operator!=(const CTransaction& a, const CTransaction& b)
655 string ToString() const
658 str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
659 GetHash().ToString().substr(0,10).c_str(),
664 for (int i = 0; i < vin.size(); i++)
665 str += " " + vin[i].ToString() + "\n";
666 for (int i = 0; i < vout.size(); i++)
667 str += " " + vout[i].ToString() + "\n";
673 printf("%s", ToString().c_str());
677 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
678 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
679 bool ReadFromDisk(COutPoint prevout);
680 bool DisconnectInputs(CTxDB& txdb);
681 bool ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
682 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee=0);
683 bool ClientConnectInputs();
684 bool CheckTransaction() const;
685 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
686 bool AcceptToMemoryPool(bool fCheckInputs=true, bool* pfMissingInputs=NULL)
689 return AcceptToMemoryPool(txdb, fCheckInputs, pfMissingInputs);
692 bool AddToMemoryPoolUnchecked();
694 bool RemoveFromMemoryPool();
702 // A transaction with a merkle branch linking it to the block chain
704 class CMerkleTx : public CTransaction
708 vector<uint256> vMerkleBranch;
712 mutable char fMerkleVerified;
720 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
729 fMerkleVerified = false;
734 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
735 nVersion = this->nVersion;
736 READWRITE(hashBlock);
737 READWRITE(vMerkleBranch);
742 int SetMerkleBranch(const CBlock* pblock=NULL);
743 int GetDepthInMainChain(int& nHeightRet) const;
744 int GetDepthInMainChain() const { int nHeight; return GetDepthInMainChain(nHeight); }
745 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
746 int GetBlocksToMaturity() const;
747 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
748 bool AcceptToMemoryPool() { CTxDB txdb("r"); return AcceptToMemoryPool(txdb); }
755 // A transaction with a bunch of additional info that only the owner cares
756 // about. It includes any unrecorded transactions needed to link it back
757 // to the block chain.
759 class CWalletTx : public CMerkleTx
762 vector<CMerkleTx> vtxPrev;
763 map<string, string> mapValue;
764 vector<pair<string, string> > vOrderForm;
765 unsigned int fTimeReceivedIsTxTime;
766 unsigned int nTimeReceived; // time received by this node
769 string strFromAccount;
772 mutable char fDebitCached;
773 mutable char fCreditCached;
774 mutable char fChangeCached;
775 mutable int64 nDebitCached;
776 mutable int64 nCreditCached;
777 mutable int64 nChangeCached;
779 // memory only UI hints
780 mutable unsigned int nTimeDisplayed;
781 mutable int nLinesDisplayed;
782 mutable char fConfirmedDisplayed;
790 CWalletTx(const CMerkleTx& txIn) : CMerkleTx(txIn)
795 CWalletTx(const CTransaction& txIn) : CMerkleTx(txIn)
805 fTimeReceivedIsTxTime = false;
809 strFromAccount.clear();
810 fDebitCached = false;
811 fCreditCached = false;
812 fChangeCached = false;
818 fConfirmedDisplayed = false;
823 CWalletTx* pthis = const_cast<CWalletTx*>(this);
826 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion, ser_action);
829 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
831 pthis->strFromAccount = pthis->mapValue["fromaccount"];
832 pthis->mapValue.erase("fromaccount");
833 pthis->mapValue.erase("version");
835 READWRITE(vOrderForm);
836 READWRITE(fTimeReceivedIsTxTime);
837 READWRITE(nTimeReceived);
842 int64 GetDebit() const
848 nDebitCached = CTransaction::GetDebit();
853 int64 GetCredit(bool fUseCache=true) const
855 // Must wait until coinbase is safely deep enough in the chain before valuing it
856 if (IsCoinBase() && GetBlocksToMaturity() > 0)
859 // GetBalance can assume transactions in mapWallet won't change
860 if (fUseCache && fCreditCached)
861 return nCreditCached;
862 nCreditCached = CTransaction::GetCredit();
863 fCreditCached = true;
864 return nCreditCached;
867 int64 GetChange() const
870 return nChangeCached;
871 nChangeCached = CTransaction::GetChange();
872 fChangeCached = true;
873 return nChangeCached;
876 void GetAccountAmounts(string strAccount, const set<CScript>& setPubKey,
877 int64& nGenerated, int64& nReceived, int64& nSent, int64& nFee) const
879 nGenerated = nReceived = nSent = nFee = 0;
881 // Generated blocks count to account ""
884 if (strAccount == "" && GetBlocksToMaturity() == 0)
885 nGenerated = GetCredit();
890 foreach(const CTxOut& txout, vout)
891 if (setPubKey.count(txout.scriptPubKey))
892 nReceived += txout.nValue;
895 if (strFromAccount == strAccount)
897 int64 nDebit = GetDebit();
900 int64 nValueOut = GetValueOut();
901 nFee = nDebit - nValueOut;
902 nSent = nValueOut - GetChange();
907 bool IsFromMe() const
909 return (GetDebit() > 0);
912 bool IsConfirmed() const
914 // Quick answer in most cases
917 if (GetDepthInMainChain() >= 1)
919 if (!IsFromMe()) // using wtx's cached debit
922 // If no confirmations but it's from us, we can still
923 // consider it confirmed if all dependencies are confirmed
924 map<uint256, const CMerkleTx*> mapPrev;
925 vector<const CMerkleTx*> vWorkQueue;
926 vWorkQueue.reserve(vtxPrev.size()+1);
927 vWorkQueue.push_back(this);
928 for (int i = 0; i < vWorkQueue.size(); i++)
930 const CMerkleTx* ptx = vWorkQueue[i];
934 if (ptx->GetDepthInMainChain() >= 1)
936 if (!ptx->IsFromMe())
940 foreach(const CMerkleTx& tx, vtxPrev)
941 mapPrev[tx.GetHash()] = &tx;
943 foreach(const CTxIn& txin, ptx->vin)
945 if (!mapPrev.count(txin.prevout.hash))
947 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
955 return CWalletDB().WriteTx(GetHash(), *this);
959 int64 GetTxTime() const;
960 int GetRequestCount() const;
962 void AddSupportingTransactions(CTxDB& txdb);
964 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
965 bool AcceptWalletTransaction() { CTxDB txdb("r"); return AcceptWalletTransaction(txdb); }
967 void RelayWalletTransaction(CTxDB& txdb);
968 void RelayWalletTransaction() { CTxDB txdb("r"); RelayWalletTransaction(txdb); }
975 // A txdb record that contains the disk location of a transaction and the
976 // locations of transactions that spend its outputs. vSpent is really only
977 // used as a flag, but having the location is very helpful for debugging.
983 vector<CDiskTxPos> vSpent;
990 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
993 vSpent.resize(nOutputs);
998 if (!(nType & SER_GETHASH))
1012 return pos.IsNull();
1015 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
1017 return (a.pos == b.pos &&
1018 a.vSpent == b.vSpent);
1021 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
1032 // Nodes collect new transactions into a block, hash them into a hash tree,
1033 // and scan through nonce values to make the block's hash satisfy proof-of-work
1034 // requirements. When they solve the proof-of-work, they broadcast the block
1035 // to everyone and the block is added to the block chain. The first transaction
1036 // in the block is a special one that creates a new coin owned by the creator
1039 // Blocks are appended to blk0001.dat files on disk. Their location on disk
1040 // is indexed by CBlockIndex objects in memory.
1047 uint256 hashPrevBlock;
1048 uint256 hashMerkleRoot;
1051 unsigned int nNonce;
1054 vector<CTransaction> vtx;
1057 mutable vector<uint256> vMerkleTree;
1067 READWRITE(this->nVersion);
1068 nVersion = this->nVersion;
1069 READWRITE(hashPrevBlock);
1070 READWRITE(hashMerkleRoot);
1075 // ConnectBlock depends on vtx being last so it can calculate offset
1076 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
1079 const_cast<CBlock*>(this)->vtx.clear();
1091 vMerkleTree.clear();
1096 return (nBits == 0);
1099 uint256 GetHash() const
1101 return Hash(BEGIN(nVersion), END(nNonce));
1104 int64 GetBlockTime() const
1106 return (int64)nTime;
1109 int GetSigOpCount() const
1112 foreach(const CTransaction& tx, vtx)
1113 n += tx.GetSigOpCount();
1118 uint256 BuildMerkleTree() const
1120 vMerkleTree.clear();
1121 foreach(const CTransaction& tx, vtx)
1122 vMerkleTree.push_back(tx.GetHash());
1124 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1126 for (int i = 0; i < nSize; i += 2)
1128 int i2 = min(i+1, nSize-1);
1129 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
1130 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
1134 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
1137 vector<uint256> GetMerkleBranch(int nIndex) const
1139 if (vMerkleTree.empty())
1141 vector<uint256> vMerkleBranch;
1143 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1145 int i = min(nIndex^1, nSize-1);
1146 vMerkleBranch.push_back(vMerkleTree[j+i]);
1150 return vMerkleBranch;
1153 static uint256 CheckMerkleBranch(uint256 hash, const vector<uint256>& vMerkleBranch, int nIndex)
1157 foreach(const uint256& otherside, vMerkleBranch)
1160 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
1162 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
1169 bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
1171 // Open history file to append
1172 CAutoFile fileout = AppendBlockFile(nFileRet);
1174 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
1176 // Write index header
1177 unsigned int nSize = fileout.GetSerializeSize(*this);
1178 fileout << FLATDATA(pchMessageStart) << nSize;
1181 nBlockPosRet = ftell(fileout);
1182 if (nBlockPosRet == -1)
1183 return error("CBlock::WriteToDisk() : ftell failed");
1186 // Flush stdio buffers and commit to disk before returning
1188 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
1191 _commit(_fileno(fileout));
1193 fsync(fileno(fileout));
1200 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
1204 // Open history file to read
1205 CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");
1207 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1208 if (!fReadTransactions)
1209 filein.nType |= SER_BLOCKHEADERONLY;
1215 if (!CheckProofOfWork(GetHash(), nBits))
1216 return error("CBlock::ReadFromDisk() : errors in block header");
1225 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
1226 GetHash().ToString().substr(0,20).c_str(),
1228 hashPrevBlock.ToString().substr(0,20).c_str(),
1229 hashMerkleRoot.ToString().substr(0,10).c_str(),
1230 nTime, nBits, nNonce,
1232 for (int i = 0; i < vtx.size(); i++)
1237 printf(" vMerkleTree: ");
1238 for (int i = 0; i < vMerkleTree.size(); i++)
1239 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1244 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1245 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1246 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1247 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1248 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1249 bool CheckBlock() const;
1259 // The block chain is a tree shaped structure starting with the
1260 // genesis block at the root, with each block potentially having multiple
1261 // candidates to be the next block. pprev and pnext link a path through the
1262 // main/longest chain. A blockindex may have multiple pprev pointing back
1263 // to it, but pnext will only point forward to the longest branch, or will
1264 // be null if the block is not part of the longest chain.
1269 const uint256* phashBlock;
1273 unsigned int nBlockPos;
1275 CBigNum bnChainWork;
1279 uint256 hashMerkleRoot;
1282 unsigned int nNonce;
1302 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1308 nBlockPos = nBlockPosIn;
1312 nVersion = block.nVersion;
1313 hashMerkleRoot = block.hashMerkleRoot;
1314 nTime = block.nTime;
1315 nBits = block.nBits;
1316 nNonce = block.nNonce;
1319 CBlock GetBlockHeader() const
1322 block.nVersion = nVersion;
1324 block.hashPrevBlock = pprev->GetBlockHash();
1325 block.hashMerkleRoot = hashMerkleRoot;
1326 block.nTime = nTime;
1327 block.nBits = nBits;
1328 block.nNonce = nNonce;
1332 uint256 GetBlockHash() const
1337 int64 GetBlockTime() const
1339 return (int64)nTime;
1342 CBigNum GetBlockWork() const
1345 bnTarget.SetCompact(nBits);
1348 return (CBigNum(1)<<256) / (bnTarget+1);
1351 bool IsInMainChain() const
1353 return (pnext || this == pindexBest);
1356 bool CheckIndex() const
1358 return CheckProofOfWork(GetBlockHash(), nBits);
1361 bool EraseBlockFromDisk()
1363 // Open history file
1364 CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");
1368 // Overwrite with empty null block
1376 enum { nMedianTimeSpan=11 };
1378 int64 GetMedianTimePast() const
1380 int64 pmedian[nMedianTimeSpan];
1381 int64* pbegin = &pmedian[nMedianTimeSpan];
1382 int64* pend = &pmedian[nMedianTimeSpan];
1384 const CBlockIndex* pindex = this;
1385 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1386 *(--pbegin) = pindex->GetBlockTime();
1389 return pbegin[(pend - pbegin)/2];
1392 int64 GetMedianTime() const
1394 const CBlockIndex* pindex = this;
1395 for (int i = 0; i < nMedianTimeSpan/2; i++)
1398 return GetBlockTime();
1399 pindex = pindex->pnext;
1401 return pindex->GetMedianTimePast();
1406 string ToString() const
1408 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
1409 pprev, pnext, nFile, nBlockPos, nHeight,
1410 hashMerkleRoot.ToString().substr(0,10).c_str(),
1411 GetBlockHash().ToString().substr(0,20).c_str());
1416 printf("%s\n", ToString().c_str());
1423 // Used to marshal pointers into hashes for db storage.
1425 class CDiskBlockIndex : public CBlockIndex
1437 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1439 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1440 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1445 if (!(nType & SER_GETHASH))
1446 READWRITE(nVersion);
1448 READWRITE(hashNext);
1450 READWRITE(nBlockPos);
1454 READWRITE(this->nVersion);
1455 READWRITE(hashPrev);
1456 READWRITE(hashMerkleRoot);
1462 uint256 GetBlockHash() const
1465 block.nVersion = nVersion;
1466 block.hashPrevBlock = hashPrev;
1467 block.hashMerkleRoot = hashMerkleRoot;
1468 block.nTime = nTime;
1469 block.nBits = nBits;
1470 block.nNonce = nNonce;
1471 return block.GetHash();
1475 string ToString() const
1477 string str = "CDiskBlockIndex(";
1478 str += CBlockIndex::ToString();
1479 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1480 GetBlockHash().ToString().c_str(),
1481 hashPrev.ToString().substr(0,20).c_str(),
1482 hashNext.ToString().substr(0,20).c_str());
1488 printf("%s\n", ToString().c_str());
1500 // Describes a place in the block chain to another node such that if the
1501 // other node doesn't have the same branch, it can find a recent common trunk.
1502 // The further back it is, the further before the fork it may be.
1507 vector<uint256> vHave;
1514 explicit CBlockLocator(const CBlockIndex* pindex)
1519 explicit CBlockLocator(uint256 hashBlock)
1521 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1522 if (mi != mapBlockIndex.end())
1528 if (!(nType & SER_GETHASH))
1529 READWRITE(nVersion);
1540 return vHave.empty();
1543 void Set(const CBlockIndex* pindex)
1549 vHave.push_back(pindex->GetBlockHash());
1551 // Exponentially larger steps back
1552 for (int i = 0; pindex && i < nStep; i++)
1553 pindex = pindex->pprev;
1554 if (vHave.size() > 10)
1557 vHave.push_back(hashGenesisBlock);
1560 int GetDistanceBack()
1562 // Retrace how far back it was in the sender's branch
1565 foreach(const uint256& hash, vHave)
1567 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1568 if (mi != mapBlockIndex.end())
1570 CBlockIndex* pindex = (*mi).second;
1571 if (pindex->IsInMainChain())
1581 CBlockIndex* GetBlockIndex()
1583 // Find the first block the caller has in the main chain
1584 foreach(const uint256& hash, vHave)
1586 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1587 if (mi != mapBlockIndex.end())
1589 CBlockIndex* pindex = (*mi).second;
1590 if (pindex->IsInMainChain())
1594 return pindexGenesisBlock;
1597 uint256 GetBlockHash()
1599 // Find the first block the caller has in the main chain
1600 foreach(const uint256& hash, vHave)
1602 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1603 if (mi != mapBlockIndex.end())
1605 CBlockIndex* pindex = (*mi).second;
1606 if (pindex->IsInMainChain())
1610 return hashGenesisBlock;
1615 CBlockIndex* pindex = GetBlockIndex();
1618 return pindex->nHeight;
1628 // Private key that includes an expiration date in case it never gets used.
1633 CPrivKey vchPrivKey;
1637 //// todo: add something to note what created it (user, getnewaddress, change)
1638 //// maybe should have a map<string, string> property map
1640 CWalletKey(int64 nExpires=0)
1642 nTimeCreated = (nExpires ? GetTime() : 0);
1643 nTimeExpires = nExpires;
1648 if (!(nType & SER_GETHASH))
1649 READWRITE(nVersion);
1650 READWRITE(vchPrivKey);
1651 READWRITE(nTimeCreated);
1652 READWRITE(nTimeExpires);
1653 READWRITE(strComment);
1663 // Account information.
1664 // Stored in wallet with key "acc"+string account name
1669 vector<unsigned char> vchPubKey;
1683 if (!(nType & SER_GETHASH))
1684 READWRITE(nVersion);
1685 READWRITE(vchPubKey);
1692 // Internal transfers.
1693 // Database key is acentry<account><counter>
1695 class CAccountingEntry
1700 string strOtherAccount;
1712 strOtherAccount.clear();
1718 if (!(nType & SER_GETHASH))
1719 READWRITE(nVersion);
1720 READWRITE(nCreditDebit);
1722 READWRITE(strOtherAccount);
1723 READWRITE(strComment);
1736 // Alert messages are broadcast as a vector of signed data. Unserializing may
1737 // not read the entire buffer if the alert is for a newer version, but older
1738 // versions can still relay the original data.
1740 class CUnsignedAlert
1744 int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
1749 int nMinVer; // lowest version inclusive
1750 int nMaxVer; // highest version inclusive
1751 set<string> setSubVer; // empty matches all
1756 string strStatusBar;
1761 READWRITE(this->nVersion);
1762 nVersion = this->nVersion;
1763 READWRITE(nRelayUntil);
1764 READWRITE(nExpiration);
1767 READWRITE(setCancel);
1770 READWRITE(setSubVer);
1771 READWRITE(nPriority);
1773 READWRITE(strComment);
1774 READWRITE(strStatusBar);
1775 READWRITE(strRPCError);
1792 strStatusBar.clear();
1793 strRPCError.clear();
1796 string ToString() const
1798 string strSetCancel;
1799 foreach(int n, setCancel)
1800 strSetCancel += strprintf("%d ", n);
1801 string strSetSubVer;
1802 foreach(string str, setSubVer)
1803 strSetSubVer += "\"" + str + "\" ";
1807 " nRelayUntil = %"PRI64d"\n"
1808 " nExpiration = %"PRI64d"\n"
1816 " strComment = \"%s\"\n"
1817 " strStatusBar = \"%s\"\n"
1818 " strRPCError = \"%s\"\n"
1825 strSetCancel.c_str(),
1828 strSetSubVer.c_str(),
1831 strStatusBar.c_str(),
1832 strRPCError.c_str());
1837 printf("%s", ToString().c_str());
1841 class CAlert : public CUnsignedAlert
1844 vector<unsigned char> vchMsg;
1845 vector<unsigned char> vchSig;
1860 CUnsignedAlert::SetNull();
1867 return (nExpiration == 0);
1870 uint256 GetHash() const
1872 return SerializeHash(*this);
1875 bool IsInEffect() const
1877 return (GetAdjustedTime() < nExpiration);
1880 bool Cancels(const CAlert& alert) const
1883 return false; // this was a no-op before 31403
1884 return (alert.nID <= nCancel || setCancel.count(alert.nID));
1887 bool AppliesTo(int nVersion, string strSubVerIn) const
1889 return (IsInEffect() &&
1890 nMinVer <= nVersion && nVersion <= nMaxVer &&
1891 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1894 bool AppliesToMe() const
1896 return AppliesTo(VERSION, ::pszSubVer);
1899 bool RelayTo(CNode* pnode) const
1903 // returns true if wasn't already contained in the set
1904 if (pnode->setKnown.insert(GetHash()).second)
1906 if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
1908 GetAdjustedTime() < nRelayUntil)
1910 pnode->PushMessage("alert", *this);
1917 bool CheckSignature()
1920 if (!key.SetPubKey(ParseHex("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284")))
1921 return error("CAlert::CheckSignature() : SetPubKey failed");
1922 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
1923 return error("CAlert::CheckSignature() : verify signature failed");
1925 // Now unserialize the data
1926 CDataStream sMsg(vchMsg);
1927 sMsg >> *(CUnsignedAlert*)this;
1931 bool ProcessAlert();
1943 extern map<uint256, CTransaction> mapTransactions;
1944 extern map<uint256, CWalletTx> mapWallet;
1945 extern vector<uint256> vWalletUpdated;
1946 extern CCriticalSection cs_mapWallet;
1947 extern map<vector<unsigned char>, CPrivKey> mapKeys;
1948 extern map<uint160, vector<unsigned char> > mapPubKeys;
1949 extern CCriticalSection cs_mapKeys;
1950 extern CKey keyUser;