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 GetAmounts(int64
& nGenerated
, list
<pair
<string
/* address */, int64
> >& listReceived
,
877 list
<pair
<string
/* address */, int64
> >& listSent
, int64
& nFee
, string
& strSentAccount
) const;
879 void GetAccountAmounts(const string
& strAccount
, int64
& nGenerated
, int64
& nReceived
,
880 int64
& nSent
, int64
& nFee
) const;
882 bool IsFromMe() const
884 return (GetDebit() > 0);
887 bool IsConfirmed() const
889 // Quick answer in most cases
892 if (GetDepthInMainChain() >= 1)
894 if (!IsFromMe()) // using wtx's cached debit
897 // If no confirmations but it's from us, we can still
898 // consider it confirmed if all dependencies are confirmed
899 map
<uint256
, const CMerkleTx
*> mapPrev
;
900 vector
<const CMerkleTx
*> vWorkQueue
;
901 vWorkQueue
.reserve(vtxPrev
.size()+1);
902 vWorkQueue
.push_back(this);
903 for (int i
= 0; i
< vWorkQueue
.size(); i
++)
905 const CMerkleTx
* ptx
= vWorkQueue
[i
];
909 if (ptx
->GetDepthInMainChain() >= 1)
911 if (!ptx
->IsFromMe())
915 foreach(const CMerkleTx
& tx
, vtxPrev
)
916 mapPrev
[tx
.GetHash()] = &tx
;
918 foreach(const CTxIn
& txin
, ptx
->vin
)
920 if (!mapPrev
.count(txin
.prevout
.hash
))
922 vWorkQueue
.push_back(mapPrev
[txin
.prevout
.hash
]);
930 return CWalletDB().WriteTx(GetHash(), *this);
934 int64
GetTxTime() const;
935 int GetRequestCount() const;
937 void AddSupportingTransactions(CTxDB
& txdb
);
939 bool AcceptWalletTransaction(CTxDB
& txdb
, bool fCheckInputs
=true);
940 bool AcceptWalletTransaction() { CTxDB
txdb("r"); return AcceptWalletTransaction(txdb
); }
942 void RelayWalletTransaction(CTxDB
& txdb
);
943 void RelayWalletTransaction() { CTxDB
txdb("r"); RelayWalletTransaction(txdb
); }
950 // A txdb record that contains the disk location of a transaction and the
951 // locations of transactions that spend its outputs. vSpent is really only
952 // used as a flag, but having the location is very helpful for debugging.
958 vector
<CDiskTxPos
> vSpent
;
965 CTxIndex(const CDiskTxPos
& posIn
, unsigned int nOutputs
)
968 vSpent
.resize(nOutputs
);
973 if (!(nType
& SER_GETHASH
))
990 friend bool operator==(const CTxIndex
& a
, const CTxIndex
& b
)
992 return (a
.pos
== b
.pos
&&
993 a
.vSpent
== b
.vSpent
);
996 friend bool operator!=(const CTxIndex
& a
, const CTxIndex
& b
)
1007 // Nodes collect new transactions into a block, hash them into a hash tree,
1008 // and scan through nonce values to make the block's hash satisfy proof-of-work
1009 // requirements. When they solve the proof-of-work, they broadcast the block
1010 // to everyone and the block is added to the block chain. The first transaction
1011 // in the block is a special one that creates a new coin owned by the creator
1014 // Blocks are appended to blk0001.dat files on disk. Their location on disk
1015 // is indexed by CBlockIndex objects in memory.
1022 uint256 hashPrevBlock
;
1023 uint256 hashMerkleRoot
;
1026 unsigned int nNonce
;
1029 vector
<CTransaction
> vtx
;
1032 mutable vector
<uint256
> vMerkleTree
;
1042 READWRITE(this->nVersion
);
1043 nVersion
= this->nVersion
;
1044 READWRITE(hashPrevBlock
);
1045 READWRITE(hashMerkleRoot
);
1050 // ConnectBlock depends on vtx being last so it can calculate offset
1051 if (!(nType
& (SER_GETHASH
|SER_BLOCKHEADERONLY
)))
1054 const_cast<CBlock
*>(this)->vtx
.clear();
1066 vMerkleTree
.clear();
1071 return (nBits
== 0);
1074 uint256
GetHash() const
1076 return Hash(BEGIN(nVersion
), END(nNonce
));
1079 int64
GetBlockTime() const
1081 return (int64
)nTime
;
1084 int GetSigOpCount() const
1087 foreach(const CTransaction
& tx
, vtx
)
1088 n
+= tx
.GetSigOpCount();
1093 uint256
BuildMerkleTree() const
1095 vMerkleTree
.clear();
1096 foreach(const CTransaction
& tx
, vtx
)
1097 vMerkleTree
.push_back(tx
.GetHash());
1099 for (int nSize
= vtx
.size(); nSize
> 1; nSize
= (nSize
+ 1) / 2)
1101 for (int i
= 0; i
< nSize
; i
+= 2)
1103 int i2
= min(i
+1, nSize
-1);
1104 vMerkleTree
.push_back(Hash(BEGIN(vMerkleTree
[j
+i
]), END(vMerkleTree
[j
+i
]),
1105 BEGIN(vMerkleTree
[j
+i2
]), END(vMerkleTree
[j
+i2
])));
1109 return (vMerkleTree
.empty() ? 0 : vMerkleTree
.back());
1112 vector
<uint256
> GetMerkleBranch(int nIndex
) const
1114 if (vMerkleTree
.empty())
1116 vector
<uint256
> vMerkleBranch
;
1118 for (int nSize
= vtx
.size(); nSize
> 1; nSize
= (nSize
+ 1) / 2)
1120 int i
= min(nIndex
^1, nSize
-1);
1121 vMerkleBranch
.push_back(vMerkleTree
[j
+i
]);
1125 return vMerkleBranch
;
1128 static uint256
CheckMerkleBranch(uint256 hash
, const vector
<uint256
>& vMerkleBranch
, int nIndex
)
1132 foreach(const uint256
& otherside
, vMerkleBranch
)
1135 hash
= Hash(BEGIN(otherside
), END(otherside
), BEGIN(hash
), END(hash
));
1137 hash
= Hash(BEGIN(hash
), END(hash
), BEGIN(otherside
), END(otherside
));
1144 bool WriteToDisk(unsigned int& nFileRet
, unsigned int& nBlockPosRet
)
1146 // Open history file to append
1147 CAutoFile fileout
= AppendBlockFile(nFileRet
);
1149 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
1151 // Write index header
1152 unsigned int nSize
= fileout
.GetSerializeSize(*this);
1153 fileout
<< FLATDATA(pchMessageStart
) << nSize
;
1156 nBlockPosRet
= ftell(fileout
);
1157 if (nBlockPosRet
== -1)
1158 return error("CBlock::WriteToDisk() : ftell failed");
1161 // Flush stdio buffers and commit to disk before returning
1163 if (!IsInitialBlockDownload() || (nBestHeight
+1) % 500 == 0)
1166 _commit(_fileno(fileout
));
1168 fsync(fileno(fileout
));
1175 bool ReadFromDisk(unsigned int nFile
, unsigned int nBlockPos
, bool fReadTransactions
=true)
1179 // Open history file to read
1180 CAutoFile filein
= OpenBlockFile(nFile
, nBlockPos
, "rb");
1182 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1183 if (!fReadTransactions
)
1184 filein
.nType
|= SER_BLOCKHEADERONLY
;
1190 if (!CheckProofOfWork(GetHash(), nBits
))
1191 return error("CBlock::ReadFromDisk() : errors in block header");
1200 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
1201 GetHash().ToString().substr(0,20).c_str(),
1203 hashPrevBlock
.ToString().substr(0,20).c_str(),
1204 hashMerkleRoot
.ToString().substr(0,10).c_str(),
1205 nTime
, nBits
, nNonce
,
1207 for (int i
= 0; i
< vtx
.size(); i
++)
1212 printf(" vMerkleTree: ");
1213 for (int i
= 0; i
< vMerkleTree
.size(); i
++)
1214 printf("%s ", vMerkleTree
[i
].ToString().substr(0,10).c_str());
1219 bool DisconnectBlock(CTxDB
& txdb
, CBlockIndex
* pindex
);
1220 bool ConnectBlock(CTxDB
& txdb
, CBlockIndex
* pindex
);
1221 bool ReadFromDisk(const CBlockIndex
* pindex
, bool fReadTransactions
=true);
1222 bool SetBestChain(CTxDB
& txdb
, CBlockIndex
* pindexNew
);
1223 bool AddToBlockIndex(unsigned int nFile
, unsigned int nBlockPos
);
1224 bool CheckBlock() const;
1234 // The block chain is a tree shaped structure starting with the
1235 // genesis block at the root, with each block potentially having multiple
1236 // candidates to be the next block. pprev and pnext link a path through the
1237 // main/longest chain. A blockindex may have multiple pprev pointing back
1238 // to it, but pnext will only point forward to the longest branch, or will
1239 // be null if the block is not part of the longest chain.
1244 const uint256
* phashBlock
;
1248 unsigned int nBlockPos
;
1250 CBigNum bnChainWork
;
1254 uint256 hashMerkleRoot
;
1257 unsigned int nNonce
;
1277 CBlockIndex(unsigned int nFileIn
, unsigned int nBlockPosIn
, CBlock
& block
)
1283 nBlockPos
= nBlockPosIn
;
1287 nVersion
= block
.nVersion
;
1288 hashMerkleRoot
= block
.hashMerkleRoot
;
1289 nTime
= block
.nTime
;
1290 nBits
= block
.nBits
;
1291 nNonce
= block
.nNonce
;
1294 CBlock
GetBlockHeader() const
1297 block
.nVersion
= nVersion
;
1299 block
.hashPrevBlock
= pprev
->GetBlockHash();
1300 block
.hashMerkleRoot
= hashMerkleRoot
;
1301 block
.nTime
= nTime
;
1302 block
.nBits
= nBits
;
1303 block
.nNonce
= nNonce
;
1307 uint256
GetBlockHash() const
1312 int64
GetBlockTime() const
1314 return (int64
)nTime
;
1317 CBigNum
GetBlockWork() const
1320 bnTarget
.SetCompact(nBits
);
1323 return (CBigNum(1)<<256) / (bnTarget
+1);
1326 bool IsInMainChain() const
1328 return (pnext
|| this == pindexBest
);
1331 bool CheckIndex() const
1333 return CheckProofOfWork(GetBlockHash(), nBits
);
1336 bool EraseBlockFromDisk()
1338 // Open history file
1339 CAutoFile fileout
= OpenBlockFile(nFile
, nBlockPos
, "rb+");
1343 // Overwrite with empty null block
1351 enum { nMedianTimeSpan
=11 };
1353 int64
GetMedianTimePast() const
1355 int64 pmedian
[nMedianTimeSpan
];
1356 int64
* pbegin
= &pmedian
[nMedianTimeSpan
];
1357 int64
* pend
= &pmedian
[nMedianTimeSpan
];
1359 const CBlockIndex
* pindex
= this;
1360 for (int i
= 0; i
< nMedianTimeSpan
&& pindex
; i
++, pindex
= pindex
->pprev
)
1361 *(--pbegin
) = pindex
->GetBlockTime();
1364 return pbegin
[(pend
- pbegin
)/2];
1367 int64
GetMedianTime() const
1369 const CBlockIndex
* pindex
= this;
1370 for (int i
= 0; i
< nMedianTimeSpan
/2; i
++)
1373 return GetBlockTime();
1374 pindex
= pindex
->pnext
;
1376 return pindex
->GetMedianTimePast();
1381 string
ToString() const
1383 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
1384 pprev
, pnext
, nFile
, nBlockPos
, nHeight
,
1385 hashMerkleRoot
.ToString().substr(0,10).c_str(),
1386 GetBlockHash().ToString().substr(0,20).c_str());
1391 printf("%s\n", ToString().c_str());
1398 // Used to marshal pointers into hashes for db storage.
1400 class CDiskBlockIndex
: public CBlockIndex
1412 explicit CDiskBlockIndex(CBlockIndex
* pindex
) : CBlockIndex(*pindex
)
1414 hashPrev
= (pprev
? pprev
->GetBlockHash() : 0);
1415 hashNext
= (pnext
? pnext
->GetBlockHash() : 0);
1420 if (!(nType
& SER_GETHASH
))
1421 READWRITE(nVersion
);
1423 READWRITE(hashNext
);
1425 READWRITE(nBlockPos
);
1429 READWRITE(this->nVersion
);
1430 READWRITE(hashPrev
);
1431 READWRITE(hashMerkleRoot
);
1437 uint256
GetBlockHash() const
1440 block
.nVersion
= nVersion
;
1441 block
.hashPrevBlock
= hashPrev
;
1442 block
.hashMerkleRoot
= hashMerkleRoot
;
1443 block
.nTime
= nTime
;
1444 block
.nBits
= nBits
;
1445 block
.nNonce
= nNonce
;
1446 return block
.GetHash();
1450 string
ToString() const
1452 string str
= "CDiskBlockIndex(";
1453 str
+= CBlockIndex::ToString();
1454 str
+= strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1455 GetBlockHash().ToString().c_str(),
1456 hashPrev
.ToString().substr(0,20).c_str(),
1457 hashNext
.ToString().substr(0,20).c_str());
1463 printf("%s\n", ToString().c_str());
1475 // Describes a place in the block chain to another node such that if the
1476 // other node doesn't have the same branch, it can find a recent common trunk.
1477 // The further back it is, the further before the fork it may be.
1482 vector
<uint256
> vHave
;
1489 explicit CBlockLocator(const CBlockIndex
* pindex
)
1494 explicit CBlockLocator(uint256 hashBlock
)
1496 map
<uint256
, CBlockIndex
*>::iterator mi
= mapBlockIndex
.find(hashBlock
);
1497 if (mi
!= mapBlockIndex
.end())
1503 if (!(nType
& SER_GETHASH
))
1504 READWRITE(nVersion
);
1515 return vHave
.empty();
1518 void Set(const CBlockIndex
* pindex
)
1524 vHave
.push_back(pindex
->GetBlockHash());
1526 // Exponentially larger steps back
1527 for (int i
= 0; pindex
&& i
< nStep
; i
++)
1528 pindex
= pindex
->pprev
;
1529 if (vHave
.size() > 10)
1532 vHave
.push_back(hashGenesisBlock
);
1535 int GetDistanceBack()
1537 // Retrace how far back it was in the sender's branch
1540 foreach(const uint256
& hash
, vHave
)
1542 map
<uint256
, CBlockIndex
*>::iterator mi
= mapBlockIndex
.find(hash
);
1543 if (mi
!= mapBlockIndex
.end())
1545 CBlockIndex
* pindex
= (*mi
).second
;
1546 if (pindex
->IsInMainChain())
1556 CBlockIndex
* GetBlockIndex()
1558 // Find the first block the caller has in the main chain
1559 foreach(const uint256
& hash
, vHave
)
1561 map
<uint256
, CBlockIndex
*>::iterator mi
= mapBlockIndex
.find(hash
);
1562 if (mi
!= mapBlockIndex
.end())
1564 CBlockIndex
* pindex
= (*mi
).second
;
1565 if (pindex
->IsInMainChain())
1569 return pindexGenesisBlock
;
1572 uint256
GetBlockHash()
1574 // Find the first block the caller has in the main chain
1575 foreach(const uint256
& hash
, vHave
)
1577 map
<uint256
, CBlockIndex
*>::iterator mi
= mapBlockIndex
.find(hash
);
1578 if (mi
!= mapBlockIndex
.end())
1580 CBlockIndex
* pindex
= (*mi
).second
;
1581 if (pindex
->IsInMainChain())
1585 return hashGenesisBlock
;
1590 CBlockIndex
* pindex
= GetBlockIndex();
1593 return pindex
->nHeight
;
1603 // Private key that includes an expiration date in case it never gets used.
1608 CPrivKey vchPrivKey
;
1612 //// todo: add something to note what created it (user, getnewaddress, change)
1613 //// maybe should have a map<string, string> property map
1615 CWalletKey(int64 nExpires
=0)
1617 nTimeCreated
= (nExpires
? GetTime() : 0);
1618 nTimeExpires
= nExpires
;
1623 if (!(nType
& SER_GETHASH
))
1624 READWRITE(nVersion
);
1625 READWRITE(vchPrivKey
);
1626 READWRITE(nTimeCreated
);
1627 READWRITE(nTimeExpires
);
1628 READWRITE(strComment
);
1638 // Account information.
1639 // Stored in wallet with key "acc"+string account name
1644 vector
<unsigned char> vchPubKey
;
1658 if (!(nType
& SER_GETHASH
))
1659 READWRITE(nVersion
);
1660 READWRITE(vchPubKey
);
1667 // Internal transfers.
1668 // Database key is acentry<account><counter>
1670 class CAccountingEntry
1676 string strOtherAccount
;
1689 strOtherAccount
.clear();
1695 if (!(nType
& SER_GETHASH
))
1696 READWRITE(nVersion
);
1697 // Note: strAccount is serialized as part of the key, not here.
1698 READWRITE(nCreditDebit
);
1700 READWRITE(strOtherAccount
);
1701 READWRITE(strComment
);
1714 // Alerts are for notifying old versions if they become too obsolete and
1715 // need to upgrade. The message is displayed in the status bar.
1716 // Alert messages are broadcast as a vector of signed data. Unserializing may
1717 // not read the entire buffer if the alert is for a newer version, but older
1718 // versions can still relay the original data.
1720 class CUnsignedAlert
1724 int64 nRelayUntil
; // when newer nodes stop relaying to newer nodes
1729 int nMinVer
; // lowest version inclusive
1730 int nMaxVer
; // highest version inclusive
1731 set
<string
> setSubVer
; // empty matches all
1736 string strStatusBar
;
1741 READWRITE(this->nVersion
);
1742 nVersion
= this->nVersion
;
1743 READWRITE(nRelayUntil
);
1744 READWRITE(nExpiration
);
1747 READWRITE(setCancel
);
1750 READWRITE(setSubVer
);
1751 READWRITE(nPriority
);
1753 READWRITE(strComment
);
1754 READWRITE(strStatusBar
);
1755 READWRITE(strReserved
);
1772 strStatusBar
.clear();
1773 strReserved
.clear();
1776 string
ToString() const
1778 string strSetCancel
;
1779 foreach(int n
, setCancel
)
1780 strSetCancel
+= strprintf("%d ", n
);
1781 string strSetSubVer
;
1782 foreach(string str
, setSubVer
)
1783 strSetSubVer
+= "\"" + str
+ "\" ";
1787 " nRelayUntil = %"PRI64d
"\n"
1788 " nExpiration = %"PRI64d
"\n"
1796 " strComment = \"%s\"\n"
1797 " strStatusBar = \"%s\"\n"
1804 strSetCancel
.c_str(),
1807 strSetSubVer
.c_str(),
1810 strStatusBar
.c_str());
1815 printf("%s", ToString().c_str());
1819 class CAlert
: public CUnsignedAlert
1822 vector
<unsigned char> vchMsg
;
1823 vector
<unsigned char> vchSig
;
1838 CUnsignedAlert::SetNull();
1845 return (nExpiration
== 0);
1848 uint256
GetHash() const
1850 return SerializeHash(*this);
1853 bool IsInEffect() const
1855 return (GetAdjustedTime() < nExpiration
);
1858 bool Cancels(const CAlert
& alert
) const
1861 return false; // this was a no-op before 31403
1862 return (alert
.nID
<= nCancel
|| setCancel
.count(alert
.nID
));
1865 bool AppliesTo(int nVersion
, string strSubVerIn
) const
1867 return (IsInEffect() &&
1868 nMinVer
<= nVersion
&& nVersion
<= nMaxVer
&&
1869 (setSubVer
.empty() || setSubVer
.count(strSubVerIn
)));
1872 bool AppliesToMe() const
1874 return AppliesTo(VERSION
, ::pszSubVer
);
1877 bool RelayTo(CNode
* pnode
) const
1881 // returns true if wasn't already contained in the set
1882 if (pnode
->setKnown
.insert(GetHash()).second
)
1884 if (AppliesTo(pnode
->nVersion
, pnode
->strSubVer
) ||
1886 GetAdjustedTime() < nRelayUntil
)
1888 pnode
->PushMessage("alert", *this);
1895 bool CheckSignature()
1898 if (!key
.SetPubKey(ParseHex("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284")))
1899 return error("CAlert::CheckSignature() : SetPubKey failed");
1900 if (!key
.Verify(Hash(vchMsg
.begin(), vchMsg
.end()), vchSig
))
1901 return error("CAlert::CheckSignature() : verify signature failed");
1903 // Now unserialize the data
1904 CDataStream
sMsg(vchMsg
);
1905 sMsg
>> *(CUnsignedAlert
*)this;
1909 bool ProcessAlert();
1921 extern map
<uint256
, CTransaction
> mapTransactions
;
1922 extern map
<uint256
, CWalletTx
> mapWallet
;
1923 extern vector
<uint256
> vWalletUpdated
;
1924 extern CCriticalSection cs_mapWallet
;
1925 extern map
<vector
<unsigned char>, CPrivKey
> mapKeys
;
1926 extern map
<uint160
, vector
<unsigned char> > mapPubKeys
;
1927 extern CCriticalSection cs_mapKeys
;
1928 extern CKey keyUser
;