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;
25 static const CBigNum
bnProofOfWorkLimit(~uint256(0) >> 32);
32 extern CCriticalSection cs_main
;
33 extern map
<uint256
, CBlockIndex
*> mapBlockIndex
;
34 extern const uint256 hashGenesisBlock
;
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
, CKey
& keyRet
, int64
& nFeeRequiredRet
);
80 bool CommitTransaction(CWalletTx
& wtxNew
, const CKey
& key
);
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
);
87 bool CheckProofOfWork(uint256 hash
, unsigned int nBits
);
88 bool IsInitialBlockDownload();
89 string
GetWarnings(string strFor
);
106 unsigned int nBlockPos
;
114 CDiskTxPos(unsigned int nFileIn
, unsigned int nBlockPosIn
, unsigned int nTxPosIn
)
117 nBlockPos
= nBlockPosIn
;
121 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
122 void SetNull() { nFile
= -1; nBlockPos
= 0; nTxPos
= 0; }
123 bool IsNull() const { return (nFile
== -1); }
125 friend bool operator==(const CDiskTxPos
& a
, const CDiskTxPos
& b
)
127 return (a
.nFile
== b
.nFile
&&
128 a
.nBlockPos
== b
.nBlockPos
&&
129 a
.nTxPos
== b
.nTxPos
);
132 friend bool operator!=(const CDiskTxPos
& a
, const CDiskTxPos
& b
)
137 string
ToString() const
140 return strprintf("null");
142 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile
, nBlockPos
, nTxPos
);
147 printf("%s", ToString().c_str());
160 CInPoint() { SetNull(); }
161 CInPoint(CTransaction
* ptxIn
, unsigned int nIn
) { ptx
= ptxIn
; n
= nIn
; }
162 void SetNull() { ptx
= NULL
; n
= -1; }
163 bool IsNull() const { return (ptx
== NULL
&& n
== -1); }
175 COutPoint() { SetNull(); }
176 COutPoint(uint256 hashIn
, unsigned int nIn
) { hash
= hashIn
; n
= nIn
; }
177 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
178 void SetNull() { hash
= 0; n
= -1; }
179 bool IsNull() const { return (hash
== 0 && n
== -1); }
181 friend bool operator<(const COutPoint
& a
, const COutPoint
& b
)
183 return (a
.hash
< b
.hash
|| (a
.hash
== b
.hash
&& a
.n
< b
.n
));
186 friend bool operator==(const COutPoint
& a
, const COutPoint
& b
)
188 return (a
.hash
== b
.hash
&& a
.n
== b
.n
);
191 friend bool operator!=(const COutPoint
& a
, const COutPoint
& b
)
196 string
ToString() const
198 return strprintf("COutPoint(%s, %d)", hash
.ToString().substr(0,6).c_str(), n
);
203 printf("%s\n", ToString().c_str());
211 // An input of a transaction. It contains the location of the previous
212 // transaction's output that it claims and a signature that matches the
213 // output's public key.
220 unsigned int nSequence
;
224 nSequence
= UINT_MAX
;
227 explicit CTxIn(COutPoint prevoutIn
, CScript scriptSigIn
=CScript(), unsigned int nSequenceIn
=UINT_MAX
)
230 scriptSig
= scriptSigIn
;
231 nSequence
= nSequenceIn
;
234 CTxIn(uint256 hashPrevTx
, unsigned int nOut
, CScript scriptSigIn
=CScript(), unsigned int nSequenceIn
=UINT_MAX
)
236 prevout
= COutPoint(hashPrevTx
, nOut
);
237 scriptSig
= scriptSigIn
;
238 nSequence
= nSequenceIn
;
244 READWRITE(scriptSig
);
245 READWRITE(nSequence
);
250 return (nSequence
== UINT_MAX
);
253 friend bool operator==(const CTxIn
& a
, const CTxIn
& b
)
255 return (a
.prevout
== b
.prevout
&&
256 a
.scriptSig
== b
.scriptSig
&&
257 a
.nSequence
== b
.nSequence
);
260 friend bool operator!=(const CTxIn
& a
, const CTxIn
& b
)
265 string
ToString() const
268 str
+= strprintf("CTxIn(");
269 str
+= prevout
.ToString();
270 if (prevout
.IsNull())
271 str
+= strprintf(", coinbase %s", HexStr(scriptSig
).c_str());
273 str
+= strprintf(", scriptSig=%s", scriptSig
.ToString().substr(0,24).c_str());
274 if (nSequence
!= UINT_MAX
)
275 str
+= strprintf(", nSequence=%u", nSequence
);
282 printf("%s\n", ToString().c_str());
286 int64
GetDebit() const;
293 // An output of a transaction. It contains the public key that the next input
294 // must be able to sign with to claim it.
300 CScript scriptPubKey
;
307 CTxOut(int64 nValueIn
, CScript scriptPubKeyIn
)
310 scriptPubKey
= scriptPubKeyIn
;
316 READWRITE(scriptPubKey
);
322 scriptPubKey
.clear();
327 return (nValue
== -1);
330 uint256
GetHash() const
332 return SerializeHash(*this);
337 return ::IsMine(scriptPubKey
);
340 int64
GetCredit() const
342 if (!MoneyRange(nValue
))
343 throw runtime_error("CTxOut::GetCredit() : value out of range");
349 friend bool operator==(const CTxOut
& a
, const CTxOut
& b
)
351 return (a
.nValue
== b
.nValue
&&
352 a
.scriptPubKey
== b
.scriptPubKey
);
355 friend bool operator!=(const CTxOut
& a
, const CTxOut
& b
)
360 string
ToString() const
362 if (scriptPubKey
.size() < 6)
363 return "CTxOut(error)";
364 return strprintf("CTxOut(nValue=%"PRI64d
".%08"PRI64d
", scriptPubKey=%s)", nValue
/ COIN
, nValue
% COIN
, scriptPubKey
.ToString().substr(0,24).c_str());
369 printf("%s\n", ToString().c_str());
377 // The basic transaction that is broadcasted on the network and contained in
378 // blocks. A transaction can contain multiple inputs and outputs.
386 unsigned int nLockTime
;
396 READWRITE(this->nVersion
);
397 nVersion
= this->nVersion
;
400 READWRITE(nLockTime
);
413 return (vin
.empty() && vout
.empty());
416 uint256
GetHash() const
418 return SerializeHash(*this);
421 bool IsFinal(int nBlockHeight
=0, int64 nBlockTime
=0) const
423 // Time based nLockTime implemented in 0.1.6
426 if (nBlockHeight
== 0)
427 nBlockHeight
= nBestHeight
;
429 nBlockTime
= GetAdjustedTime();
430 if ((int64
)nLockTime
< (nLockTime
< 500000000 ? (int64
)nBlockHeight
: nBlockTime
))
432 foreach(const CTxIn
& txin
, vin
)
438 bool IsNewerThan(const CTransaction
& old
) const
440 if (vin
.size() != old
.vin
.size())
442 for (int i
= 0; i
< vin
.size(); i
++)
443 if (vin
[i
].prevout
!= old
.vin
[i
].prevout
)
447 unsigned int nLowest
= UINT_MAX
;
448 for (int i
= 0; i
< vin
.size(); i
++)
450 if (vin
[i
].nSequence
!= old
.vin
[i
].nSequence
)
452 if (vin
[i
].nSequence
<= nLowest
)
455 nLowest
= vin
[i
].nSequence
;
457 if (old
.vin
[i
].nSequence
< nLowest
)
460 nLowest
= old
.vin
[i
].nSequence
;
467 bool IsCoinBase() const
469 return (vin
.size() == 1 && vin
[0].prevout
.IsNull());
472 bool CheckTransaction() const
474 // Basic checks that don't depend on any context
475 if (vin
.empty() || vout
.empty())
476 return error("CTransaction::CheckTransaction() : vin or vout empty");
479 if (::GetSerializeSize(*this, SER_NETWORK
) > MAX_BLOCK_SIZE
)
480 return error("CTransaction::CheckTransaction() : size limits failed");
482 // Check for negative or overflow output values
484 foreach(const CTxOut
& txout
, vout
)
486 if (txout
.nValue
< 0)
487 return error("CTransaction::CheckTransaction() : txout.nValue negative");
488 if (txout
.nValue
> MAX_MONEY
)
489 return error("CTransaction::CheckTransaction() : txout.nValue too high");
490 nValueOut
+= txout
.nValue
;
491 if (!MoneyRange(nValueOut
))
492 return error("CTransaction::CheckTransaction() : txout total out of range");
497 if (vin
[0].scriptSig
.size() < 2 || vin
[0].scriptSig
.size() > 100)
498 return error("CTransaction::CheckTransaction() : coinbase script size");
502 foreach(const CTxIn
& txin
, vin
)
503 if (txin
.prevout
.IsNull())
504 return error("CTransaction::CheckTransaction() : prevout is null");
510 int GetSigOpCount() const
513 foreach(const CTxIn
& txin
, vin
)
514 n
+= txin
.scriptSig
.GetSigOpCount();
515 foreach(const CTxOut
& txout
, vout
)
516 n
+= txout
.scriptPubKey
.GetSigOpCount();
522 foreach(const CTxOut
& txout
, vout
)
528 int64
GetDebit() const
531 foreach(const CTxIn
& txin
, vin
)
533 nDebit
+= txin
.GetDebit();
534 if (!MoneyRange(nDebit
))
535 throw runtime_error("CTransaction::GetDebit() : value out of range");
540 int64
GetCredit() const
543 foreach(const CTxOut
& txout
, vout
)
545 nCredit
+= txout
.GetCredit();
546 if (!MoneyRange(nCredit
))
547 throw runtime_error("CTransaction::GetCredit() : value out of range");
552 int64
GetValueOut() const
555 foreach(const CTxOut
& txout
, vout
)
557 nValueOut
+= txout
.nValue
;
558 if (!MoneyRange(txout
.nValue
) || !MoneyRange(nValueOut
))
559 throw runtime_error("CTransaction::GetValueOut() : value out of range");
564 int64
GetMinFee(unsigned int nBlockSize
=1) const
566 // Base fee is 1 cent per kilobyte
567 unsigned int nBytes
= ::GetSerializeSize(*this, SER_NETWORK
);
568 int64 nMinFee
= (1 + (int64
)nBytes
/ 1000) * CENT
;
570 // Transactions under 60K are free as long as block size is under 80K
571 // (about 27,000bc if made of 50bc inputs)
572 if (nBytes
< 60000 && nBlockSize
< 80000)
575 // Transactions under 3K are free as long as block size is under 200K
576 if (nBytes
< 3000 && nBlockSize
< 200000)
579 // To limit dust spam, require a 0.01 fee if any output is less than 0.01
581 foreach(const CTxOut
& txout
, vout
)
582 if (txout
.nValue
< CENT
)
585 // Raise the price as the block approaches full
586 if (MAX_BLOCK_SIZE
/2 <= nBlockSize
&& nBlockSize
< MAX_BLOCK_SIZE
)
587 nMinFee
*= MAX_BLOCK_SIZE
/ (MAX_BLOCK_SIZE
- nBlockSize
);
588 if (!MoneyRange(nMinFee
))
595 bool ReadFromDisk(CDiskTxPos pos
, FILE** pfileRet
=NULL
)
597 CAutoFile filein
= OpenBlockFile(pos
.nFile
, 0, pfileRet
? "rb+" : "rb");
599 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
602 if (fseek(filein
, pos
.nTxPos
, SEEK_SET
) != 0)
603 return error("CTransaction::ReadFromDisk() : fseek failed");
606 // Return file pointer
609 if (fseek(filein
, pos
.nTxPos
, SEEK_SET
) != 0)
610 return error("CTransaction::ReadFromDisk() : second fseek failed");
611 *pfileRet
= filein
.release();
617 friend bool operator==(const CTransaction
& a
, const CTransaction
& b
)
619 return (a
.nVersion
== b
.nVersion
&&
622 a
.nLockTime
== b
.nLockTime
);
625 friend bool operator!=(const CTransaction
& a
, const CTransaction
& b
)
631 string
ToString() const
634 str
+= strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
635 GetHash().ToString().substr(0,6).c_str(),
640 for (int i
= 0; i
< vin
.size(); i
++)
641 str
+= " " + vin
[i
].ToString() + "\n";
642 for (int i
= 0; i
< vout
.size(); i
++)
643 str
+= " " + vout
[i
].ToString() + "\n";
649 printf("%s", ToString().c_str());
654 bool DisconnectInputs(CTxDB
& txdb
);
655 bool ConnectInputs(CTxDB
& txdb
, map
<uint256
, CTxIndex
>& mapTestPool
, CDiskTxPos posThisTx
,
656 CBlockIndex
* pindexBlock
, int64
& nFees
, bool fBlock
, bool fMiner
, int64 nMinFee
=0);
657 bool ClientConnectInputs();
659 bool AcceptToMemoryPool(CTxDB
& txdb
, bool fCheckInputs
=true, bool* pfMissingInputs
=NULL
);
661 bool AcceptToMemoryPool(bool fCheckInputs
=true, bool* pfMissingInputs
=NULL
)
664 return AcceptToMemoryPool(txdb
, fCheckInputs
, pfMissingInputs
);
668 bool AddToMemoryPoolUnchecked();
670 bool RemoveFromMemoryPool();
678 // A transaction with a merkle branch linking it to the block chain
680 class CMerkleTx
: public CTransaction
684 vector
<uint256
> vMerkleBranch
;
688 mutable bool fMerkleVerified
;
689 mutable bool fGetCreditCached
;
690 mutable int64 nGetCreditCached
;
698 CMerkleTx(const CTransaction
& txIn
) : CTransaction(txIn
)
707 fMerkleVerified
= false;
708 fGetCreditCached
= false;
709 nGetCreditCached
= 0;
714 nSerSize
+= SerReadWrite(s
, *(CTransaction
*)this, nType
, nVersion
, ser_action
);
715 nVersion
= this->nVersion
;
716 READWRITE(hashBlock
);
717 READWRITE(vMerkleBranch
);
721 int64
GetCredit(bool fUseCache
=false) const
723 // Must wait until coinbase is safely deep enough in the chain before valuing it
724 if (IsCoinBase() && GetBlocksToMaturity() > 0)
727 // GetBalance can assume transactions in mapWallet won't change
728 if (fUseCache
&& fGetCreditCached
)
729 return nGetCreditCached
;
730 nGetCreditCached
= CTransaction::GetCredit();
731 fGetCreditCached
= true;
732 return nGetCreditCached
;
736 int SetMerkleBranch(const CBlock
* pblock
=NULL
);
737 int GetDepthInMainChain(int& nHeightRet
) const;
738 int GetDepthInMainChain() const { int nHeight
; return GetDepthInMainChain(nHeight
); }
739 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
740 int GetBlocksToMaturity() const;
741 bool AcceptToMemoryPool(CTxDB
& txdb
, bool fCheckInputs
=true);
742 bool AcceptToMemoryPool() { CTxDB
txdb("r"); return AcceptToMemoryPool(txdb
); }
749 // A transaction with a bunch of additional info that only the owner cares
750 // about. It includes any unrecorded transactions needed to link it back
751 // to the block chain.
753 class CWalletTx
: public CMerkleTx
756 vector
<CMerkleTx
> vtxPrev
;
757 map
<string
, string
> mapValue
;
758 vector
<pair
<string
, string
> > vOrderForm
;
759 unsigned int fTimeReceivedIsTxTime
;
760 unsigned int nTimeReceived
; // time received by this node
763 //// probably need to sign the order info so know it came from payer
765 // memory only UI hints
766 mutable unsigned int nTimeDisplayed
;
767 mutable int nLinesDisplayed
;
775 CWalletTx(const CMerkleTx
& txIn
) : CMerkleTx(txIn
)
780 CWalletTx(const CTransaction
& txIn
) : CMerkleTx(txIn
)
787 fTimeReceivedIsTxTime
= false;
797 nSerSize
+= SerReadWrite(s
, *(CMerkleTx
*)this, nType
, nVersion
, ser_action
);
798 nVersion
= this->nVersion
;
801 READWRITE(vOrderForm
);
802 READWRITE(fTimeReceivedIsTxTime
);
803 READWRITE(nTimeReceived
);
810 return CWalletDB().WriteTx(GetHash(), *this);
814 int64
GetTxTime() const;
815 int GetRequestCount() const;
817 void AddSupportingTransactions(CTxDB
& txdb
);
819 bool AcceptWalletTransaction(CTxDB
& txdb
, bool fCheckInputs
=true);
820 bool AcceptWalletTransaction() { CTxDB
txdb("r"); return AcceptWalletTransaction(txdb
); }
822 void RelayWalletTransaction(CTxDB
& txdb
);
823 void RelayWalletTransaction() { CTxDB
txdb("r"); RelayWalletTransaction(txdb
); }
830 // A txdb record that contains the disk location of a transaction and the
831 // locations of transactions that spend its outputs. vSpent is really only
832 // used as a flag, but having the location is very helpful for debugging.
838 vector
<CDiskTxPos
> vSpent
;
845 CTxIndex(const CDiskTxPos
& posIn
, unsigned int nOutputs
)
848 vSpent
.resize(nOutputs
);
853 if (!(nType
& SER_GETHASH
))
870 friend bool operator==(const CTxIndex
& a
, const CTxIndex
& b
)
872 return (a
.pos
== b
.pos
&&
873 a
.vSpent
== b
.vSpent
);
876 friend bool operator!=(const CTxIndex
& a
, const CTxIndex
& b
)
887 // Nodes collect new transactions into a block, hash them into a hash tree,
888 // and scan through nonce values to make the block's hash satisfy proof-of-work
889 // requirements. When they solve the proof-of-work, they broadcast the block
890 // to everyone and the block is added to the block chain. The first transaction
891 // in the block is a special one that creates a new coin owned by the creator
894 // Blocks are appended to blk0001.dat files on disk. Their location on disk
895 // is indexed by CBlockIndex objects in memory.
902 uint256 hashPrevBlock
;
903 uint256 hashMerkleRoot
;
909 vector
<CTransaction
> vtx
;
912 mutable vector
<uint256
> vMerkleTree
;
922 READWRITE(this->nVersion
);
923 nVersion
= this->nVersion
;
924 READWRITE(hashPrevBlock
);
925 READWRITE(hashMerkleRoot
);
930 // ConnectBlock depends on vtx being last so it can calculate offset
931 if (!(nType
& (SER_GETHASH
|SER_BLOCKHEADERONLY
)))
934 const_cast<CBlock
*>(this)->vtx
.clear();
954 uint256
GetHash() const
956 return Hash(BEGIN(nVersion
), END(nNonce
));
959 int64
GetBlockTime() const
964 int GetSigOpCount() const
967 foreach(const CTransaction
& tx
, vtx
)
968 n
+= tx
.GetSigOpCount();
973 uint256
BuildMerkleTree() const
976 foreach(const CTransaction
& tx
, vtx
)
977 vMerkleTree
.push_back(tx
.GetHash());
979 for (int nSize
= vtx
.size(); nSize
> 1; nSize
= (nSize
+ 1) / 2)
981 for (int i
= 0; i
< nSize
; i
+= 2)
983 int i2
= min(i
+1, nSize
-1);
984 vMerkleTree
.push_back(Hash(BEGIN(vMerkleTree
[j
+i
]), END(vMerkleTree
[j
+i
]),
985 BEGIN(vMerkleTree
[j
+i2
]), END(vMerkleTree
[j
+i2
])));
989 return (vMerkleTree
.empty() ? 0 : vMerkleTree
.back());
992 vector
<uint256
> GetMerkleBranch(int nIndex
) const
994 if (vMerkleTree
.empty())
996 vector
<uint256
> vMerkleBranch
;
998 for (int nSize
= vtx
.size(); nSize
> 1; nSize
= (nSize
+ 1) / 2)
1000 int i
= min(nIndex
^1, nSize
-1);
1001 vMerkleBranch
.push_back(vMerkleTree
[j
+i
]);
1005 return vMerkleBranch
;
1008 static uint256
CheckMerkleBranch(uint256 hash
, const vector
<uint256
>& vMerkleBranch
, int nIndex
)
1012 foreach(const uint256
& otherside
, vMerkleBranch
)
1015 hash
= Hash(BEGIN(otherside
), END(otherside
), BEGIN(hash
), END(hash
));
1017 hash
= Hash(BEGIN(hash
), END(hash
), BEGIN(otherside
), END(otherside
));
1024 bool WriteToDisk(bool fWriteTransactions
, unsigned int& nFileRet
, unsigned int& nBlockPosRet
)
1026 // Open history file to append
1027 CAutoFile fileout
= AppendBlockFile(nFileRet
);
1029 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
1030 if (!fWriteTransactions
)
1031 fileout
.nType
|= SER_BLOCKHEADERONLY
;
1033 // Write index header
1034 unsigned int nSize
= fileout
.GetSerializeSize(*this);
1035 fileout
<< FLATDATA(pchMessageStart
) << nSize
;
1038 nBlockPosRet
= ftell(fileout
);
1039 if (nBlockPosRet
== -1)
1040 return error("CBlock::WriteToDisk() : ftell failed");
1043 // Flush stdio buffers and commit to disk before returning
1045 if (!IsInitialBlockDownload() || (nBestHeight
+1) % 500 == 0)
1048 _commit(_fileno(fileout
));
1050 fsync(fileno(fileout
));
1057 bool ReadFromDisk(unsigned int nFile
, unsigned int nBlockPos
, bool fReadTransactions
=true)
1061 // Open history file to read
1062 CAutoFile filein
= OpenBlockFile(nFile
, nBlockPos
, "rb");
1064 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1065 if (!fReadTransactions
)
1066 filein
.nType
|= SER_BLOCKHEADERONLY
;
1072 if (!CheckProofOfWork(GetHash(), nBits
))
1073 return error("CBlock::ReadFromDisk() : errors in block header");
1082 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
1083 GetHash().ToString().substr(0,20).c_str(),
1085 hashPrevBlock
.ToString().substr(0,20).c_str(),
1086 hashMerkleRoot
.ToString().substr(0,6).c_str(),
1087 nTime
, nBits
, nNonce
,
1089 for (int i
= 0; i
< vtx
.size(); i
++)
1094 printf(" vMerkleTree: ");
1095 for (int i
= 0; i
< vMerkleTree
.size(); i
++)
1096 printf("%s ", vMerkleTree
[i
].ToString().substr(0,6).c_str());
1101 int64
GetBlockValue(int nHeight
, int64 nFees
) const;
1102 bool DisconnectBlock(CTxDB
& txdb
, CBlockIndex
* pindex
);
1103 bool ConnectBlock(CTxDB
& txdb
, CBlockIndex
* pindex
);
1104 bool ReadFromDisk(const CBlockIndex
* pindex
, bool fReadTransactions
=true);
1105 bool SetBestChain(CTxDB
& txdb
, CBlockIndex
* pindexNew
);
1106 bool AddToBlockIndex(unsigned int nFile
, unsigned int nBlockPos
);
1107 bool CheckBlock() const;
1117 // The block chain is a tree shaped structure starting with the
1118 // genesis block at the root, with each block potentially having multiple
1119 // candidates to be the next block. pprev and pnext link a path through the
1120 // main/longest chain. A blockindex may have multiple pprev pointing back
1121 // to it, but pnext will only point forward to the longest branch, or will
1122 // be null if the block is not part of the longest chain.
1127 const uint256
* phashBlock
;
1131 unsigned int nBlockPos
;
1133 CBigNum bnChainWork
;
1137 uint256 hashMerkleRoot
;
1140 unsigned int nNonce
;
1160 CBlockIndex(unsigned int nFileIn
, unsigned int nBlockPosIn
, CBlock
& block
)
1166 nBlockPos
= nBlockPosIn
;
1170 nVersion
= block
.nVersion
;
1171 hashMerkleRoot
= block
.hashMerkleRoot
;
1172 nTime
= block
.nTime
;
1173 nBits
= block
.nBits
;
1174 nNonce
= block
.nNonce
;
1177 uint256
GetBlockHash() const
1182 int64
GetBlockTime() const
1184 return (int64
)nTime
;
1187 CBigNum
GetBlockWork() const
1189 if (CBigNum().SetCompact(nBits
) <= 0)
1191 return (CBigNum(1)<<256) / (CBigNum().SetCompact(nBits
)+1);
1194 bool IsInMainChain() const
1196 return (pnext
|| this == pindexBest
);
1199 bool CheckIndex() const
1201 return CheckProofOfWork(GetBlockHash(), nBits
);
1204 bool EraseBlockFromDisk()
1206 // Open history file
1207 CAutoFile fileout
= OpenBlockFile(nFile
, nBlockPos
, "rb+");
1211 // Overwrite with empty null block
1219 enum { nMedianTimeSpan
=11 };
1221 int64
GetMedianTimePast() const
1223 int64 pmedian
[nMedianTimeSpan
];
1224 int64
* pbegin
= &pmedian
[nMedianTimeSpan
];
1225 int64
* pend
= &pmedian
[nMedianTimeSpan
];
1227 const CBlockIndex
* pindex
= this;
1228 for (int i
= 0; i
< nMedianTimeSpan
&& pindex
; i
++, pindex
= pindex
->pprev
)
1229 *(--pbegin
) = pindex
->GetBlockTime();
1232 return pbegin
[(pend
- pbegin
)/2];
1235 int64
GetMedianTime() const
1237 const CBlockIndex
* pindex
= this;
1238 for (int i
= 0; i
< nMedianTimeSpan
/2; i
++)
1241 return GetBlockTime();
1242 pindex
= pindex
->pnext
;
1244 return pindex
->GetMedianTimePast();
1249 string
ToString() const
1251 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
1252 pprev
, pnext
, nFile
, nBlockPos
, nHeight
,
1253 hashMerkleRoot
.ToString().substr(0,6).c_str(),
1254 GetBlockHash().ToString().substr(0,20).c_str());
1259 printf("%s\n", ToString().c_str());
1266 // Used to marshal pointers into hashes for db storage.
1268 class CDiskBlockIndex
: public CBlockIndex
1280 explicit CDiskBlockIndex(CBlockIndex
* pindex
) : CBlockIndex(*pindex
)
1282 hashPrev
= (pprev
? pprev
->GetBlockHash() : 0);
1283 hashNext
= (pnext
? pnext
->GetBlockHash() : 0);
1288 if (!(nType
& SER_GETHASH
))
1289 READWRITE(nVersion
);
1291 READWRITE(hashNext
);
1293 READWRITE(nBlockPos
);
1297 READWRITE(this->nVersion
);
1298 READWRITE(hashPrev
);
1299 READWRITE(hashMerkleRoot
);
1305 uint256
GetBlockHash() const
1308 block
.nVersion
= nVersion
;
1309 block
.hashPrevBlock
= hashPrev
;
1310 block
.hashMerkleRoot
= hashMerkleRoot
;
1311 block
.nTime
= nTime
;
1312 block
.nBits
= nBits
;
1313 block
.nNonce
= nNonce
;
1314 return block
.GetHash();
1318 string
ToString() const
1320 string str
= "CDiskBlockIndex(";
1321 str
+= CBlockIndex::ToString();
1322 str
+= strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1323 GetBlockHash().ToString().c_str(),
1324 hashPrev
.ToString().substr(0,20).c_str(),
1325 hashNext
.ToString().substr(0,20).c_str());
1331 printf("%s\n", ToString().c_str());
1343 // Describes a place in the block chain to another node such that if the
1344 // other node doesn't have the same branch, it can find a recent common trunk.
1345 // The further back it is, the further before the fork it may be.
1350 vector
<uint256
> vHave
;
1357 explicit CBlockLocator(const CBlockIndex
* pindex
)
1362 explicit CBlockLocator(uint256 hashBlock
)
1364 map
<uint256
, CBlockIndex
*>::iterator mi
= mapBlockIndex
.find(hashBlock
);
1365 if (mi
!= mapBlockIndex
.end())
1371 if (!(nType
& SER_GETHASH
))
1372 READWRITE(nVersion
);
1376 void Set(const CBlockIndex
* pindex
)
1382 vHave
.push_back(pindex
->GetBlockHash());
1384 // Exponentially larger steps back
1385 for (int i
= 0; pindex
&& i
< nStep
; i
++)
1386 pindex
= pindex
->pprev
;
1387 if (vHave
.size() > 10)
1390 vHave
.push_back(hashGenesisBlock
);
1393 int GetDistanceBack()
1395 // Retrace how far back it was in the sender's branch
1398 foreach(const uint256
& hash
, vHave
)
1400 map
<uint256
, CBlockIndex
*>::iterator mi
= mapBlockIndex
.find(hash
);
1401 if (mi
!= mapBlockIndex
.end())
1403 CBlockIndex
* pindex
= (*mi
).second
;
1404 if (pindex
->IsInMainChain())
1414 CBlockIndex
* GetBlockIndex()
1416 // Find the first block the caller has in the main chain
1417 foreach(const uint256
& hash
, vHave
)
1419 map
<uint256
, CBlockIndex
*>::iterator mi
= mapBlockIndex
.find(hash
);
1420 if (mi
!= mapBlockIndex
.end())
1422 CBlockIndex
* pindex
= (*mi
).second
;
1423 if (pindex
->IsInMainChain())
1427 return pindexGenesisBlock
;
1430 uint256
GetBlockHash()
1432 // Find the first block the caller has in the main chain
1433 foreach(const uint256
& hash
, vHave
)
1435 map
<uint256
, CBlockIndex
*>::iterator mi
= mapBlockIndex
.find(hash
);
1436 if (mi
!= mapBlockIndex
.end())
1438 CBlockIndex
* pindex
= (*mi
).second
;
1439 if (pindex
->IsInMainChain())
1443 return hashGenesisBlock
;
1448 CBlockIndex
* pindex
= GetBlockIndex();
1451 return pindex
->nHeight
;
1461 // Private key that includes an expiration date in case it never gets used.
1466 CPrivKey vchPrivKey
;
1470 //// todo: add something to note what created it (user, getnewaddress, change)
1471 //// maybe should have a map<string, string> property map
1473 CWalletKey(int64 nTimeExpiresIn
=0)
1475 nTimeCreated
= (nTimeExpiresIn
? GetTime() : 0);
1476 nTimeExpires
= nTimeExpiresIn
;
1481 if (!(nType
& SER_GETHASH
))
1482 READWRITE(nVersion
);
1483 READWRITE(vchPrivKey
);
1484 READWRITE(nTimeCreated
);
1485 READWRITE(nTimeExpires
);
1486 READWRITE(strComment
);
1496 // Alert messages are broadcast as a vector of signed data. Unserializing may
1497 // not read the entire buffer if the alert is for a newer version, but older
1498 // versions can still relay the original data.
1500 class CUnsignedAlert
1504 int64 nRelayUntil
; // when newer nodes stop relaying to newer nodes
1509 int nMinVer
; // lowest version inclusive
1510 int nMaxVer
; // highest version inclusive
1511 set
<string
> setSubVer
; // empty matches all
1516 string strStatusBar
;
1521 READWRITE(this->nVersion
);
1522 nVersion
= this->nVersion
;
1523 READWRITE(nRelayUntil
);
1524 READWRITE(nExpiration
);
1527 READWRITE(setCancel
);
1530 READWRITE(setSubVer
);
1531 READWRITE(nPriority
);
1533 READWRITE(strComment
);
1534 READWRITE(strStatusBar
);
1535 READWRITE(strRPCError
);
1552 strStatusBar
.clear();
1553 strRPCError
.clear();
1556 string
ToString() const
1558 string strSetCancel
;
1559 foreach(int n
, setCancel
)
1560 strSetCancel
+= strprintf("%d ", n
);
1561 string strSetSubVer
;
1562 foreach(string str
, setSubVer
)
1563 strSetSubVer
+= "\"" + str
+ "\" ";
1567 " nRelayUntil = %"PRI64d
"\n"
1568 " nExpiration = %"PRI64d
"\n"
1576 " strComment = \"%s\"\n"
1577 " strStatusBar = \"%s\"\n"
1578 " strRPCError = \"%s\"\n"
1585 strSetCancel
.c_str(),
1588 strSetSubVer
.c_str(),
1591 strStatusBar
.c_str(),
1592 strRPCError
.c_str());
1597 printf("%s", ToString().c_str());
1601 class CAlert
: public CUnsignedAlert
1604 vector
<unsigned char> vchMsg
;
1605 vector
<unsigned char> vchSig
;
1620 CUnsignedAlert::SetNull();
1627 return (nExpiration
== 0);
1630 uint256
GetHash() const
1632 return SerializeHash(*this);
1635 bool IsInEffect() const
1637 return (GetAdjustedTime() < nExpiration
);
1640 bool Cancels(const CAlert
& alert
) const
1644 return (alert
.nID
<= nCancel
|| setCancel
.count(alert
.nID
));
1647 bool AppliesTo(int nVersion
, string strSubVerIn
) const
1649 return (IsInEffect() &&
1650 nMinVer
<= nVersion
&& nVersion
<= nMaxVer
&&
1651 (setSubVer
.empty() || setSubVer
.count(strSubVerIn
)));
1654 bool AppliesToMe() const
1656 return AppliesTo(VERSION
, ::pszSubVer
);
1659 bool RelayTo(CNode
* pnode
) const
1663 // returns true if wasn't already contained in the set
1664 if (pnode
->setKnown
.insert(GetHash()).second
)
1666 if (AppliesTo(pnode
->nVersion
, pnode
->strSubVer
) ||
1668 GetAdjustedTime() < nRelayUntil
)
1670 pnode
->PushMessage("alert", *this);
1677 bool CheckSignature()
1680 if (!key
.SetPubKey(ParseHex("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284")))
1681 return error("CAlert::CheckSignature() : SetPubKey failed");
1682 if (!key
.Verify(Hash(vchMsg
.begin(), vchMsg
.end()), vchSig
))
1683 return error("CAlert::CheckSignature() : verify signature failed");
1685 // Now unserialize the data
1686 CDataStream
sMsg(vchMsg
);
1687 sMsg
>> *(CUnsignedAlert
*)this;
1691 bool ProcessAlert();
1703 extern map
<uint256
, CTransaction
> mapTransactions
;
1704 extern map
<uint256
, CWalletTx
> mapWallet
;
1705 extern vector
<uint256
> vWalletUpdated
;
1706 extern CCriticalSection cs_mapWallet
;
1707 extern map
<vector
<unsigned char>, CPrivKey
> mapKeys
;
1708 extern map
<uint160
, vector
<unsigned char> > mapPubKeys
;
1709 extern CCriticalSection cs_mapKeys
;
1710 extern CKey keyUser
;