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_SIZE
= 0x02000000;
18 static const unsigned int MAX_BLOCK_SIZE
= 1000000;
19 static const int64 COIN
= 100000000;
20 static const int64 CENT
= 1000000;
21 static const int COINBASE_MATURITY
= 100;
23 static const CBigNum
bnProofOfWorkLimit(~uint256(0) >> 32);
30 extern CCriticalSection cs_main
;
31 extern map
<uint256
, CBlockIndex
*> mapBlockIndex
;
32 extern const uint256 hashGenesisBlock
;
33 extern CBlockIndex
* pindexGenesisBlock
;
34 extern int nBestHeight
;
35 extern uint256 hashBestChain
;
36 extern CBlockIndex
* pindexBest
;
37 extern unsigned int nTransactionsUpdated
;
38 extern map
<uint256
, int> mapRequestCount
;
39 extern CCriticalSection cs_mapRequestCount
;
40 extern map
<string
, string
> mapAddressBook
;
41 extern CCriticalSection cs_mapAddressBook
;
42 extern vector
<unsigned char> vchDefaultKey
;
45 extern int fGenerateBitcoins
;
46 extern int64 nTransactionFee
;
47 extern CAddress addrIncoming
;
48 extern int fLimitProcessors
;
49 extern int nLimitProcessors
;
50 extern int fMinimizeToTray
;
51 extern int fMinimizeOnClose
;
59 bool CheckDiskSpace(int64 nAdditionalBytes
=0);
60 FILE* OpenBlockFile(unsigned int nFile
, unsigned int nBlockPos
, const char* pszMode
="rb");
61 FILE* AppendBlockFile(unsigned int& nFileRet
);
62 bool AddKey(const CKey
& key
);
63 vector
<unsigned char> GenerateNewKey();
64 bool AddToWallet(const CWalletTx
& wtxIn
);
65 void WalletUpdateSpent(const COutPoint
& prevout
);
66 void ReacceptWalletTransactions();
67 bool LoadBlockIndex(bool fAllowNew
=true);
68 void PrintBlockTree();
69 bool ProcessMessages(CNode
* pfrom
);
70 bool ProcessMessage(CNode
* pfrom
, string strCommand
, CDataStream
& vRecv
);
71 bool SendMessages(CNode
* pto
, bool fSendTrickle
);
73 bool CreateTransaction(CScript scriptPubKey
, int64 nValue
, CWalletTx
& wtxNew
, CKey
& keyRet
, int64
& nFeeRequiredRet
);
74 bool CommitTransaction(CWalletTx
& wtxNew
, const CKey
& key
);
75 bool BroadcastTransaction(CWalletTx
& wtxNew
);
76 string
SendMoney(CScript scriptPubKey
, int64 nValue
, CWalletTx
& wtxNew
, bool fAskFee
=false);
77 string
SendMoneyToBitcoinAddress(string strAddress
, int64 nValue
, CWalletTx
& wtxNew
, bool fAskFee
=false);
78 void GenerateBitcoins(bool fGenerate
);
79 void ThreadBitcoinMiner(void* parg
);
97 unsigned int nBlockPos
;
105 CDiskTxPos(unsigned int nFileIn
, unsigned int nBlockPosIn
, unsigned int nTxPosIn
)
108 nBlockPos
= nBlockPosIn
;
112 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
113 void SetNull() { nFile
= -1; nBlockPos
= 0; nTxPos
= 0; }
114 bool IsNull() const { return (nFile
== -1); }
116 friend bool operator==(const CDiskTxPos
& a
, const CDiskTxPos
& b
)
118 return (a
.nFile
== b
.nFile
&&
119 a
.nBlockPos
== b
.nBlockPos
&&
120 a
.nTxPos
== b
.nTxPos
);
123 friend bool operator!=(const CDiskTxPos
& a
, const CDiskTxPos
& b
)
128 string
ToString() const
131 return strprintf("null");
133 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile
, nBlockPos
, nTxPos
);
138 printf("%s", ToString().c_str());
151 CInPoint() { SetNull(); }
152 CInPoint(CTransaction
* ptxIn
, unsigned int nIn
) { ptx
= ptxIn
; n
= nIn
; }
153 void SetNull() { ptx
= NULL
; n
= -1; }
154 bool IsNull() const { return (ptx
== NULL
&& n
== -1); }
166 COutPoint() { SetNull(); }
167 COutPoint(uint256 hashIn
, unsigned int nIn
) { hash
= hashIn
; n
= nIn
; }
168 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
169 void SetNull() { hash
= 0; n
= -1; }
170 bool IsNull() const { return (hash
== 0 && n
== -1); }
172 friend bool operator<(const COutPoint
& a
, const COutPoint
& b
)
174 return (a
.hash
< b
.hash
|| (a
.hash
== b
.hash
&& a
.n
< b
.n
));
177 friend bool operator==(const COutPoint
& a
, const COutPoint
& b
)
179 return (a
.hash
== b
.hash
&& a
.n
== b
.n
);
182 friend bool operator!=(const COutPoint
& a
, const COutPoint
& b
)
187 string
ToString() const
189 return strprintf("COutPoint(%s, %d)", hash
.ToString().substr(0,6).c_str(), n
);
194 printf("%s\n", ToString().c_str());
202 // An input of a transaction. It contains the location of the previous
203 // transaction's output that it claims and a signature that matches the
204 // output's public key.
211 unsigned int nSequence
;
215 nSequence
= UINT_MAX
;
218 explicit CTxIn(COutPoint prevoutIn
, CScript scriptSigIn
=CScript(), unsigned int nSequenceIn
=UINT_MAX
)
221 scriptSig
= scriptSigIn
;
222 nSequence
= nSequenceIn
;
225 CTxIn(uint256 hashPrevTx
, unsigned int nOut
, CScript scriptSigIn
=CScript(), unsigned int nSequenceIn
=UINT_MAX
)
227 prevout
= COutPoint(hashPrevTx
, nOut
);
228 scriptSig
= scriptSigIn
;
229 nSequence
= nSequenceIn
;
235 READWRITE(scriptSig
);
236 READWRITE(nSequence
);
241 return (nSequence
== UINT_MAX
);
244 friend bool operator==(const CTxIn
& a
, const CTxIn
& b
)
246 return (a
.prevout
== b
.prevout
&&
247 a
.scriptSig
== b
.scriptSig
&&
248 a
.nSequence
== b
.nSequence
);
251 friend bool operator!=(const CTxIn
& a
, const CTxIn
& b
)
256 string
ToString() const
259 str
+= strprintf("CTxIn(");
260 str
+= prevout
.ToString();
261 if (prevout
.IsNull())
262 str
+= strprintf(", coinbase %s", HexStr(scriptSig
.begin(), scriptSig
.end(), false).c_str());
264 str
+= strprintf(", scriptSig=%s", scriptSig
.ToString().substr(0,24).c_str());
265 if (nSequence
!= UINT_MAX
)
266 str
+= strprintf(", nSequence=%u", nSequence
);
273 printf("%s\n", ToString().c_str());
277 int64
GetDebit() const;
284 // An output of a transaction. It contains the public key that the next input
285 // must be able to sign with to claim it.
291 CScript scriptPubKey
;
299 CTxOut(int64 nValueIn
, CScript scriptPubKeyIn
)
302 scriptPubKey
= scriptPubKeyIn
;
308 READWRITE(scriptPubKey
);
314 scriptPubKey
.clear();
319 return (nValue
== -1);
322 uint256
GetHash() const
324 return SerializeHash(*this);
329 return ::IsMine(scriptPubKey
);
332 int64
GetCredit() const
339 friend bool operator==(const CTxOut
& a
, const CTxOut
& b
)
341 return (a
.nValue
== b
.nValue
&&
342 a
.scriptPubKey
== b
.scriptPubKey
);
345 friend bool operator!=(const CTxOut
& a
, const CTxOut
& b
)
350 string
ToString() const
352 if (scriptPubKey
.size() < 6)
353 return "CTxOut(error)";
354 return strprintf("CTxOut(nValue=%"PRI64d
".%08"PRI64d
", scriptPubKey=%s)", nValue
/ COIN
, nValue
% COIN
, scriptPubKey
.ToString().substr(0,24).c_str());
359 printf("%s\n", ToString().c_str());
367 // The basic transaction that is broadcasted on the network and contained in
368 // blocks. A transaction can contain multiple inputs and outputs.
376 unsigned int nLockTime
;
386 READWRITE(this->nVersion
);
387 nVersion
= this->nVersion
;
390 READWRITE(nLockTime
);
403 return (vin
.empty() && vout
.empty());
406 uint256
GetHash() const
408 return SerializeHash(*this);
411 bool IsFinal(int64 nBlockTime
=0) const
413 // Time based nLockTime implemented in 0.1.6,
414 // do not use time based until most 0.1.5 nodes have upgraded.
418 nBlockTime
= GetAdjustedTime();
419 if (nLockTime
< (nLockTime
< 500000000 ? nBestHeight
: nBlockTime
))
421 foreach(const CTxIn
& txin
, vin
)
427 bool IsNewerThan(const CTransaction
& old
) const
429 if (vin
.size() != old
.vin
.size())
431 for (int i
= 0; i
< vin
.size(); i
++)
432 if (vin
[i
].prevout
!= old
.vin
[i
].prevout
)
436 unsigned int nLowest
= UINT_MAX
;
437 for (int i
= 0; i
< vin
.size(); i
++)
439 if (vin
[i
].nSequence
!= old
.vin
[i
].nSequence
)
441 if (vin
[i
].nSequence
<= nLowest
)
444 nLowest
= vin
[i
].nSequence
;
446 if (old
.vin
[i
].nSequence
< nLowest
)
449 nLowest
= old
.vin
[i
].nSequence
;
456 bool IsCoinBase() const
458 return (vin
.size() == 1 && vin
[0].prevout
.IsNull());
461 bool CheckTransaction() const
463 // Basic checks that don't depend on any context
464 if (vin
.empty() || vout
.empty())
465 return error("CTransaction::CheckTransaction() : vin or vout empty");
467 // Check for negative values
468 foreach(const CTxOut
& txout
, vout
)
469 if (txout
.nValue
< 0)
470 return error("CTransaction::CheckTransaction() : txout.nValue negative");
474 if (vin
[0].scriptSig
.size() < 2 || vin
[0].scriptSig
.size() > 100)
475 return error("CTransaction::CheckTransaction() : coinbase script size");
479 foreach(const CTxIn
& txin
, vin
)
480 if (txin
.prevout
.IsNull())
481 return error("CTransaction::CheckTransaction() : prevout is null");
489 foreach(const CTxOut
& txout
, vout
)
495 int64
GetDebit() const
498 foreach(const CTxIn
& txin
, vin
)
499 nDebit
+= txin
.GetDebit();
503 int64
GetCredit() const
506 foreach(const CTxOut
& txout
, vout
)
507 nCredit
+= txout
.GetCredit();
511 int64
GetValueOut() const
514 foreach(const CTxOut
& txout
, vout
)
516 if (txout
.nValue
< 0)
517 throw runtime_error("CTransaction::GetValueOut() : negative value");
518 nValueOut
+= txout
.nValue
;
523 int64
GetMinFee(unsigned int nBlockSize
=1) const
525 // Base fee is 1 cent per kilobyte
526 unsigned int nBytes
= ::GetSerializeSize(*this, SER_NETWORK
);
527 int64 nMinFee
= (1 + (int64
)nBytes
/ 1000) * CENT
;
529 // Transactions under 60K are free as long as block size is under 80K
530 // (about 27,000bc if made of 50bc inputs)
531 if (nBytes
< 60000 && nBlockSize
< 80000)
534 // Transactions under 3K are free as long as block size is under 200K
535 if (nBytes
< 3000 && nBlockSize
< 200000)
538 // To limit dust spam, require a 0.01 fee if any output is less than 0.01
540 foreach(const CTxOut
& txout
, vout
)
541 if (txout
.nValue
< CENT
)
549 bool ReadFromDisk(CDiskTxPos pos
, FILE** pfileRet
=NULL
)
551 CAutoFile filein
= OpenBlockFile(pos
.nFile
, 0, pfileRet
? "rb+" : "rb");
553 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
556 if (fseek(filein
, pos
.nTxPos
, SEEK_SET
) != 0)
557 return error("CTransaction::ReadFromDisk() : fseek failed");
560 // Return file pointer
563 if (fseek(filein
, pos
.nTxPos
, SEEK_SET
) != 0)
564 return error("CTransaction::ReadFromDisk() : second fseek failed");
565 *pfileRet
= filein
.release();
571 friend bool operator==(const CTransaction
& a
, const CTransaction
& b
)
573 return (a
.nVersion
== b
.nVersion
&&
576 a
.nLockTime
== b
.nLockTime
);
579 friend bool operator!=(const CTransaction
& a
, const CTransaction
& b
)
585 string
ToString() const
588 str
+= strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
589 GetHash().ToString().substr(0,6).c_str(),
594 for (int i
= 0; i
< vin
.size(); i
++)
595 str
+= " " + vin
[i
].ToString() + "\n";
596 for (int i
= 0; i
< vout
.size(); i
++)
597 str
+= " " + vout
[i
].ToString() + "\n";
603 printf("%s", ToString().c_str());
608 bool DisconnectInputs(CTxDB
& txdb
);
609 bool ConnectInputs(CTxDB
& txdb
, map
<uint256
, CTxIndex
>& mapTestPool
, CDiskTxPos posThisTx
, int nHeight
, int64
& nFees
, bool fBlock
, bool fMiner
, int64 nMinFee
=0);
610 bool ClientConnectInputs();
612 bool AcceptTransaction(CTxDB
& txdb
, bool fCheckInputs
=true, bool* pfMissingInputs
=NULL
);
614 bool AcceptTransaction(bool fCheckInputs
=true, bool* pfMissingInputs
=NULL
)
617 return AcceptTransaction(txdb
, fCheckInputs
, pfMissingInputs
);
621 bool AddToMemoryPool();
623 bool RemoveFromMemoryPool();
631 // A transaction with a merkle branch linking it to the block chain
633 class CMerkleTx
: public CTransaction
637 vector
<uint256
> vMerkleBranch
;
641 mutable bool fMerkleVerified
;
642 mutable bool fGetCreditCached
;
643 mutable int64 nGetCreditCached
;
651 CMerkleTx(const CTransaction
& txIn
) : CTransaction(txIn
)
660 fMerkleVerified
= false;
661 fGetCreditCached
= false;
662 nGetCreditCached
= 0;
667 nSerSize
+= SerReadWrite(s
, *(CTransaction
*)this, nType
, nVersion
, ser_action
);
668 nVersion
= this->nVersion
;
669 READWRITE(hashBlock
);
670 READWRITE(vMerkleBranch
);
674 int64
GetCredit(bool fUseCache
=false) const
676 // Must wait until coinbase is safely deep enough in the chain before valuing it
677 if (IsCoinBase() && GetBlocksToMaturity() > 0)
680 // GetBalance can assume transactions in mapWallet won't change
681 if (fUseCache
&& fGetCreditCached
)
682 return nGetCreditCached
;
683 nGetCreditCached
= CTransaction::GetCredit();
684 fGetCreditCached
= true;
685 return nGetCreditCached
;
689 int SetMerkleBranch(const CBlock
* pblock
=NULL
);
690 int GetDepthInMainChain(int& nHeightRet
) const;
691 int GetDepthInMainChain() const { int nHeight
; return GetDepthInMainChain(nHeight
); }
692 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
693 int GetBlocksToMaturity() const;
694 bool AcceptTransaction(CTxDB
& txdb
, bool fCheckInputs
=true);
695 bool AcceptTransaction() { CTxDB
txdb("r"); return AcceptTransaction(txdb
); }
702 // A transaction with a bunch of additional info that only the owner cares
703 // about. It includes any unrecorded transactions needed to link it back
704 // to the block chain.
706 class CWalletTx
: public CMerkleTx
709 vector
<CMerkleTx
> vtxPrev
;
710 map
<string
, string
> mapValue
;
711 vector
<pair
<string
, string
> > vOrderForm
;
712 unsigned int fTimeReceivedIsTxTime
;
713 unsigned int nTimeReceived
; // time received by this node
716 //// probably need to sign the order info so know it came from payer
718 // memory only UI hints
719 mutable unsigned int nTimeDisplayed
;
720 mutable int nLinesDisplayed
;
728 CWalletTx(const CMerkleTx
& txIn
) : CMerkleTx(txIn
)
733 CWalletTx(const CTransaction
& txIn
) : CMerkleTx(txIn
)
740 fTimeReceivedIsTxTime
= false;
750 nSerSize
+= SerReadWrite(s
, *(CMerkleTx
*)this, nType
, nVersion
, ser_action
);
751 nVersion
= this->nVersion
;
754 READWRITE(vOrderForm
);
755 READWRITE(fTimeReceivedIsTxTime
);
756 READWRITE(nTimeReceived
);
763 return CWalletDB().WriteTx(GetHash(), *this);
767 int64
GetTxTime() const;
768 int GetRequestCount() const;
770 void AddSupportingTransactions(CTxDB
& txdb
);
772 bool AcceptWalletTransaction(CTxDB
& txdb
, bool fCheckInputs
=true);
773 bool AcceptWalletTransaction() { CTxDB
txdb("r"); return AcceptWalletTransaction(txdb
); }
775 void RelayWalletTransaction(CTxDB
& txdb
);
776 void RelayWalletTransaction() { CTxDB
txdb("r"); RelayWalletTransaction(txdb
); }
783 // A txdb record that contains the disk location of a transaction and the
784 // locations of transactions that spend its outputs. vSpent is really only
785 // used as a flag, but having the location is very helpful for debugging.
791 vector
<CDiskTxPos
> vSpent
;
798 CTxIndex(const CDiskTxPos
& posIn
, unsigned int nOutputs
)
801 vSpent
.resize(nOutputs
);
806 if (!(nType
& SER_GETHASH
))
823 friend bool operator==(const CTxIndex
& a
, const CTxIndex
& b
)
825 if (a
.pos
!= b
.pos
|| a
.vSpent
.size() != b
.vSpent
.size())
827 for (int i
= 0; i
< a
.vSpent
.size(); i
++)
828 if (a
.vSpent
[i
] != b
.vSpent
[i
])
833 friend bool operator!=(const CTxIndex
& a
, const CTxIndex
& b
)
844 // Nodes collect new transactions into a block, hash them into a hash tree,
845 // and scan through nonce values to make the block's hash satisfy proof-of-work
846 // requirements. When they solve the proof-of-work, they broadcast the block
847 // to everyone and the block is added to the block chain. The first transaction
848 // in the block is a special one that creates a new coin owned by the creator
851 // Blocks are appended to blk0001.dat files on disk. Their location on disk
852 // is indexed by CBlockIndex objects in memory.
859 uint256 hashPrevBlock
;
860 uint256 hashMerkleRoot
;
866 vector
<CTransaction
> vtx
;
869 mutable vector
<uint256
> vMerkleTree
;
879 READWRITE(this->nVersion
);
880 nVersion
= this->nVersion
;
881 READWRITE(hashPrevBlock
);
882 READWRITE(hashMerkleRoot
);
887 // ConnectBlock depends on vtx being last so it can calculate offset
888 if (!(nType
& (SER_GETHASH
|SER_BLOCKHEADERONLY
)))
891 const_cast<CBlock
*>(this)->vtx
.clear();
911 uint256
GetHash() const
913 return Hash(BEGIN(nVersion
), END(nNonce
));
917 uint256
BuildMerkleTree() const
920 foreach(const CTransaction
& tx
, vtx
)
921 vMerkleTree
.push_back(tx
.GetHash());
923 for (int nSize
= vtx
.size(); nSize
> 1; nSize
= (nSize
+ 1) / 2)
925 for (int i
= 0; i
< nSize
; i
+= 2)
927 int i2
= min(i
+1, nSize
-1);
928 vMerkleTree
.push_back(Hash(BEGIN(vMerkleTree
[j
+i
]), END(vMerkleTree
[j
+i
]),
929 BEGIN(vMerkleTree
[j
+i2
]), END(vMerkleTree
[j
+i2
])));
933 return (vMerkleTree
.empty() ? 0 : vMerkleTree
.back());
936 vector
<uint256
> GetMerkleBranch(int nIndex
) const
938 if (vMerkleTree
.empty())
940 vector
<uint256
> vMerkleBranch
;
942 for (int nSize
= vtx
.size(); nSize
> 1; nSize
= (nSize
+ 1) / 2)
944 int i
= min(nIndex
^1, nSize
-1);
945 vMerkleBranch
.push_back(vMerkleTree
[j
+i
]);
949 return vMerkleBranch
;
952 static uint256
CheckMerkleBranch(uint256 hash
, const vector
<uint256
>& vMerkleBranch
, int nIndex
)
956 foreach(const uint256
& otherside
, vMerkleBranch
)
959 hash
= Hash(BEGIN(otherside
), END(otherside
), BEGIN(hash
), END(hash
));
961 hash
= Hash(BEGIN(hash
), END(hash
), BEGIN(otherside
), END(otherside
));
968 bool WriteToDisk(bool fWriteTransactions
, unsigned int& nFileRet
, unsigned int& nBlockPosRet
)
970 // Open history file to append
971 CAutoFile fileout
= AppendBlockFile(nFileRet
);
973 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
974 if (!fWriteTransactions
)
975 fileout
.nType
|= SER_BLOCKHEADERONLY
;
977 // Write index header
978 unsigned int nSize
= fileout
.GetSerializeSize(*this);
979 fileout
<< FLATDATA(pchMessageStart
) << nSize
;
982 nBlockPosRet
= ftell(fileout
);
983 if (nBlockPosRet
== -1)
984 return error("CBlock::WriteToDisk() : ftell failed");
987 // Flush stdio buffers and commit to disk before returning
990 _commit(_fileno(fileout
));
992 fsync(fileno(fileout
));
998 bool ReadFromDisk(unsigned int nFile
, unsigned int nBlockPos
, bool fReadTransactions
=true)
1002 // Open history file to read
1003 CAutoFile filein
= OpenBlockFile(nFile
, nBlockPos
, "rb");
1005 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1006 if (!fReadTransactions
)
1007 filein
.nType
|= SER_BLOCKHEADERONLY
;
1013 if (CBigNum().SetCompact(nBits
) > bnProofOfWorkLimit
)
1014 return error("CBlock::ReadFromDisk() : nBits errors in block header");
1015 if (GetHash() > CBigNum().SetCompact(nBits
).getuint256())
1016 return error("CBlock::ReadFromDisk() : GetHash() errors in block header");
1025 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
1026 GetHash().ToString().substr(0,16).c_str(),
1028 hashPrevBlock
.ToString().substr(0,16).c_str(),
1029 hashMerkleRoot
.ToString().substr(0,6).c_str(),
1030 nTime
, nBits
, nNonce
,
1032 for (int i
= 0; i
< vtx
.size(); i
++)
1037 printf(" vMerkleTree: ");
1038 for (int i
= 0; i
< vMerkleTree
.size(); i
++)
1039 printf("%s ", vMerkleTree
[i
].ToString().substr(0,6).c_str());
1044 int64
GetBlockValue(int64 nFees
) const;
1045 bool DisconnectBlock(CTxDB
& txdb
, CBlockIndex
* pindex
);
1046 bool ConnectBlock(CTxDB
& txdb
, CBlockIndex
* pindex
);
1047 bool ReadFromDisk(const CBlockIndex
* blockindex
, bool fReadTransactions
=true);
1048 bool AddToBlockIndex(unsigned int nFile
, unsigned int nBlockPos
);
1049 bool CheckBlock() const;
1059 // The block chain is a tree shaped structure starting with the
1060 // genesis block at the root, with each block potentially having multiple
1061 // candidates to be the next block. pprev and pnext link a path through the
1062 // main/longest chain. A blockindex may have multiple pprev pointing back
1063 // to it, but pnext will only point forward to the longest branch, or will
1064 // be null if the block is not part of the longest chain.
1069 const uint256
* phashBlock
;
1073 unsigned int nBlockPos
;
1078 uint256 hashMerkleRoot
;
1081 unsigned int nNonce
;
1100 CBlockIndex(unsigned int nFileIn
, unsigned int nBlockPosIn
, CBlock
& block
)
1106 nBlockPos
= nBlockPosIn
;
1109 nVersion
= block
.nVersion
;
1110 hashMerkleRoot
= block
.hashMerkleRoot
;
1111 nTime
= block
.nTime
;
1112 nBits
= block
.nBits
;
1113 nNonce
= block
.nNonce
;
1116 uint256
GetBlockHash() const
1121 bool IsInMainChain() const
1123 return (pnext
|| this == pindexBest
);
1126 bool EraseBlockFromDisk()
1128 // Open history file
1129 CAutoFile fileout
= OpenBlockFile(nFile
, nBlockPos
, "rb+");
1133 // Overwrite with empty null block
1141 enum { nMedianTimeSpan
=11 };
1143 int64
GetMedianTimePast() const
1145 unsigned int pmedian
[nMedianTimeSpan
];
1146 unsigned int* pbegin
= &pmedian
[nMedianTimeSpan
];
1147 unsigned int* pend
= &pmedian
[nMedianTimeSpan
];
1149 const CBlockIndex
* pindex
= this;
1150 for (int i
= 0; i
< nMedianTimeSpan
&& pindex
; i
++, pindex
= pindex
->pprev
)
1151 *(--pbegin
) = pindex
->nTime
;
1154 return pbegin
[(pend
- pbegin
)/2];
1157 int64
GetMedianTime() const
1159 const CBlockIndex
* pindex
= this;
1160 for (int i
= 0; i
< nMedianTimeSpan
/2; i
++)
1164 pindex
= pindex
->pnext
;
1166 return pindex
->GetMedianTimePast();
1171 string
ToString() const
1173 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
1174 pprev
, pnext
, nFile
, nBlockPos
, nHeight
,
1175 hashMerkleRoot
.ToString().substr(0,6).c_str(),
1176 GetBlockHash().ToString().substr(0,16).c_str());
1181 printf("%s\n", ToString().c_str());
1188 // Used to marshal pointers into hashes for db storage.
1190 class CDiskBlockIndex
: public CBlockIndex
1202 explicit CDiskBlockIndex(CBlockIndex
* pindex
) : CBlockIndex(*pindex
)
1204 hashPrev
= (pprev
? pprev
->GetBlockHash() : 0);
1205 hashNext
= (pnext
? pnext
->GetBlockHash() : 0);
1210 if (!(nType
& SER_GETHASH
))
1211 READWRITE(nVersion
);
1213 READWRITE(hashNext
);
1215 READWRITE(nBlockPos
);
1219 READWRITE(this->nVersion
);
1220 READWRITE(hashPrev
);
1221 READWRITE(hashMerkleRoot
);
1227 uint256
GetBlockHash() const
1230 block
.nVersion
= nVersion
;
1231 block
.hashPrevBlock
= hashPrev
;
1232 block
.hashMerkleRoot
= hashMerkleRoot
;
1233 block
.nTime
= nTime
;
1234 block
.nBits
= nBits
;
1235 block
.nNonce
= nNonce
;
1236 return block
.GetHash();
1240 string
ToString() const
1242 string str
= "CDiskBlockIndex(";
1243 str
+= CBlockIndex::ToString();
1244 str
+= strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1245 GetBlockHash().ToString().c_str(),
1246 hashPrev
.ToString().substr(0,16).c_str(),
1247 hashNext
.ToString().substr(0,16).c_str());
1253 printf("%s\n", ToString().c_str());
1265 // Describes a place in the block chain to another node such that if the
1266 // other node doesn't have the same branch, it can find a recent common trunk.
1267 // The further back it is, the further before the fork it may be.
1272 vector
<uint256
> vHave
;
1279 explicit CBlockLocator(const CBlockIndex
* pindex
)
1284 explicit CBlockLocator(uint256 hashBlock
)
1286 map
<uint256
, CBlockIndex
*>::iterator mi
= mapBlockIndex
.find(hashBlock
);
1287 if (mi
!= mapBlockIndex
.end())
1293 if (!(nType
& SER_GETHASH
))
1294 READWRITE(nVersion
);
1298 void Set(const CBlockIndex
* pindex
)
1304 vHave
.push_back(pindex
->GetBlockHash());
1306 // Exponentially larger steps back
1307 for (int i
= 0; pindex
&& i
< nStep
; i
++)
1308 pindex
= pindex
->pprev
;
1309 if (vHave
.size() > 10)
1312 vHave
.push_back(hashGenesisBlock
);
1315 int GetDistanceBack()
1317 // Retrace how far back it was in the sender's branch
1320 foreach(const uint256
& hash
, vHave
)
1322 map
<uint256
, CBlockIndex
*>::iterator mi
= mapBlockIndex
.find(hash
);
1323 if (mi
!= mapBlockIndex
.end())
1325 CBlockIndex
* pindex
= (*mi
).second
;
1326 if (pindex
->IsInMainChain())
1336 CBlockIndex
* GetBlockIndex()
1338 // Find the first block the caller has in the main chain
1339 foreach(const uint256
& hash
, vHave
)
1341 map
<uint256
, CBlockIndex
*>::iterator mi
= mapBlockIndex
.find(hash
);
1342 if (mi
!= mapBlockIndex
.end())
1344 CBlockIndex
* pindex
= (*mi
).second
;
1345 if (pindex
->IsInMainChain())
1349 return pindexGenesisBlock
;
1352 uint256
GetBlockHash()
1354 // Find the first block the caller has in the main chain
1355 foreach(const uint256
& hash
, vHave
)
1357 map
<uint256
, CBlockIndex
*>::iterator mi
= mapBlockIndex
.find(hash
);
1358 if (mi
!= mapBlockIndex
.end())
1360 CBlockIndex
* pindex
= (*mi
).second
;
1361 if (pindex
->IsInMainChain())
1365 return hashGenesisBlock
;
1370 CBlockIndex
* pindex
= GetBlockIndex();
1373 return pindex
->nHeight
;
1383 // Private key that includes an expiration date in case it never gets used.
1388 CPrivKey vchPrivKey
;
1392 //// todo: add something to note what created it (user, getnewaddress, change)
1393 //// maybe should have a map<string, string> property map
1395 CWalletKey(int64 nTimeExpiresIn
=0)
1397 nTimeCreated
= (nTimeExpiresIn
? GetTime() : 0);
1398 nTimeExpires
= nTimeExpiresIn
;
1403 if (!(nType
& SER_GETHASH
))
1404 READWRITE(nVersion
);
1405 READWRITE(vchPrivKey
);
1406 READWRITE(nTimeCreated
);
1407 READWRITE(nTimeExpires
);
1408 READWRITE(strComment
);
1417 extern map
<uint256
, CTransaction
> mapTransactions
;
1418 extern map
<uint256
, CWalletTx
> mapWallet
;
1419 extern vector
<uint256
> vWalletUpdated
;
1420 extern CCriticalSection cs_mapWallet
;
1421 extern map
<vector
<unsigned char>, CPrivKey
> mapKeys
;
1422 extern map
<uint160
, vector
<unsigned char> > mapPubKeys
;
1423 extern CCriticalSection cs_mapKeys
;
1424 extern CKey keyUser
;