1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Distributed under the MIT/X11 software license, see the accompanying
3 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
17 static const unsigned int MAX_BLOCK_SIZE
= 1000000;
18 static const unsigned int MAX_BLOCK_SIZE_GEN
= MAX_BLOCK_SIZE
/2;
19 static const int MAX_BLOCK_SIGOPS
= MAX_BLOCK_SIZE
/50;
20 static const int64 COIN
= 100000000;
21 static const int64 CENT
= 1000000;
22 static const int64 MAX_MONEY
= 21000000 * COIN
;
23 inline bool MoneyRange(int64 nValue
) { return (nValue
>= 0 && nValue
<= MAX_MONEY
); }
24 static const int COINBASE_MATURITY
= 100;
31 extern CCriticalSection cs_main
;
32 extern map
<uint256
, CBlockIndex
*> mapBlockIndex
;
33 extern uint256 hashGenesisBlock
;
34 extern CBigNum bnProofOfWorkLimit
;
35 extern CBlockIndex
* pindexGenesisBlock
;
36 extern int nBestHeight
;
37 extern CBigNum bnBestChainWork
;
38 extern CBigNum bnBestInvalidWork
;
39 extern uint256 hashBestChain
;
40 extern CBlockIndex
* pindexBest
;
41 extern unsigned int nTransactionsUpdated
;
42 extern map
<uint256
, int> mapRequestCount
;
43 extern CCriticalSection cs_mapRequestCount
;
44 extern map
<string
, string
> mapAddressBook
;
45 extern CCriticalSection cs_mapAddressBook
;
46 extern vector
<unsigned char> vchDefaultKey
;
47 extern double dHashesPerSec
;
48 extern int64 nHPSTimerStart
;
51 extern int fGenerateBitcoins
;
52 extern int64 nTransactionFee
;
53 extern CAddress addrIncoming
;
54 extern int fLimitProcessors
;
55 extern int nLimitProcessors
;
56 extern int fMinimizeToTray
;
57 extern int fMinimizeOnClose
;
65 bool CheckDiskSpace(uint64 nAdditionalBytes
=0);
66 FILE* OpenBlockFile(unsigned int nFile
, unsigned int nBlockPos
, const char* pszMode
="rb");
67 FILE* AppendBlockFile(unsigned int& nFileRet
);
68 bool AddKey(const CKey
& key
);
69 vector
<unsigned char> GenerateNewKey();
70 bool AddToWallet(const CWalletTx
& wtxIn
);
71 void WalletUpdateSpent(const COutPoint
& prevout
);
72 int ScanForWalletTransactions(CBlockIndex
* pindexStart
);
73 void ReacceptWalletTransactions();
74 bool LoadBlockIndex(bool fAllowNew
=true);
75 void PrintBlockTree();
76 bool ProcessMessages(CNode
* pfrom
);
77 bool ProcessMessage(CNode
* pfrom
, string strCommand
, CDataStream
& vRecv
);
78 bool SendMessages(CNode
* pto
, bool fSendTrickle
);
80 bool CreateTransaction(CScript scriptPubKey
, int64 nValue
, CWalletTx
& wtxNew
, CReserveKey
& reservekey
, int64
& nFeeRet
);
81 bool CommitTransaction(CWalletTx
& wtxNew
, CReserveKey
& reservekey
);
82 bool BroadcastTransaction(CWalletTx
& wtxNew
);
83 string
SendMoney(CScript scriptPubKey
, int64 nValue
, CWalletTx
& wtxNew
, bool fAskFee
=false);
84 string
SendMoneyToBitcoinAddress(string strAddress
, int64 nValue
, CWalletTx
& wtxNew
, bool fAskFee
=false);
85 void GenerateBitcoins(bool fGenerate
);
86 void ThreadBitcoinMiner(void* parg
);
87 CBlock
* CreateNewBlock(CReserveKey
& reservekey
);
88 void IncrementExtraNonce(CBlock
* pblock
, CBlockIndex
* pindexPrev
, unsigned int& nExtraNonce
, int64
& nPrevTime
);
89 void FormatHashBuffers(CBlock
* pblock
, char* pmidstate
, char* pdata
, char* phash1
);
90 bool CheckWork(CBlock
* pblock
, CReserveKey
& reservekey
);
92 bool CheckProofOfWork(uint256 hash
, unsigned int nBits
);
93 bool IsInitialBlockDownload();
94 string
GetWarnings(string strFor
);
111 unsigned int nBlockPos
;
119 CDiskTxPos(unsigned int nFileIn
, unsigned int nBlockPosIn
, unsigned int nTxPosIn
)
122 nBlockPos
= nBlockPosIn
;
126 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
127 void SetNull() { nFile
= -1; nBlockPos
= 0; nTxPos
= 0; }
128 bool IsNull() const { return (nFile
== -1); }
130 friend bool operator==(const CDiskTxPos
& a
, const CDiskTxPos
& b
)
132 return (a
.nFile
== b
.nFile
&&
133 a
.nBlockPos
== b
.nBlockPos
&&
134 a
.nTxPos
== b
.nTxPos
);
137 friend bool operator!=(const CDiskTxPos
& a
, const CDiskTxPos
& b
)
142 string
ToString() const
145 return strprintf("null");
147 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile
, nBlockPos
, nTxPos
);
152 printf("%s", ToString().c_str());
165 CInPoint() { SetNull(); }
166 CInPoint(CTransaction
* ptxIn
, unsigned int nIn
) { ptx
= ptxIn
; n
= nIn
; }
167 void SetNull() { ptx
= NULL
; n
= -1; }
168 bool IsNull() const { return (ptx
== NULL
&& n
== -1); }
180 COutPoint() { SetNull(); }
181 COutPoint(uint256 hashIn
, unsigned int nIn
) { hash
= hashIn
; n
= nIn
; }
182 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
183 void SetNull() { hash
= 0; n
= -1; }
184 bool IsNull() const { return (hash
== 0 && n
== -1); }
186 friend bool operator<(const COutPoint
& a
, const COutPoint
& b
)
188 return (a
.hash
< b
.hash
|| (a
.hash
== b
.hash
&& a
.n
< b
.n
));
191 friend bool operator==(const COutPoint
& a
, const COutPoint
& b
)
193 return (a
.hash
== b
.hash
&& a
.n
== b
.n
);
196 friend bool operator!=(const COutPoint
& a
, const COutPoint
& b
)
201 string
ToString() const
203 return strprintf("COutPoint(%s, %d)", hash
.ToString().substr(0,10).c_str(), n
);
208 printf("%s\n", ToString().c_str());
216 // An input of a transaction. It contains the location of the previous
217 // transaction's output that it claims and a signature that matches the
218 // output's public key.
225 unsigned int nSequence
;
229 nSequence
= UINT_MAX
;
232 explicit CTxIn(COutPoint prevoutIn
, CScript scriptSigIn
=CScript(), unsigned int nSequenceIn
=UINT_MAX
)
235 scriptSig
= scriptSigIn
;
236 nSequence
= nSequenceIn
;
239 CTxIn(uint256 hashPrevTx
, unsigned int nOut
, CScript scriptSigIn
=CScript(), unsigned int nSequenceIn
=UINT_MAX
)
241 prevout
= COutPoint(hashPrevTx
, nOut
);
242 scriptSig
= scriptSigIn
;
243 nSequence
= nSequenceIn
;
249 READWRITE(scriptSig
);
250 READWRITE(nSequence
);
255 return (nSequence
== UINT_MAX
);
258 friend bool operator==(const CTxIn
& a
, const CTxIn
& b
)
260 return (a
.prevout
== b
.prevout
&&
261 a
.scriptSig
== b
.scriptSig
&&
262 a
.nSequence
== b
.nSequence
);
265 friend bool operator!=(const CTxIn
& a
, const CTxIn
& b
)
270 string
ToString() const
273 str
+= strprintf("CTxIn(");
274 str
+= prevout
.ToString();
275 if (prevout
.IsNull())
276 str
+= strprintf(", coinbase %s", HexStr(scriptSig
).c_str());
278 str
+= strprintf(", scriptSig=%s", scriptSig
.ToString().substr(0,24).c_str());
279 if (nSequence
!= UINT_MAX
)
280 str
+= strprintf(", nSequence=%u", nSequence
);
287 printf("%s\n", ToString().c_str());
291 int64
GetDebit() const;
298 // An output of a transaction. It contains the public key that the next input
299 // must be able to sign with to claim it.
305 CScript scriptPubKey
;
312 CTxOut(int64 nValueIn
, CScript scriptPubKeyIn
)
315 scriptPubKey
= scriptPubKeyIn
;
321 READWRITE(scriptPubKey
);
327 scriptPubKey
.clear();
332 return (nValue
== -1);
335 uint256
GetHash() const
337 return SerializeHash(*this);
342 return ::IsMine(scriptPubKey
);
345 int64
GetCredit() const
347 if (!MoneyRange(nValue
))
348 throw runtime_error("CTxOut::GetCredit() : value out of range");
349 return (IsMine() ? nValue
: 0);
352 bool IsChange() const
354 // On a debit transaction, a txout that's mine but isn't in the address book is change
355 vector
<unsigned char> vchPubKey
;
356 if (ExtractPubKey(scriptPubKey
, true, vchPubKey
))
357 CRITICAL_BLOCK(cs_mapAddressBook
)
358 if (!mapAddressBook
.count(PubKeyToAddress(vchPubKey
)))
363 int64
GetChange() const
365 if (!MoneyRange(nValue
))
366 throw runtime_error("CTxOut::GetChange() : value out of range");
367 return (IsChange() ? nValue
: 0);
370 friend bool operator==(const CTxOut
& a
, const CTxOut
& b
)
372 return (a
.nValue
== b
.nValue
&&
373 a
.scriptPubKey
== b
.scriptPubKey
);
376 friend bool operator!=(const CTxOut
& a
, const CTxOut
& b
)
381 string
ToString() const
383 if (scriptPubKey
.size() < 6)
384 return "CTxOut(error)";
385 return strprintf("CTxOut(nValue=%"PRI64d
".%08"PRI64d
", scriptPubKey=%s)", nValue
/ COIN
, nValue
% COIN
, scriptPubKey
.ToString().substr(0,30).c_str());
390 printf("%s\n", ToString().c_str());
398 // The basic transaction that is broadcasted on the network and contained in
399 // blocks. A transaction can contain multiple inputs and outputs.
407 unsigned int nLockTime
;
417 READWRITE(this->nVersion
);
418 nVersion
= this->nVersion
;
421 READWRITE(nLockTime
);
434 return (vin
.empty() && vout
.empty());
437 uint256
GetHash() const
439 return SerializeHash(*this);
442 bool IsFinal(int nBlockHeight
=0, int64 nBlockTime
=0) const
444 // Time based nLockTime implemented in 0.1.6
447 if (nBlockHeight
== 0)
448 nBlockHeight
= nBestHeight
;
450 nBlockTime
= GetAdjustedTime();
451 if ((int64
)nLockTime
< (nLockTime
< 500000000 ? (int64
)nBlockHeight
: nBlockTime
))
453 foreach(const CTxIn
& txin
, vin
)
459 bool IsNewerThan(const CTransaction
& old
) const
461 if (vin
.size() != old
.vin
.size())
463 for (int i
= 0; i
< vin
.size(); i
++)
464 if (vin
[i
].prevout
!= old
.vin
[i
].prevout
)
468 unsigned int nLowest
= UINT_MAX
;
469 for (int i
= 0; i
< vin
.size(); i
++)
471 if (vin
[i
].nSequence
!= old
.vin
[i
].nSequence
)
473 if (vin
[i
].nSequence
<= nLowest
)
476 nLowest
= vin
[i
].nSequence
;
478 if (old
.vin
[i
].nSequence
< nLowest
)
481 nLowest
= old
.vin
[i
].nSequence
;
488 bool IsCoinBase() const
490 return (vin
.size() == 1 && vin
[0].prevout
.IsNull());
493 int GetSigOpCount() const
496 foreach(const CTxIn
& txin
, vin
)
497 n
+= txin
.scriptSig
.GetSigOpCount();
498 foreach(const CTxOut
& txout
, vout
)
499 n
+= txout
.scriptPubKey
.GetSigOpCount();
503 bool IsStandard() const
505 foreach(const CTxIn
& txin
, vin
)
506 if (!txin
.scriptSig
.IsPushOnly())
507 return error("nonstandard txin: %s", txin
.scriptSig
.ToString().c_str());
508 foreach(const CTxOut
& txout
, vout
)
509 if (!::IsStandard(txout
.scriptPubKey
))
510 return error("nonstandard txout: %s", txout
.scriptPubKey
.ToString().c_str());
516 foreach(const CTxOut
& txout
, vout
)
522 bool IsFromMe() const
524 return (GetDebit() > 0);
527 int64
GetDebit() const
530 foreach(const CTxIn
& txin
, vin
)
532 nDebit
+= txin
.GetDebit();
533 if (!MoneyRange(nDebit
))
534 throw runtime_error("CTransaction::GetDebit() : value out of range");
539 int64
GetCredit() const
542 foreach(const CTxOut
& txout
, vout
)
544 nCredit
+= txout
.GetCredit();
545 if (!MoneyRange(nCredit
))
546 throw runtime_error("CTransaction::GetCredit() : value out of range");
551 int64
GetChange() const
556 foreach(const CTxOut
& txout
, vout
)
558 nChange
+= txout
.GetChange();
559 if (!MoneyRange(nChange
))
560 throw runtime_error("CTransaction::GetChange() : value out of range");
565 int64
GetValueOut() const
568 foreach(const CTxOut
& txout
, vout
)
570 nValueOut
+= txout
.nValue
;
571 if (!MoneyRange(txout
.nValue
) || !MoneyRange(nValueOut
))
572 throw runtime_error("CTransaction::GetValueOut() : value out of range");
577 int64
GetMinFee(unsigned int nBlockSize
=1, bool fAllowFree
=true) const
579 // Base fee is 1 cent per kilobyte
580 unsigned int nBytes
= ::GetSerializeSize(*this, SER_NETWORK
);
581 unsigned int nNewBlockSize
= nBlockSize
+ nBytes
;
582 int64 nMinFee
= (1 + (int64
)nBytes
/ 1000) * CENT
;
588 // Transactions under 10K are free
589 // (about 4500bc if made of 50bc inputs)
595 // Free transaction area
596 if (nNewBlockSize
< 27000)
601 // To limit dust spam, require a 0.01 fee if any output is less than 0.01
603 foreach(const CTxOut
& txout
, vout
)
604 if (txout
.nValue
< CENT
)
607 // Raise the price as the block approaches full
608 if (nBlockSize
!= 1 && nNewBlockSize
>= MAX_BLOCK_SIZE_GEN
/2)
610 if (nNewBlockSize
>= MAX_BLOCK_SIZE_GEN
)
612 nMinFee
*= MAX_BLOCK_SIZE_GEN
/ (MAX_BLOCK_SIZE_GEN
- nNewBlockSize
);
615 if (!MoneyRange(nMinFee
))
621 bool ReadFromDisk(CDiskTxPos pos
, FILE** pfileRet
=NULL
)
623 CAutoFile filein
= OpenBlockFile(pos
.nFile
, 0, pfileRet
? "rb+" : "rb");
625 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
628 if (fseek(filein
, pos
.nTxPos
, SEEK_SET
) != 0)
629 return error("CTransaction::ReadFromDisk() : fseek failed");
632 // Return file pointer
635 if (fseek(filein
, pos
.nTxPos
, SEEK_SET
) != 0)
636 return error("CTransaction::ReadFromDisk() : second fseek failed");
637 *pfileRet
= filein
.release();
642 friend bool operator==(const CTransaction
& a
, const CTransaction
& b
)
644 return (a
.nVersion
== b
.nVersion
&&
647 a
.nLockTime
== b
.nLockTime
);
650 friend bool operator!=(const CTransaction
& a
, const CTransaction
& b
)
656 string
ToString() const
659 str
+= strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
660 GetHash().ToString().substr(0,10).c_str(),
665 for (int i
= 0; i
< vin
.size(); i
++)
666 str
+= " " + vin
[i
].ToString() + "\n";
667 for (int i
= 0; i
< vout
.size(); i
++)
668 str
+= " " + vout
[i
].ToString() + "\n";
674 printf("%s", ToString().c_str());
678 bool ReadFromDisk(CTxDB
& txdb
, COutPoint prevout
, CTxIndex
& txindexRet
);
679 bool ReadFromDisk(CTxDB
& txdb
, COutPoint prevout
);
680 bool ReadFromDisk(COutPoint prevout
);
681 bool DisconnectInputs(CTxDB
& txdb
);
682 bool ConnectInputs(CTxDB
& txdb
, map
<uint256
, CTxIndex
>& mapTestPool
, CDiskTxPos posThisTx
,
683 CBlockIndex
* pindexBlock
, int64
& nFees
, bool fBlock
, bool fMiner
, int64 nMinFee
=0);
684 bool ClientConnectInputs();
685 bool CheckTransaction() const;
686 bool AcceptToMemoryPool(CTxDB
& txdb
, bool fCheckInputs
=true, bool* pfMissingInputs
=NULL
);
687 bool AcceptToMemoryPool(bool fCheckInputs
=true, bool* pfMissingInputs
=NULL
)
690 return AcceptToMemoryPool(txdb
, fCheckInputs
, pfMissingInputs
);
693 bool AddToMemoryPoolUnchecked();
695 bool RemoveFromMemoryPool();
703 // A transaction with a merkle branch linking it to the block chain
705 class CMerkleTx
: public CTransaction
709 vector
<uint256
> vMerkleBranch
;
713 mutable char fMerkleVerified
;
721 CMerkleTx(const CTransaction
& txIn
) : CTransaction(txIn
)
730 fMerkleVerified
= false;
735 nSerSize
+= SerReadWrite(s
, *(CTransaction
*)this, nType
, nVersion
, ser_action
);
736 nVersion
= this->nVersion
;
737 READWRITE(hashBlock
);
738 READWRITE(vMerkleBranch
);
743 int SetMerkleBranch(const CBlock
* pblock
=NULL
);
744 int GetDepthInMainChain(int& nHeightRet
) const;
745 int GetDepthInMainChain() const { int nHeight
; return GetDepthInMainChain(nHeight
); }
746 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
747 int GetBlocksToMaturity() const;
748 bool AcceptToMemoryPool(CTxDB
& txdb
, bool fCheckInputs
=true);
749 bool AcceptToMemoryPool() { CTxDB
txdb("r"); return AcceptToMemoryPool(txdb
); }
756 // A transaction with a bunch of additional info that only the owner cares
757 // about. It includes any unrecorded transactions needed to link it back
758 // to the block chain.
760 class CWalletTx
: public CMerkleTx
763 vector
<CMerkleTx
> vtxPrev
;
764 map
<string
, string
> mapValue
;
765 vector
<pair
<string
, string
> > vOrderForm
;
766 unsigned int fTimeReceivedIsTxTime
;
767 unsigned int nTimeReceived
; // time received by this node
770 string strFromAccount
;
773 mutable char fDebitCached
;
774 mutable char fCreditCached
;
775 mutable char fChangeCached
;
776 mutable int64 nDebitCached
;
777 mutable int64 nCreditCached
;
778 mutable int64 nChangeCached
;
780 // memory only UI hints
781 mutable unsigned int nTimeDisplayed
;
782 mutable int nLinesDisplayed
;
783 mutable char fConfirmedDisplayed
;
791 CWalletTx(const CMerkleTx
& txIn
) : CMerkleTx(txIn
)
796 CWalletTx(const CTransaction
& txIn
) : CMerkleTx(txIn
)
806 fTimeReceivedIsTxTime
= false;
810 strFromAccount
.clear();
811 fDebitCached
= false;
812 fCreditCached
= false;
813 fChangeCached
= false;
819 fConfirmedDisplayed
= false;
824 CWalletTx
* pthis
= const_cast<CWalletTx
*>(this);
827 nSerSize
+= SerReadWrite(s
, *(CMerkleTx
*)this, nType
, nVersion
, ser_action
);
830 pthis
->mapValue
["fromaccount"] = pthis
->strFromAccount
;
832 pthis
->strFromAccount
= pthis
->mapValue
["fromaccount"];
833 pthis
->mapValue
.erase("fromaccount");
834 pthis
->mapValue
.erase("version");
836 READWRITE(vOrderForm
);
837 READWRITE(fTimeReceivedIsTxTime
);
838 READWRITE(nTimeReceived
);
843 int64
GetDebit() const
849 nDebitCached
= CTransaction::GetDebit();
854 int64
GetCredit(bool fUseCache
=true) const
856 // Must wait until coinbase is safely deep enough in the chain before valuing it
857 if (IsCoinBase() && GetBlocksToMaturity() > 0)
860 // GetBalance can assume transactions in mapWallet won't change
861 if (fUseCache
&& fCreditCached
)
862 return nCreditCached
;
863 nCreditCached
= CTransaction::GetCredit();
864 fCreditCached
= true;
865 return nCreditCached
;
868 int64
GetChange() const
871 return nChangeCached
;
872 nChangeCached
= CTransaction::GetChange();
873 fChangeCached
= true;
874 return nChangeCached
;
877 void GetAmounts(int64
& nGenerated
, list
<pair
<string
/* address */, int64
> >& listReceived
,
878 list
<pair
<string
/* address */, int64
> >& listSent
, int64
& nFee
, string
& strSentAccount
) const;
880 void GetAccountAmounts(const string
& strAccount
, int64
& nGenerated
, int64
& nReceived
,
881 int64
& nSent
, int64
& nFee
) const;
883 bool IsFromMe() const
885 return (GetDebit() > 0);
888 bool IsConfirmed() const
890 // Quick answer in most cases
893 if (GetDepthInMainChain() >= 1)
895 if (!IsFromMe()) // using wtx's cached debit
898 // If no confirmations but it's from us, we can still
899 // consider it confirmed if all dependencies are confirmed
900 map
<uint256
, const CMerkleTx
*> mapPrev
;
901 vector
<const CMerkleTx
*> vWorkQueue
;
902 vWorkQueue
.reserve(vtxPrev
.size()+1);
903 vWorkQueue
.push_back(this);
904 for (int i
= 0; i
< vWorkQueue
.size(); i
++)
906 const CMerkleTx
* ptx
= vWorkQueue
[i
];
910 if (ptx
->GetDepthInMainChain() >= 1)
912 if (!ptx
->IsFromMe())
916 foreach(const CMerkleTx
& tx
, vtxPrev
)
917 mapPrev
[tx
.GetHash()] = &tx
;
919 foreach(const CTxIn
& txin
, ptx
->vin
)
921 if (!mapPrev
.count(txin
.prevout
.hash
))
923 vWorkQueue
.push_back(mapPrev
[txin
.prevout
.hash
]);
931 return CWalletDB().WriteTx(GetHash(), *this);
935 int64
GetTxTime() const;
936 int GetRequestCount() const;
938 void AddSupportingTransactions(CTxDB
& txdb
);
940 bool AcceptWalletTransaction(CTxDB
& txdb
, bool fCheckInputs
=true);
941 bool AcceptWalletTransaction() { CTxDB
txdb("r"); return AcceptWalletTransaction(txdb
); }
943 void RelayWalletTransaction(CTxDB
& txdb
);
944 void RelayWalletTransaction() { CTxDB
txdb("r"); RelayWalletTransaction(txdb
); }
951 // A txdb record that contains the disk location of a transaction and the
952 // locations of transactions that spend its outputs. vSpent is really only
953 // used as a flag, but having the location is very helpful for debugging.
959 vector
<CDiskTxPos
> vSpent
;
966 CTxIndex(const CDiskTxPos
& posIn
, unsigned int nOutputs
)
969 vSpent
.resize(nOutputs
);
974 if (!(nType
& SER_GETHASH
))
991 friend bool operator==(const CTxIndex
& a
, const CTxIndex
& b
)
993 return (a
.pos
== b
.pos
&&
994 a
.vSpent
== b
.vSpent
);
997 friend bool operator!=(const CTxIndex
& a
, const CTxIndex
& b
)
1008 // Nodes collect new transactions into a block, hash them into a hash tree,
1009 // and scan through nonce values to make the block's hash satisfy proof-of-work
1010 // requirements. When they solve the proof-of-work, they broadcast the block
1011 // to everyone and the block is added to the block chain. The first transaction
1012 // in the block is a special one that creates a new coin owned by the creator
1015 // Blocks are appended to blk0001.dat files on disk. Their location on disk
1016 // is indexed by CBlockIndex objects in memory.
1023 uint256 hashPrevBlock
;
1024 uint256 hashMerkleRoot
;
1027 unsigned int nNonce
;
1030 vector
<CTransaction
> vtx
;
1033 mutable vector
<uint256
> vMerkleTree
;
1043 READWRITE(this->nVersion
);
1044 nVersion
= this->nVersion
;
1045 READWRITE(hashPrevBlock
);
1046 READWRITE(hashMerkleRoot
);
1051 // ConnectBlock depends on vtx being last so it can calculate offset
1052 if (!(nType
& (SER_GETHASH
|SER_BLOCKHEADERONLY
)))
1055 const_cast<CBlock
*>(this)->vtx
.clear();
1067 vMerkleTree
.clear();
1072 return (nBits
== 0);
1075 uint256
GetHash() const
1077 return Hash(BEGIN(nVersion
), END(nNonce
));
1080 int64
GetBlockTime() const
1082 return (int64
)nTime
;
1085 int GetSigOpCount() const
1088 foreach(const CTransaction
& tx
, vtx
)
1089 n
+= tx
.GetSigOpCount();
1094 uint256
BuildMerkleTree() const
1096 vMerkleTree
.clear();
1097 foreach(const CTransaction
& tx
, vtx
)
1098 vMerkleTree
.push_back(tx
.GetHash());
1100 for (int nSize
= vtx
.size(); nSize
> 1; nSize
= (nSize
+ 1) / 2)
1102 for (int i
= 0; i
< nSize
; i
+= 2)
1104 int i2
= min(i
+1, nSize
-1);
1105 vMerkleTree
.push_back(Hash(BEGIN(vMerkleTree
[j
+i
]), END(vMerkleTree
[j
+i
]),
1106 BEGIN(vMerkleTree
[j
+i2
]), END(vMerkleTree
[j
+i2
])));
1110 return (vMerkleTree
.empty() ? 0 : vMerkleTree
.back());
1113 vector
<uint256
> GetMerkleBranch(int nIndex
) const
1115 if (vMerkleTree
.empty())
1117 vector
<uint256
> vMerkleBranch
;
1119 for (int nSize
= vtx
.size(); nSize
> 1; nSize
= (nSize
+ 1) / 2)
1121 int i
= min(nIndex
^1, nSize
-1);
1122 vMerkleBranch
.push_back(vMerkleTree
[j
+i
]);
1126 return vMerkleBranch
;
1129 static uint256
CheckMerkleBranch(uint256 hash
, const vector
<uint256
>& vMerkleBranch
, int nIndex
)
1133 foreach(const uint256
& otherside
, vMerkleBranch
)
1136 hash
= Hash(BEGIN(otherside
), END(otherside
), BEGIN(hash
), END(hash
));
1138 hash
= Hash(BEGIN(hash
), END(hash
), BEGIN(otherside
), END(otherside
));
1145 bool WriteToDisk(unsigned int& nFileRet
, unsigned int& nBlockPosRet
)
1147 // Open history file to append
1148 CAutoFile fileout
= AppendBlockFile(nFileRet
);
1150 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
1152 // Write index header
1153 unsigned int nSize
= fileout
.GetSerializeSize(*this);
1154 fileout
<< FLATDATA(pchMessageStart
) << nSize
;
1157 nBlockPosRet
= ftell(fileout
);
1158 if (nBlockPosRet
== -1)
1159 return error("CBlock::WriteToDisk() : ftell failed");
1162 // Flush stdio buffers and commit to disk before returning
1164 if (!IsInitialBlockDownload() || (nBestHeight
+1) % 500 == 0)
1167 _commit(_fileno(fileout
));
1169 fsync(fileno(fileout
));
1176 bool ReadFromDisk(unsigned int nFile
, unsigned int nBlockPos
, bool fReadTransactions
=true)
1180 // Open history file to read
1181 CAutoFile filein
= OpenBlockFile(nFile
, nBlockPos
, "rb");
1183 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1184 if (!fReadTransactions
)
1185 filein
.nType
|= SER_BLOCKHEADERONLY
;
1191 if (!CheckProofOfWork(GetHash(), nBits
))
1192 return error("CBlock::ReadFromDisk() : errors in block header");
1201 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
1202 GetHash().ToString().substr(0,20).c_str(),
1204 hashPrevBlock
.ToString().substr(0,20).c_str(),
1205 hashMerkleRoot
.ToString().substr(0,10).c_str(),
1206 nTime
, nBits
, nNonce
,
1208 for (int i
= 0; i
< vtx
.size(); i
++)
1213 printf(" vMerkleTree: ");
1214 for (int i
= 0; i
< vMerkleTree
.size(); i
++)
1215 printf("%s ", vMerkleTree
[i
].ToString().substr(0,10).c_str());
1220 bool DisconnectBlock(CTxDB
& txdb
, CBlockIndex
* pindex
);
1221 bool ConnectBlock(CTxDB
& txdb
, CBlockIndex
* pindex
);
1222 bool ReadFromDisk(const CBlockIndex
* pindex
, bool fReadTransactions
=true);
1223 bool SetBestChain(CTxDB
& txdb
, CBlockIndex
* pindexNew
);
1224 bool AddToBlockIndex(unsigned int nFile
, unsigned int nBlockPos
);
1225 bool CheckBlock() const;
1235 // The block chain is a tree shaped structure starting with the
1236 // genesis block at the root, with each block potentially having multiple
1237 // candidates to be the next block. pprev and pnext link a path through the
1238 // main/longest chain. A blockindex may have multiple pprev pointing back
1239 // to it, but pnext will only point forward to the longest branch, or will
1240 // be null if the block is not part of the longest chain.
1245 const uint256
* phashBlock
;
1249 unsigned int nBlockPos
;
1251 CBigNum bnChainWork
;
1255 uint256 hashMerkleRoot
;
1258 unsigned int nNonce
;
1278 CBlockIndex(unsigned int nFileIn
, unsigned int nBlockPosIn
, CBlock
& block
)
1284 nBlockPos
= nBlockPosIn
;
1288 nVersion
= block
.nVersion
;
1289 hashMerkleRoot
= block
.hashMerkleRoot
;
1290 nTime
= block
.nTime
;
1291 nBits
= block
.nBits
;
1292 nNonce
= block
.nNonce
;
1295 CBlock
GetBlockHeader() const
1298 block
.nVersion
= nVersion
;
1300 block
.hashPrevBlock
= pprev
->GetBlockHash();
1301 block
.hashMerkleRoot
= hashMerkleRoot
;
1302 block
.nTime
= nTime
;
1303 block
.nBits
= nBits
;
1304 block
.nNonce
= nNonce
;
1308 uint256
GetBlockHash() const
1313 int64
GetBlockTime() const
1315 return (int64
)nTime
;
1318 CBigNum
GetBlockWork() const
1321 bnTarget
.SetCompact(nBits
);
1324 return (CBigNum(1)<<256) / (bnTarget
+1);
1327 bool IsInMainChain() const
1329 return (pnext
|| this == pindexBest
);
1332 bool CheckIndex() const
1334 return CheckProofOfWork(GetBlockHash(), nBits
);
1337 bool EraseBlockFromDisk()
1339 // Open history file
1340 CAutoFile fileout
= OpenBlockFile(nFile
, nBlockPos
, "rb+");
1344 // Overwrite with empty null block
1352 enum { nMedianTimeSpan
=11 };
1354 int64
GetMedianTimePast() const
1356 int64 pmedian
[nMedianTimeSpan
];
1357 int64
* pbegin
= &pmedian
[nMedianTimeSpan
];
1358 int64
* pend
= &pmedian
[nMedianTimeSpan
];
1360 const CBlockIndex
* pindex
= this;
1361 for (int i
= 0; i
< nMedianTimeSpan
&& pindex
; i
++, pindex
= pindex
->pprev
)
1362 *(--pbegin
) = pindex
->GetBlockTime();
1365 return pbegin
[(pend
- pbegin
)/2];
1368 int64
GetMedianTime() const
1370 const CBlockIndex
* pindex
= this;
1371 for (int i
= 0; i
< nMedianTimeSpan
/2; i
++)
1374 return GetBlockTime();
1375 pindex
= pindex
->pnext
;
1377 return pindex
->GetMedianTimePast();
1382 string
ToString() const
1384 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
1385 pprev
, pnext
, nFile
, nBlockPos
, nHeight
,
1386 hashMerkleRoot
.ToString().substr(0,10).c_str(),
1387 GetBlockHash().ToString().substr(0,20).c_str());
1392 printf("%s\n", ToString().c_str());
1399 // Used to marshal pointers into hashes for db storage.
1401 class CDiskBlockIndex
: public CBlockIndex
1413 explicit CDiskBlockIndex(CBlockIndex
* pindex
) : CBlockIndex(*pindex
)
1415 hashPrev
= (pprev
? pprev
->GetBlockHash() : 0);
1416 hashNext
= (pnext
? pnext
->GetBlockHash() : 0);
1421 if (!(nType
& SER_GETHASH
))
1422 READWRITE(nVersion
);
1424 READWRITE(hashNext
);
1426 READWRITE(nBlockPos
);
1430 READWRITE(this->nVersion
);
1431 READWRITE(hashPrev
);
1432 READWRITE(hashMerkleRoot
);
1438 uint256
GetBlockHash() const
1441 block
.nVersion
= nVersion
;
1442 block
.hashPrevBlock
= hashPrev
;
1443 block
.hashMerkleRoot
= hashMerkleRoot
;
1444 block
.nTime
= nTime
;
1445 block
.nBits
= nBits
;
1446 block
.nNonce
= nNonce
;
1447 return block
.GetHash();
1451 string
ToString() const
1453 string str
= "CDiskBlockIndex(";
1454 str
+= CBlockIndex::ToString();
1455 str
+= strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1456 GetBlockHash().ToString().c_str(),
1457 hashPrev
.ToString().substr(0,20).c_str(),
1458 hashNext
.ToString().substr(0,20).c_str());
1464 printf("%s\n", ToString().c_str());
1476 // Describes a place in the block chain to another node such that if the
1477 // other node doesn't have the same branch, it can find a recent common trunk.
1478 // The further back it is, the further before the fork it may be.
1483 vector
<uint256
> vHave
;
1490 explicit CBlockLocator(const CBlockIndex
* pindex
)
1495 explicit CBlockLocator(uint256 hashBlock
)
1497 map
<uint256
, CBlockIndex
*>::iterator mi
= mapBlockIndex
.find(hashBlock
);
1498 if (mi
!= mapBlockIndex
.end())
1504 if (!(nType
& SER_GETHASH
))
1505 READWRITE(nVersion
);
1516 return vHave
.empty();
1519 void Set(const CBlockIndex
* pindex
)
1525 vHave
.push_back(pindex
->GetBlockHash());
1527 // Exponentially larger steps back
1528 for (int i
= 0; pindex
&& i
< nStep
; i
++)
1529 pindex
= pindex
->pprev
;
1530 if (vHave
.size() > 10)
1533 vHave
.push_back(hashGenesisBlock
);
1536 int GetDistanceBack()
1538 // Retrace how far back it was in the sender's branch
1541 foreach(const uint256
& hash
, vHave
)
1543 map
<uint256
, CBlockIndex
*>::iterator mi
= mapBlockIndex
.find(hash
);
1544 if (mi
!= mapBlockIndex
.end())
1546 CBlockIndex
* pindex
= (*mi
).second
;
1547 if (pindex
->IsInMainChain())
1557 CBlockIndex
* GetBlockIndex()
1559 // Find the first block the caller has in the main chain
1560 foreach(const uint256
& hash
, vHave
)
1562 map
<uint256
, CBlockIndex
*>::iterator mi
= mapBlockIndex
.find(hash
);
1563 if (mi
!= mapBlockIndex
.end())
1565 CBlockIndex
* pindex
= (*mi
).second
;
1566 if (pindex
->IsInMainChain())
1570 return pindexGenesisBlock
;
1573 uint256
GetBlockHash()
1575 // Find the first block the caller has in the main chain
1576 foreach(const uint256
& hash
, vHave
)
1578 map
<uint256
, CBlockIndex
*>::iterator mi
= mapBlockIndex
.find(hash
);
1579 if (mi
!= mapBlockIndex
.end())
1581 CBlockIndex
* pindex
= (*mi
).second
;
1582 if (pindex
->IsInMainChain())
1586 return hashGenesisBlock
;
1591 CBlockIndex
* pindex
= GetBlockIndex();
1594 return pindex
->nHeight
;
1604 // Private key that includes an expiration date in case it never gets used.
1609 CPrivKey vchPrivKey
;
1613 //// todo: add something to note what created it (user, getnewaddress, change)
1614 //// maybe should have a map<string, string> property map
1616 CWalletKey(int64 nExpires
=0)
1618 nTimeCreated
= (nExpires
? GetTime() : 0);
1619 nTimeExpires
= nExpires
;
1624 if (!(nType
& SER_GETHASH
))
1625 READWRITE(nVersion
);
1626 READWRITE(vchPrivKey
);
1627 READWRITE(nTimeCreated
);
1628 READWRITE(nTimeExpires
);
1629 READWRITE(strComment
);
1639 // Account information.
1640 // Stored in wallet with key "acc"+string account name
1645 vector
<unsigned char> vchPubKey
;
1659 if (!(nType
& SER_GETHASH
))
1660 READWRITE(nVersion
);
1661 READWRITE(vchPubKey
);
1668 // Internal transfers.
1669 // Database key is acentry<account><counter>
1671 class CAccountingEntry
1677 string strOtherAccount
;
1690 strOtherAccount
.clear();
1696 if (!(nType
& SER_GETHASH
))
1697 READWRITE(nVersion
);
1698 // Note: strAccount is serialized as part of the key, not here.
1699 READWRITE(nCreditDebit
);
1701 READWRITE(strOtherAccount
);
1702 READWRITE(strComment
);
1715 // Alerts are for notifying old versions if they become too obsolete and
1716 // need to upgrade. The message is displayed in the status bar.
1717 // Alert messages are broadcast as a vector of signed data. Unserializing may
1718 // not read the entire buffer if the alert is for a newer version, but older
1719 // versions can still relay the original data.
1721 class CUnsignedAlert
1725 int64 nRelayUntil
; // when newer nodes stop relaying to newer nodes
1730 int nMinVer
; // lowest version inclusive
1731 int nMaxVer
; // highest version inclusive
1732 set
<string
> setSubVer
; // empty matches all
1737 string strStatusBar
;
1742 READWRITE(this->nVersion
);
1743 nVersion
= this->nVersion
;
1744 READWRITE(nRelayUntil
);
1745 READWRITE(nExpiration
);
1748 READWRITE(setCancel
);
1751 READWRITE(setSubVer
);
1752 READWRITE(nPriority
);
1754 READWRITE(strComment
);
1755 READWRITE(strStatusBar
);
1756 READWRITE(strReserved
);
1773 strStatusBar
.clear();
1774 strReserved
.clear();
1777 string
ToString() const
1779 string strSetCancel
;
1780 foreach(int n
, setCancel
)
1781 strSetCancel
+= strprintf("%d ", n
);
1782 string strSetSubVer
;
1783 foreach(string str
, setSubVer
)
1784 strSetSubVer
+= "\"" + str
+ "\" ";
1788 " nRelayUntil = %"PRI64d
"\n"
1789 " nExpiration = %"PRI64d
"\n"
1797 " strComment = \"%s\"\n"
1798 " strStatusBar = \"%s\"\n"
1805 strSetCancel
.c_str(),
1808 strSetSubVer
.c_str(),
1811 strStatusBar
.c_str());
1816 printf("%s", ToString().c_str());
1820 class CAlert
: public CUnsignedAlert
1823 vector
<unsigned char> vchMsg
;
1824 vector
<unsigned char> vchSig
;
1839 CUnsignedAlert::SetNull();
1846 return (nExpiration
== 0);
1849 uint256
GetHash() const
1851 return SerializeHash(*this);
1854 bool IsInEffect() const
1856 return (GetAdjustedTime() < nExpiration
);
1859 bool Cancels(const CAlert
& alert
) const
1862 return false; // this was a no-op before 31403
1863 return (alert
.nID
<= nCancel
|| setCancel
.count(alert
.nID
));
1866 bool AppliesTo(int nVersion
, string strSubVerIn
) const
1868 return (IsInEffect() &&
1869 nMinVer
<= nVersion
&& nVersion
<= nMaxVer
&&
1870 (setSubVer
.empty() || setSubVer
.count(strSubVerIn
)));
1873 bool AppliesToMe() const
1875 return AppliesTo(VERSION
, ::pszSubVer
);
1878 bool RelayTo(CNode
* pnode
) const
1882 // returns true if wasn't already contained in the set
1883 if (pnode
->setKnown
.insert(GetHash()).second
)
1885 if (AppliesTo(pnode
->nVersion
, pnode
->strSubVer
) ||
1887 GetAdjustedTime() < nRelayUntil
)
1889 pnode
->PushMessage("alert", *this);
1896 bool CheckSignature()
1899 if (!key
.SetPubKey(ParseHex("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284")))
1900 return error("CAlert::CheckSignature() : SetPubKey failed");
1901 if (!key
.Verify(Hash(vchMsg
.begin(), vchMsg
.end()), vchSig
))
1902 return error("CAlert::CheckSignature() : verify signature failed");
1904 // Now unserialize the data
1905 CDataStream
sMsg(vchMsg
);
1906 sMsg
>> *(CUnsignedAlert
*)this;
1910 bool ProcessAlert();
1922 extern map
<uint256
, CTransaction
> mapTransactions
;
1923 extern map
<uint256
, CWalletTx
> mapWallet
;
1924 extern vector
<uint256
> vWalletUpdated
;
1925 extern CCriticalSection cs_mapWallet
;
1926 extern map
<vector
<unsigned char>, CPrivKey
> mapKeys
;
1927 extern map
<uint160
, vector
<unsigned char> > mapPubKeys
;
1928 extern CCriticalSection cs_mapKeys
;
1929 extern CKey keyUser
;