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 MIN_TX_FEE = 50000;
23 static const int64 MAX_MONEY = 21000000 * COIN;
24 inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
25 static const int COINBASE_MATURITY = 100;
27 static const int fHaveUPnP = true;
29 static const int fHaveUPnP = false;
37 extern CCriticalSection cs_main;
38 extern map<uint256, CBlockIndex*> mapBlockIndex;
39 extern uint256 hashGenesisBlock;
40 extern CBigNum bnProofOfWorkLimit;
41 extern CBlockIndex* pindexGenesisBlock;
42 extern int nBestHeight;
43 extern CBigNum bnBestChainWork;
44 extern CBigNum bnBestInvalidWork;
45 extern uint256 hashBestChain;
46 extern CBlockIndex* pindexBest;
47 extern unsigned int nTransactionsUpdated;
48 extern map<uint256, int> mapRequestCount;
49 extern CCriticalSection cs_mapRequestCount;
50 extern map<string, string> mapAddressBook;
51 extern CCriticalSection cs_mapAddressBook;
52 extern vector<unsigned char> vchDefaultKey;
53 extern double dHashesPerSec;
54 extern int64 nHPSTimerStart;
57 extern int fGenerateBitcoins;
58 extern int64 nTransactionFee;
59 extern CAddress addrIncoming;
60 extern int fLimitProcessors;
61 extern int nLimitProcessors;
62 extern int fMinimizeToTray;
63 extern int fMinimizeOnClose;
72 bool CheckDiskSpace(uint64 nAdditionalBytes=0);
73 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
74 FILE* AppendBlockFile(unsigned int& nFileRet);
75 bool AddKey(const CKey& key);
76 vector<unsigned char> GenerateNewKey();
77 bool AddToWallet(const CWalletTx& wtxIn);
78 void WalletUpdateSpent(const COutPoint& prevout);
79 int ScanForWalletTransactions(CBlockIndex* pindexStart);
80 void ReacceptWalletTransactions();
81 bool LoadBlockIndex(bool fAllowNew=true);
82 void PrintBlockTree();
83 bool ProcessMessages(CNode* pfrom);
84 bool ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv);
85 bool SendMessages(CNode* pto, bool fSendTrickle);
87 bool CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
88 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
89 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
90 bool BroadcastTransaction(CWalletTx& wtxNew);
91 string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
92 string SendMoneyToBitcoinAddress(string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
93 void GenerateBitcoins(bool fGenerate);
94 void ThreadBitcoinMiner(void* parg);
95 CBlock* CreateNewBlock(CReserveKey& reservekey);
96 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce, int64& nPrevTime);
97 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
98 bool CheckWork(CBlock* pblock, CReserveKey& reservekey);
100 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
101 bool IsInitialBlockDownload();
102 string GetWarnings(string strFor);
119 unsigned int nBlockPos;
127 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
130 nBlockPos = nBlockPosIn;
134 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
135 void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
136 bool IsNull() const { return (nFile == -1); }
138 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
140 return (a.nFile == b.nFile &&
141 a.nBlockPos == b.nBlockPos &&
142 a.nTxPos == b.nTxPos);
145 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
150 string ToString() const
153 return strprintf("null");
155 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
160 printf("%s", ToString().c_str());
173 CInPoint() { SetNull(); }
174 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
175 void SetNull() { ptx = NULL; n = -1; }
176 bool IsNull() const { return (ptx == NULL && n == -1); }
188 COutPoint() { SetNull(); }
189 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
190 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
191 void SetNull() { hash = 0; n = -1; }
192 bool IsNull() const { return (hash == 0 && n == -1); }
194 friend bool operator<(const COutPoint& a, const COutPoint& b)
196 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
199 friend bool operator==(const COutPoint& a, const COutPoint& b)
201 return (a.hash == b.hash && a.n == b.n);
204 friend bool operator!=(const COutPoint& a, const COutPoint& b)
209 string ToString() const
211 return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,10).c_str(), n);
216 printf("%s\n", ToString().c_str());
224 // An input of a transaction. It contains the location of the previous
225 // transaction's output that it claims and a signature that matches the
226 // output's public key.
233 unsigned int nSequence;
237 nSequence = UINT_MAX;
240 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
243 scriptSig = scriptSigIn;
244 nSequence = nSequenceIn;
247 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
249 prevout = COutPoint(hashPrevTx, nOut);
250 scriptSig = scriptSigIn;
251 nSequence = nSequenceIn;
257 READWRITE(scriptSig);
258 READWRITE(nSequence);
263 return (nSequence == UINT_MAX);
266 friend bool operator==(const CTxIn& a, const CTxIn& b)
268 return (a.prevout == b.prevout &&
269 a.scriptSig == b.scriptSig &&
270 a.nSequence == b.nSequence);
273 friend bool operator!=(const CTxIn& a, const CTxIn& b)
278 string ToString() const
281 str += strprintf("CTxIn(");
282 str += prevout.ToString();
283 if (prevout.IsNull())
284 str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
286 str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
287 if (nSequence != UINT_MAX)
288 str += strprintf(", nSequence=%u", nSequence);
295 printf("%s\n", ToString().c_str());
299 int64 GetDebit() const;
306 // An output of a transaction. It contains the public key that the next input
307 // must be able to sign with to claim it.
313 CScript scriptPubKey;
320 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
323 scriptPubKey = scriptPubKeyIn;
329 READWRITE(scriptPubKey);
335 scriptPubKey.clear();
340 return (nValue == -1);
343 uint256 GetHash() const
345 return SerializeHash(*this);
350 return ::IsMine(scriptPubKey);
353 int64 GetCredit() const
355 if (!MoneyRange(nValue))
356 throw runtime_error("CTxOut::GetCredit() : value out of range");
357 return (IsMine() ? nValue : 0);
360 bool IsChange() const
362 // On a debit transaction, a txout that's mine but isn't in the address book is change
363 vector<unsigned char> vchPubKey;
364 if (ExtractPubKey(scriptPubKey, true, vchPubKey))
365 CRITICAL_BLOCK(cs_mapAddressBook)
366 if (!mapAddressBook.count(PubKeyToAddress(vchPubKey)))
371 int64 GetChange() const
373 if (!MoneyRange(nValue))
374 throw runtime_error("CTxOut::GetChange() : value out of range");
375 return (IsChange() ? nValue : 0);
378 friend bool operator==(const CTxOut& a, const CTxOut& b)
380 return (a.nValue == b.nValue &&
381 a.scriptPubKey == b.scriptPubKey);
384 friend bool operator!=(const CTxOut& a, const CTxOut& b)
389 string ToString() const
391 if (scriptPubKey.size() < 6)
392 return "CTxOut(error)";
393 return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,30).c_str());
398 printf("%s\n", ToString().c_str());
406 // The basic transaction that is broadcasted on the network and contained in
407 // blocks. A transaction can contain multiple inputs and outputs.
415 unsigned int nLockTime;
425 READWRITE(this->nVersion);
426 nVersion = this->nVersion;
429 READWRITE(nLockTime);
442 return (vin.empty() && vout.empty());
445 uint256 GetHash() const
447 return SerializeHash(*this);
450 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
452 // Time based nLockTime implemented in 0.1.6
455 if (nBlockHeight == 0)
456 nBlockHeight = nBestHeight;
458 nBlockTime = GetAdjustedTime();
459 if ((int64)nLockTime < (nLockTime < 500000000 ? (int64)nBlockHeight : nBlockTime))
461 foreach(const CTxIn& txin, vin)
467 bool IsNewerThan(const CTransaction& old) const
469 if (vin.size() != old.vin.size())
471 for (int i = 0; i < vin.size(); i++)
472 if (vin[i].prevout != old.vin[i].prevout)
476 unsigned int nLowest = UINT_MAX;
477 for (int i = 0; i < vin.size(); i++)
479 if (vin[i].nSequence != old.vin[i].nSequence)
481 if (vin[i].nSequence <= nLowest)
484 nLowest = vin[i].nSequence;
486 if (old.vin[i].nSequence < nLowest)
489 nLowest = old.vin[i].nSequence;
496 bool IsCoinBase() const
498 return (vin.size() == 1 && vin[0].prevout.IsNull());
501 int GetSigOpCount() const
504 foreach(const CTxIn& txin, vin)
505 n += txin.scriptSig.GetSigOpCount();
506 foreach(const CTxOut& txout, vout)
507 n += txout.scriptPubKey.GetSigOpCount();
511 bool IsStandard() const
513 foreach(const CTxIn& txin, vin)
514 if (!txin.scriptSig.IsPushOnly())
515 return error("nonstandard txin: %s", txin.scriptSig.ToString().c_str());
516 foreach(const CTxOut& txout, vout)
517 if (!::IsStandard(txout.scriptPubKey))
518 return error("nonstandard txout: %s", txout.scriptPubKey.ToString().c_str());
524 foreach(const CTxOut& txout, vout)
530 bool IsFromMe() const
532 return (GetDebit() > 0);
535 int64 GetDebit() const
538 foreach(const CTxIn& txin, vin)
540 nDebit += txin.GetDebit();
541 if (!MoneyRange(nDebit))
542 throw runtime_error("CTransaction::GetDebit() : value out of range");
547 int64 GetCredit() const
550 foreach(const CTxOut& txout, vout)
552 nCredit += txout.GetCredit();
553 if (!MoneyRange(nCredit))
554 throw runtime_error("CTransaction::GetCredit() : value out of range");
559 int64 GetChange() const
564 foreach(const CTxOut& txout, vout)
566 nChange += txout.GetChange();
567 if (!MoneyRange(nChange))
568 throw runtime_error("CTransaction::GetChange() : value out of range");
573 int64 GetValueOut() const
576 foreach(const CTxOut& txout, vout)
578 nValueOut += txout.nValue;
579 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
580 throw runtime_error("CTransaction::GetValueOut() : value out of range");
585 static bool AllowFree(double dPriority)
587 // Large (in bytes) low-priority (new, small-coin) transactions
589 return dPriority > COIN * 144 / 250;
592 int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=true) const
594 // Base fee is 1 cent per kilobyte
595 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);
596 unsigned int nNewBlockSize = nBlockSize + nBytes;
597 int64 nMinFee = (1 + (int64)nBytes / 1000) * MIN_TX_FEE;
603 // Transactions under 10K are free
604 // (about 4500bc if made of 50bc inputs)
610 // Free transaction area
611 if (nNewBlockSize < 27000)
616 // To limit dust spam, require MIN_TX_FEE if any output is less than 0.01
617 if (nMinFee < MIN_TX_FEE)
618 foreach(const CTxOut& txout, vout)
619 if (txout.nValue < CENT)
620 nMinFee = MIN_TX_FEE;
622 // Raise the price as the block approaches full
623 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
625 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
627 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
630 if (!MoneyRange(nMinFee))
636 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
638 CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");
640 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
643 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
644 return error("CTransaction::ReadFromDisk() : fseek failed");
647 // Return file pointer
650 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
651 return error("CTransaction::ReadFromDisk() : second fseek failed");
652 *pfileRet = filein.release();
657 friend bool operator==(const CTransaction& a, const CTransaction& b)
659 return (a.nVersion == b.nVersion &&
662 a.nLockTime == b.nLockTime);
665 friend bool operator!=(const CTransaction& a, const CTransaction& b)
671 string ToString() const
674 str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
675 GetHash().ToString().substr(0,10).c_str(),
680 for (int i = 0; i < vin.size(); i++)
681 str += " " + vin[i].ToString() + "\n";
682 for (int i = 0; i < vout.size(); i++)
683 str += " " + vout[i].ToString() + "\n";
689 printf("%s", ToString().c_str());
693 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
694 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
695 bool ReadFromDisk(COutPoint prevout);
696 bool DisconnectInputs(CTxDB& txdb);
697 bool ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
698 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee=0);
699 bool ClientConnectInputs();
700 bool CheckTransaction() const;
701 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
702 bool AcceptToMemoryPool(bool fCheckInputs=true, bool* pfMissingInputs=NULL)
705 return AcceptToMemoryPool(txdb, fCheckInputs, pfMissingInputs);
708 bool AddToMemoryPoolUnchecked();
710 bool RemoveFromMemoryPool();
718 // A transaction with a merkle branch linking it to the block chain
720 class CMerkleTx : public CTransaction
724 vector<uint256> vMerkleBranch;
728 mutable char fMerkleVerified;
736 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
745 fMerkleVerified = false;
751 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
752 nVersion = this->nVersion;
753 READWRITE(hashBlock);
754 READWRITE(vMerkleBranch);
759 int SetMerkleBranch(const CBlock* pblock=NULL);
760 int GetDepthInMainChain(int& nHeightRet) const;
761 int GetDepthInMainChain() const { int nHeight; return GetDepthInMainChain(nHeight); }
762 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
763 int GetBlocksToMaturity() const;
764 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
765 bool AcceptToMemoryPool() { CTxDB txdb("r"); return AcceptToMemoryPool(txdb); }
772 // A transaction with a bunch of additional info that only the owner cares
773 // about. It includes any unrecorded transactions needed to link it back
774 // to the block chain.
776 class CWalletTx : public CMerkleTx
779 vector<CMerkleTx> vtxPrev;
780 map<string, string> mapValue;
781 vector<pair<string, string> > vOrderForm;
782 unsigned int fTimeReceivedIsTxTime;
783 unsigned int nTimeReceived; // time received by this node
785 string strFromAccount;
786 vector<char> vfSpent;
789 mutable char fDebitCached;
790 mutable char fCreditCached;
791 mutable char fAvailableCreditCached;
792 mutable char fChangeCached;
793 mutable int64 nDebitCached;
794 mutable int64 nCreditCached;
795 mutable int64 nAvailableCreditCached;
796 mutable int64 nChangeCached;
798 // memory only UI hints
799 mutable unsigned int nTimeDisplayed;
800 mutable int nLinesDisplayed;
801 mutable char fConfirmedDisplayed;
809 CWalletTx(const CMerkleTx& txIn) : CMerkleTx(txIn)
814 CWalletTx(const CTransaction& txIn) : CMerkleTx(txIn)
824 fTimeReceivedIsTxTime = false;
827 strFromAccount.clear();
829 fDebitCached = false;
830 fCreditCached = false;
831 fAvailableCreditCached = false;
832 fChangeCached = false;
835 nAvailableCreditCached = 0;
839 fConfirmedDisplayed = false;
844 CWalletTx* pthis = const_cast<CWalletTx*>(this);
851 pthis->mapValue["fromaccount"] = pthis->strFromAccount;
854 foreach(char f, vfSpent)
856 str += (f ? '1' : '0');
860 pthis->mapValue["spent"] = str;
863 nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
866 READWRITE(vOrderForm);
867 READWRITE(fTimeReceivedIsTxTime);
868 READWRITE(nTimeReceived);
874 pthis->strFromAccount = pthis->mapValue["fromaccount"];
876 if (mapValue.count("spent"))
877 foreach(char c, pthis->mapValue["spent"])
878 pthis->vfSpent.push_back(c != '0');
880 pthis->vfSpent.assign(vout.size(), fSpent);
883 pthis->mapValue.erase("fromaccount");
884 pthis->mapValue.erase("version");
885 pthis->mapValue.erase("spent");
888 // marks certain txout's as spent
889 // returns true if any update took place
890 bool UpdateSpent(const vector<char>& vfNewSpent)
892 bool fReturn = false;
893 for (int i=0; i < vfNewSpent.size(); i++)
895 if (i == vfSpent.size())
898 if (vfNewSpent[i] && !vfSpent[i])
902 fAvailableCreditCached = false;
910 fCreditCached = false;
911 fAvailableCreditCached = false;
912 fDebitCached = false;
913 fChangeCached = false;
916 void MarkSpent(unsigned int nOut)
918 if (nOut >= vout.size())
919 throw runtime_error("CWalletTx::MarkSpent() : nOut out of range");
920 vfSpent.resize(vout.size());
923 vfSpent[nOut] = true;
924 fAvailableCreditCached = false;
928 bool IsSpent(unsigned int nOut) const
930 if (nOut >= vout.size())
931 throw runtime_error("CWalletTx::IsSpent() : nOut out of range");
932 if (nOut >= vfSpent.size())
934 return (!!vfSpent[nOut]);
937 int64 GetDebit() const
943 nDebitCached = CTransaction::GetDebit();
948 int64 GetCredit(bool fUseCache=true) const
950 // Must wait until coinbase is safely deep enough in the chain before valuing it
951 if (IsCoinBase() && GetBlocksToMaturity() > 0)
954 // GetBalance can assume transactions in mapWallet won't change
955 if (fUseCache && fCreditCached)
956 return nCreditCached;
957 nCreditCached = CTransaction::GetCredit();
958 fCreditCached = true;
959 return nCreditCached;
962 int64 GetAvailableCredit(bool fUseCache=true) const
964 // Must wait until coinbase is safely deep enough in the chain before valuing it
965 if (IsCoinBase() && GetBlocksToMaturity() > 0)
968 if (fUseCache && fAvailableCreditCached)
969 return nAvailableCreditCached;
972 for (int i = 0; i < vout.size(); i++)
976 const CTxOut &txout = vout[i];
977 nCredit += txout.GetCredit();
978 if (!MoneyRange(nCredit))
979 throw runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
983 nAvailableCreditCached = nCredit;
984 fAvailableCreditCached = true;
989 int64 GetChange() const
992 return nChangeCached;
993 nChangeCached = CTransaction::GetChange();
994 fChangeCached = true;
995 return nChangeCached;
998 void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, list<pair<string /* address */, int64> >& listReceived,
999 list<pair<string /* address */, int64> >& listSent, int64& nFee, string& strSentAccount) const;
1001 void GetAccountAmounts(const string& strAccount, int64& nGenerated, int64& nReceived,
1002 int64& nSent, int64& nFee) const;
1004 bool IsFromMe() const
1006 return (GetDebit() > 0);
1009 bool IsConfirmed() const
1011 // Quick answer in most cases
1014 if (GetDepthInMainChain() >= 1)
1016 if (!IsFromMe()) // using wtx's cached debit
1019 // If no confirmations but it's from us, we can still
1020 // consider it confirmed if all dependencies are confirmed
1021 map<uint256, const CMerkleTx*> mapPrev;
1022 vector<const CMerkleTx*> vWorkQueue;
1023 vWorkQueue.reserve(vtxPrev.size()+1);
1024 vWorkQueue.push_back(this);
1025 for (int i = 0; i < vWorkQueue.size(); i++)
1027 const CMerkleTx* ptx = vWorkQueue[i];
1029 if (!ptx->IsFinal())
1031 if (ptx->GetDepthInMainChain() >= 1)
1033 if (!ptx->IsFromMe())
1036 if (mapPrev.empty())
1037 foreach(const CMerkleTx& tx, vtxPrev)
1038 mapPrev[tx.GetHash()] = &tx;
1040 foreach(const CTxIn& txin, ptx->vin)
1042 if (!mapPrev.count(txin.prevout.hash))
1044 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
1052 return CWalletDB().WriteTx(GetHash(), *this);
1056 int64 GetTxTime() const;
1057 int GetRequestCount() const;
1059 void AddSupportingTransactions(CTxDB& txdb);
1061 bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
1062 bool AcceptWalletTransaction() { CTxDB txdb("r"); return AcceptWalletTransaction(txdb); }
1064 void RelayWalletTransaction(CTxDB& txdb);
1065 void RelayWalletTransaction() { CTxDB txdb("r"); RelayWalletTransaction(txdb); }
1072 // A txdb record that contains the disk location of a transaction and the
1073 // locations of transactions that spend its outputs. vSpent is really only
1074 // used as a flag, but having the location is very helpful for debugging.
1080 vector<CDiskTxPos> vSpent;
1087 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
1090 vSpent.resize(nOutputs);
1095 if (!(nType & SER_GETHASH))
1096 READWRITE(nVersion);
1109 return pos.IsNull();
1112 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
1114 return (a.pos == b.pos &&
1115 a.vSpent == b.vSpent);
1118 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
1122 int GetDepthInMainChain() const;
1130 // Nodes collect new transactions into a block, hash them into a hash tree,
1131 // and scan through nonce values to make the block's hash satisfy proof-of-work
1132 // requirements. When they solve the proof-of-work, they broadcast the block
1133 // to everyone and the block is added to the block chain. The first transaction
1134 // in the block is a special one that creates a new coin owned by the creator
1137 // Blocks are appended to blk0001.dat files on disk. Their location on disk
1138 // is indexed by CBlockIndex objects in memory.
1145 uint256 hashPrevBlock;
1146 uint256 hashMerkleRoot;
1149 unsigned int nNonce;
1152 vector<CTransaction> vtx;
1155 mutable vector<uint256> vMerkleTree;
1165 READWRITE(this->nVersion);
1166 nVersion = this->nVersion;
1167 READWRITE(hashPrevBlock);
1168 READWRITE(hashMerkleRoot);
1173 // ConnectBlock depends on vtx being last so it can calculate offset
1174 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
1177 const_cast<CBlock*>(this)->vtx.clear();
1189 vMerkleTree.clear();
1194 return (nBits == 0);
1197 uint256 GetHash() const
1199 return Hash(BEGIN(nVersion), END(nNonce));
1202 int64 GetBlockTime() const
1204 return (int64)nTime;
1207 int GetSigOpCount() const
1210 foreach(const CTransaction& tx, vtx)
1211 n += tx.GetSigOpCount();
1216 uint256 BuildMerkleTree() const
1218 vMerkleTree.clear();
1219 foreach(const CTransaction& tx, vtx)
1220 vMerkleTree.push_back(tx.GetHash());
1222 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1224 for (int i = 0; i < nSize; i += 2)
1226 int i2 = min(i+1, nSize-1);
1227 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
1228 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
1232 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
1235 vector<uint256> GetMerkleBranch(int nIndex) const
1237 if (vMerkleTree.empty())
1239 vector<uint256> vMerkleBranch;
1241 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1243 int i = min(nIndex^1, nSize-1);
1244 vMerkleBranch.push_back(vMerkleTree[j+i]);
1248 return vMerkleBranch;
1251 static uint256 CheckMerkleBranch(uint256 hash, const vector<uint256>& vMerkleBranch, int nIndex)
1255 foreach(const uint256& otherside, vMerkleBranch)
1258 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
1260 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
1267 bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
1269 // Open history file to append
1270 CAutoFile fileout = AppendBlockFile(nFileRet);
1272 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
1274 // Write index header
1275 unsigned int nSize = fileout.GetSerializeSize(*this);
1276 fileout << FLATDATA(pchMessageStart) << nSize;
1279 nBlockPosRet = ftell(fileout);
1280 if (nBlockPosRet == -1)
1281 return error("CBlock::WriteToDisk() : ftell failed");
1284 // Flush stdio buffers and commit to disk before returning
1286 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
1289 _commit(_fileno(fileout));
1291 fsync(fileno(fileout));
1298 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
1302 // Open history file to read
1303 CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");
1305 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1306 if (!fReadTransactions)
1307 filein.nType |= SER_BLOCKHEADERONLY;
1313 if (!CheckProofOfWork(GetHash(), nBits))
1314 return error("CBlock::ReadFromDisk() : errors in block header");
1323 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
1324 GetHash().ToString().substr(0,20).c_str(),
1326 hashPrevBlock.ToString().substr(0,20).c_str(),
1327 hashMerkleRoot.ToString().substr(0,10).c_str(),
1328 nTime, nBits, nNonce,
1330 for (int i = 0; i < vtx.size(); i++)
1335 printf(" vMerkleTree: ");
1336 for (int i = 0; i < vMerkleTree.size(); i++)
1337 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1342 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1343 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1344 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1345 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1346 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1347 bool CheckBlock() const;
1357 // The block chain is a tree shaped structure starting with the
1358 // genesis block at the root, with each block potentially having multiple
1359 // candidates to be the next block. pprev and pnext link a path through the
1360 // main/longest chain. A blockindex may have multiple pprev pointing back
1361 // to it, but pnext will only point forward to the longest branch, or will
1362 // be null if the block is not part of the longest chain.
1367 const uint256* phashBlock;
1371 unsigned int nBlockPos;
1373 CBigNum bnChainWork;
1377 uint256 hashMerkleRoot;
1380 unsigned int nNonce;
1400 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1406 nBlockPos = nBlockPosIn;
1410 nVersion = block.nVersion;
1411 hashMerkleRoot = block.hashMerkleRoot;
1412 nTime = block.nTime;
1413 nBits = block.nBits;
1414 nNonce = block.nNonce;
1417 CBlock GetBlockHeader() const
1420 block.nVersion = nVersion;
1422 block.hashPrevBlock = pprev->GetBlockHash();
1423 block.hashMerkleRoot = hashMerkleRoot;
1424 block.nTime = nTime;
1425 block.nBits = nBits;
1426 block.nNonce = nNonce;
1430 uint256 GetBlockHash() const
1435 int64 GetBlockTime() const
1437 return (int64)nTime;
1440 CBigNum GetBlockWork() const
1443 bnTarget.SetCompact(nBits);
1446 return (CBigNum(1)<<256) / (bnTarget+1);
1449 bool IsInMainChain() const
1451 return (pnext || this == pindexBest);
1454 bool CheckIndex() const
1456 return CheckProofOfWork(GetBlockHash(), nBits);
1459 bool EraseBlockFromDisk()
1461 // Open history file
1462 CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");
1466 // Overwrite with empty null block
1474 enum { nMedianTimeSpan=11 };
1476 int64 GetMedianTimePast() const
1478 int64 pmedian[nMedianTimeSpan];
1479 int64* pbegin = &pmedian[nMedianTimeSpan];
1480 int64* pend = &pmedian[nMedianTimeSpan];
1482 const CBlockIndex* pindex = this;
1483 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1484 *(--pbegin) = pindex->GetBlockTime();
1487 return pbegin[(pend - pbegin)/2];
1490 int64 GetMedianTime() const
1492 const CBlockIndex* pindex = this;
1493 for (int i = 0; i < nMedianTimeSpan/2; i++)
1496 return GetBlockTime();
1497 pindex = pindex->pnext;
1499 return pindex->GetMedianTimePast();
1504 string ToString() const
1506 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
1507 pprev, pnext, nFile, nBlockPos, nHeight,
1508 hashMerkleRoot.ToString().substr(0,10).c_str(),
1509 GetBlockHash().ToString().substr(0,20).c_str());
1514 printf("%s\n", ToString().c_str());
1521 // Used to marshal pointers into hashes for db storage.
1523 class CDiskBlockIndex : public CBlockIndex
1535 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1537 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1538 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1543 if (!(nType & SER_GETHASH))
1544 READWRITE(nVersion);
1546 READWRITE(hashNext);
1548 READWRITE(nBlockPos);
1552 READWRITE(this->nVersion);
1553 READWRITE(hashPrev);
1554 READWRITE(hashMerkleRoot);
1560 uint256 GetBlockHash() const
1563 block.nVersion = nVersion;
1564 block.hashPrevBlock = hashPrev;
1565 block.hashMerkleRoot = hashMerkleRoot;
1566 block.nTime = nTime;
1567 block.nBits = nBits;
1568 block.nNonce = nNonce;
1569 return block.GetHash();
1573 string ToString() const
1575 string str = "CDiskBlockIndex(";
1576 str += CBlockIndex::ToString();
1577 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1578 GetBlockHash().ToString().c_str(),
1579 hashPrev.ToString().substr(0,20).c_str(),
1580 hashNext.ToString().substr(0,20).c_str());
1586 printf("%s\n", ToString().c_str());
1598 // Describes a place in the block chain to another node such that if the
1599 // other node doesn't have the same branch, it can find a recent common trunk.
1600 // The further back it is, the further before the fork it may be.
1605 vector<uint256> vHave;
1612 explicit CBlockLocator(const CBlockIndex* pindex)
1617 explicit CBlockLocator(uint256 hashBlock)
1619 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1620 if (mi != mapBlockIndex.end())
1626 if (!(nType & SER_GETHASH))
1627 READWRITE(nVersion);
1638 return vHave.empty();
1641 void Set(const CBlockIndex* pindex)
1647 vHave.push_back(pindex->GetBlockHash());
1649 // Exponentially larger steps back
1650 for (int i = 0; pindex && i < nStep; i++)
1651 pindex = pindex->pprev;
1652 if (vHave.size() > 10)
1655 vHave.push_back(hashGenesisBlock);
1658 int GetDistanceBack()
1660 // Retrace how far back it was in the sender's branch
1663 foreach(const uint256& hash, vHave)
1665 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1666 if (mi != mapBlockIndex.end())
1668 CBlockIndex* pindex = (*mi).second;
1669 if (pindex->IsInMainChain())
1679 CBlockIndex* GetBlockIndex()
1681 // Find the first block the caller has in the main chain
1682 foreach(const uint256& hash, vHave)
1684 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1685 if (mi != mapBlockIndex.end())
1687 CBlockIndex* pindex = (*mi).second;
1688 if (pindex->IsInMainChain())
1692 return pindexGenesisBlock;
1695 uint256 GetBlockHash()
1697 // Find the first block the caller has in the main chain
1698 foreach(const uint256& hash, vHave)
1700 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1701 if (mi != mapBlockIndex.end())
1703 CBlockIndex* pindex = (*mi).second;
1704 if (pindex->IsInMainChain())
1708 return hashGenesisBlock;
1713 CBlockIndex* pindex = GetBlockIndex();
1716 return pindex->nHeight;
1726 // Private key that includes an expiration date in case it never gets used.
1731 CPrivKey vchPrivKey;
1735 //// todo: add something to note what created it (user, getnewaddress, change)
1736 //// maybe should have a map<string, string> property map
1738 CWalletKey(int64 nExpires=0)
1740 nTimeCreated = (nExpires ? GetTime() : 0);
1741 nTimeExpires = nExpires;
1746 if (!(nType & SER_GETHASH))
1747 READWRITE(nVersion);
1748 READWRITE(vchPrivKey);
1749 READWRITE(nTimeCreated);
1750 READWRITE(nTimeExpires);
1751 READWRITE(strComment);
1761 // Account information.
1762 // Stored in wallet with key "acc"+string account name
1767 vector<unsigned char> vchPubKey;
1781 if (!(nType & SER_GETHASH))
1782 READWRITE(nVersion);
1783 READWRITE(vchPubKey);
1790 // Internal transfers.
1791 // Database key is acentry<account><counter>
1793 class CAccountingEntry
1799 string strOtherAccount;
1812 strOtherAccount.clear();
1818 if (!(nType & SER_GETHASH))
1819 READWRITE(nVersion);
1820 // Note: strAccount is serialized as part of the key, not here.
1821 READWRITE(nCreditDebit);
1823 READWRITE(strOtherAccount);
1824 READWRITE(strComment);
1837 // Alerts are for notifying old versions if they become too obsolete and
1838 // need to upgrade. The message is displayed in the status bar.
1839 // Alert messages are broadcast as a vector of signed data. Unserializing may
1840 // not read the entire buffer if the alert is for a newer version, but older
1841 // versions can still relay the original data.
1843 class CUnsignedAlert
1847 int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
1852 int nMinVer; // lowest version inclusive
1853 int nMaxVer; // highest version inclusive
1854 set<string> setSubVer; // empty matches all
1859 string strStatusBar;
1864 READWRITE(this->nVersion);
1865 nVersion = this->nVersion;
1866 READWRITE(nRelayUntil);
1867 READWRITE(nExpiration);
1870 READWRITE(setCancel);
1873 READWRITE(setSubVer);
1874 READWRITE(nPriority);
1876 READWRITE(strComment);
1877 READWRITE(strStatusBar);
1878 READWRITE(strReserved);
1895 strStatusBar.clear();
1896 strReserved.clear();
1899 string ToString() const
1901 string strSetCancel;
1902 foreach(int n, setCancel)
1903 strSetCancel += strprintf("%d ", n);
1904 string strSetSubVer;
1905 foreach(string str, setSubVer)
1906 strSetSubVer += "\"" + str + "\" ";
1910 " nRelayUntil = %"PRI64d"\n"
1911 " nExpiration = %"PRI64d"\n"
1919 " strComment = \"%s\"\n"
1920 " strStatusBar = \"%s\"\n"
1927 strSetCancel.c_str(),
1930 strSetSubVer.c_str(),
1933 strStatusBar.c_str());
1938 printf("%s", ToString().c_str());
1942 class CAlert : public CUnsignedAlert
1945 vector<unsigned char> vchMsg;
1946 vector<unsigned char> vchSig;
1961 CUnsignedAlert::SetNull();
1968 return (nExpiration == 0);
1971 uint256 GetHash() const
1973 return SerializeHash(*this);
1976 bool IsInEffect() const
1978 return (GetAdjustedTime() < nExpiration);
1981 bool Cancels(const CAlert& alert) const
1984 return false; // this was a no-op before 31403
1985 return (alert.nID <= nCancel || setCancel.count(alert.nID));
1988 bool AppliesTo(int nVersion, string strSubVerIn) const
1990 return (IsInEffect() &&
1991 nMinVer <= nVersion && nVersion <= nMaxVer &&
1992 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1995 bool AppliesToMe() const
1997 return AppliesTo(VERSION, ::pszSubVer);
2000 bool RelayTo(CNode* pnode) const
2004 // returns true if wasn't already contained in the set
2005 if (pnode->setKnown.insert(GetHash()).second)
2007 if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
2009 GetAdjustedTime() < nRelayUntil)
2011 pnode->PushMessage("alert", *this);
2018 bool CheckSignature()
2021 if (!key.SetPubKey(ParseHex("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284")))
2022 return error("CAlert::CheckSignature() : SetPubKey failed");
2023 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
2024 return error("CAlert::CheckSignature() : verify signature failed");
2026 // Now unserialize the data
2027 CDataStream sMsg(vchMsg);
2028 sMsg >> *(CUnsignedAlert*)this;
2032 bool ProcessAlert();
2044 extern map<uint256, CTransaction> mapTransactions;
2045 extern map<uint256, CWalletTx> mapWallet;
2046 extern vector<uint256> vWalletUpdated;
2047 extern CCriticalSection cs_mapWallet;
2048 extern map<vector<unsigned char>, CPrivKey> mapKeys;
2049 extern map<uint160, vector<unsigned char> > mapPubKeys;
2050 extern CCriticalSection cs_mapKeys;
2051 extern CKey keyUser;