1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
23 class CRequestTracker
;
26 static const unsigned int MAX_BLOCK_SIZE
= 1000000;
27 static const unsigned int MAX_BLOCK_SIZE_GEN
= MAX_BLOCK_SIZE
/2;
28 static const unsigned int MAX_BLOCK_SIGOPS
= MAX_BLOCK_SIZE
/50;
29 static const unsigned int MAX_ORPHAN_TRANSACTIONS
= MAX_BLOCK_SIZE
/100;
30 static const int64 MIN_TX_FEE
= 50000;
31 static const int64 MIN_RELAY_TX_FEE
= 10000;
32 static const int64 MAX_MONEY
= 21000000 * COIN
;
33 inline bool MoneyRange(int64 nValue
) { return (nValue
>= 0 && nValue
<= MAX_MONEY
); }
34 static const int COINBASE_MATURITY
= 100;
35 // Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp.
36 static const unsigned int LOCKTIME_THRESHOLD
= 500000000; // Tue Nov 5 00:53:20 1985 UTC
38 static const int fHaveUPnP
= true;
40 static const int fHaveUPnP
= false;
44 extern CScript COINBASE_FLAGS
;
51 extern CCriticalSection cs_main
;
52 extern std::map
<uint256
, CBlockIndex
*> mapBlockIndex
;
53 extern uint256 hashGenesisBlock
;
54 extern CBlockIndex
* pindexGenesisBlock
;
55 extern int nBestHeight
;
56 extern CBigNum bnBestChainWork
;
57 extern CBigNum bnBestInvalidWork
;
58 extern uint256 hashBestChain
;
59 extern CBlockIndex
* pindexBest
;
60 extern unsigned int nTransactionsUpdated
;
61 extern uint64 nLastBlockTx
;
62 extern uint64 nLastBlockSize
;
63 extern const std::string strMessageMagic
;
64 extern double dHashesPerSec
;
65 extern int64 nHPSTimerStart
;
66 extern int64 nTimeBestReceived
;
67 extern CCriticalSection cs_setpwalletRegistered
;
68 extern std::set
<CWallet
*> setpwalletRegistered
;
69 extern unsigned char pchMessageStart
[4];
72 extern int64 nTransactionFee
;
82 void RegisterWallet(CWallet
* pwalletIn
);
83 void UnregisterWallet(CWallet
* pwalletIn
);
84 bool ProcessBlock(CNode
* pfrom
, CBlock
* pblock
);
85 bool CheckDiskSpace(uint64 nAdditionalBytes
=0);
86 FILE* OpenBlockFile(unsigned int nFile
, unsigned int nBlockPos
, const char* pszMode
="rb");
87 FILE* AppendBlockFile(unsigned int& nFileRet
);
88 bool LoadBlockIndex(bool fAllowNew
=true);
89 void PrintBlockTree();
90 bool ProcessMessages(CNode
* pfrom
);
91 bool SendMessages(CNode
* pto
, bool fSendTrickle
);
92 bool LoadExternalBlockFile(FILE* fileIn
);
93 void GenerateBitcoins(bool fGenerate
, CWallet
* pwallet
);
94 CBlock
* CreateNewBlock(CReserveKey
& reservekey
);
95 void IncrementExtraNonce(CBlock
* pblock
, CBlockIndex
* pindexPrev
, unsigned int& nExtraNonce
);
96 void FormatHashBuffers(CBlock
* pblock
, char* pmidstate
, char* pdata
, char* phash1
);
97 bool CheckWork(CBlock
* pblock
, CWallet
& wallet
, CReserveKey
& reservekey
);
98 bool CheckProofOfWork(uint256 hash
, unsigned int nBits
);
99 unsigned int ComputeMinWork(unsigned int nBase
, int64 nTime
);
100 int GetNumBlocksOfPeers();
101 bool IsInitialBlockDownload();
102 std::string
GetWarnings(std::string strFor
);
103 bool GetTransaction(const uint256
&hash
, CTransaction
&tx
, uint256
&hashBlock
);
115 bool GetWalletFile(CWallet
* pwallet
, std::string
&strWalletFileOut
);
117 /** Position on disk for a particular transaction. */
122 unsigned int nBlockPos
;
130 CDiskTxPos(unsigned int nFileIn
, unsigned int nBlockPosIn
, unsigned int nTxPosIn
)
133 nBlockPos
= nBlockPosIn
;
137 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
138 void SetNull() { nFile
= (unsigned int) -1; nBlockPos
= 0; nTxPos
= 0; }
139 bool IsNull() const { return (nFile
== (unsigned int) -1); }
141 friend bool operator==(const CDiskTxPos
& a
, const CDiskTxPos
& b
)
143 return (a
.nFile
== b
.nFile
&&
144 a
.nBlockPos
== b
.nBlockPos
&&
145 a
.nTxPos
== b
.nTxPos
);
148 friend bool operator!=(const CDiskTxPos
& a
, const CDiskTxPos
& b
)
153 std::string
ToString() const
158 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile
, nBlockPos
, nTxPos
);
163 printf("%s", ToString().c_str());
169 /** An inpoint - a combination of a transaction and an index n into its vin */
176 CInPoint() { SetNull(); }
177 CInPoint(CTransaction
* ptxIn
, unsigned int nIn
) { ptx
= ptxIn
; n
= nIn
; }
178 void SetNull() { ptx
= NULL
; n
= (unsigned int) -1; }
179 bool IsNull() const { return (ptx
== NULL
&& n
== (unsigned int) -1); }
184 /** An outpoint - a combination of a transaction hash and an index n into its vout */
191 COutPoint() { SetNull(); }
192 COutPoint(uint256 hashIn
, unsigned int nIn
) { hash
= hashIn
; n
= nIn
; }
193 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
194 void SetNull() { hash
= 0; n
= (unsigned int) -1; }
195 bool IsNull() const { return (hash
== 0 && n
== (unsigned int) -1); }
197 friend bool operator<(const COutPoint
& a
, const COutPoint
& b
)
199 return (a
.hash
< b
.hash
|| (a
.hash
== b
.hash
&& a
.n
< b
.n
));
202 friend bool operator==(const COutPoint
& a
, const COutPoint
& b
)
204 return (a
.hash
== b
.hash
&& a
.n
== b
.n
);
207 friend bool operator!=(const COutPoint
& a
, const COutPoint
& b
)
212 std::string
ToString() const
214 return strprintf("COutPoint(%s, %d)", hash
.ToString().substr(0,10).c_str(), n
);
219 printf("%s\n", ToString().c_str());
226 /** An input of a transaction. It contains the location of the previous
227 * transaction's output that it claims and a signature that matches the
228 * output's public key.
235 unsigned int nSequence
;
239 nSequence
= std::numeric_limits
<unsigned int>::max();
242 explicit CTxIn(COutPoint prevoutIn
, CScript scriptSigIn
=CScript(), unsigned int nSequenceIn
=std::numeric_limits
<unsigned int>::max())
245 scriptSig
= scriptSigIn
;
246 nSequence
= nSequenceIn
;
249 CTxIn(uint256 hashPrevTx
, unsigned int nOut
, CScript scriptSigIn
=CScript(), unsigned int nSequenceIn
=std::numeric_limits
<unsigned int>::max())
251 prevout
= COutPoint(hashPrevTx
, nOut
);
252 scriptSig
= scriptSigIn
;
253 nSequence
= nSequenceIn
;
259 READWRITE(scriptSig
);
260 READWRITE(nSequence
);
265 return (nSequence
== std::numeric_limits
<unsigned int>::max());
268 friend bool operator==(const CTxIn
& a
, const CTxIn
& b
)
270 return (a
.prevout
== b
.prevout
&&
271 a
.scriptSig
== b
.scriptSig
&&
272 a
.nSequence
== b
.nSequence
);
275 friend bool operator!=(const CTxIn
& a
, const CTxIn
& b
)
280 std::string
ToString() const
284 str
+= prevout
.ToString();
285 if (prevout
.IsNull())
286 str
+= strprintf(", coinbase %s", HexStr(scriptSig
).c_str());
288 str
+= strprintf(", scriptSig=%s", scriptSig
.ToString().substr(0,24).c_str());
289 if (nSequence
!= std::numeric_limits
<unsigned int>::max())
290 str
+= strprintf(", nSequence=%u", nSequence
);
297 printf("%s\n", ToString().c_str());
304 /** An output of a transaction. It contains the public key that the next input
305 * must be able to sign with to claim it.
311 CScript scriptPubKey
;
318 CTxOut(int64 nValueIn
, CScript scriptPubKeyIn
)
321 scriptPubKey
= scriptPubKeyIn
;
327 READWRITE(scriptPubKey
);
333 scriptPubKey
.clear();
338 return (nValue
== -1);
341 uint256
GetHash() const
343 return SerializeHash(*this);
346 friend bool operator==(const CTxOut
& a
, const CTxOut
& b
)
348 return (a
.nValue
== b
.nValue
&&
349 a
.scriptPubKey
== b
.scriptPubKey
);
352 friend bool operator!=(const CTxOut
& a
, const CTxOut
& b
)
357 std::string
ToString() const
359 if (scriptPubKey
.size() < 6)
360 return "CTxOut(error)";
361 return strprintf("CTxOut(nValue=%"PRI64d
".%08"PRI64d
", scriptPubKey=%s)", nValue
/ COIN
, nValue
% COIN
, scriptPubKey
.ToString().substr(0,30).c_str());
366 printf("%s\n", ToString().c_str());
380 typedef std::map
<uint256
, std::pair
<CTxIndex
, CTransaction
> > MapPrevTx
;
382 /** The basic transaction that is broadcasted on the network and contained in
383 * blocks. A transaction can contain multiple inputs and outputs.
389 std::vector
<CTxIn
> vin
;
390 std::vector
<CTxOut
> vout
;
391 unsigned int nLockTime
;
393 // Denial-of-service detection:
395 bool DoS(int nDoSIn
, bool fIn
) const { nDoS
+= nDoSIn
; return fIn
; }
404 READWRITE(this->nVersion
);
405 nVersion
= this->nVersion
;
408 READWRITE(nLockTime
);
417 nDoS
= 0; // Denial-of-service prevention
422 return (vin
.empty() && vout
.empty());
425 uint256
GetHash() const
427 return SerializeHash(*this);
430 bool IsFinal(int nBlockHeight
=0, int64 nBlockTime
=0) const
432 // Time based nLockTime implemented in 0.1.6
435 if (nBlockHeight
== 0)
436 nBlockHeight
= nBestHeight
;
438 nBlockTime
= GetAdjustedTime();
439 if ((int64
)nLockTime
< ((int64
)nLockTime
< LOCKTIME_THRESHOLD
? (int64
)nBlockHeight
: nBlockTime
))
441 BOOST_FOREACH(const CTxIn
& txin
, vin
)
447 bool IsNewerThan(const CTransaction
& old
) const
449 if (vin
.size() != old
.vin
.size())
451 for (unsigned int i
= 0; i
< vin
.size(); i
++)
452 if (vin
[i
].prevout
!= old
.vin
[i
].prevout
)
456 unsigned int nLowest
= std::numeric_limits
<unsigned int>::max();
457 for (unsigned int i
= 0; i
< vin
.size(); i
++)
459 if (vin
[i
].nSequence
!= old
.vin
[i
].nSequence
)
461 if (vin
[i
].nSequence
<= nLowest
)
464 nLowest
= vin
[i
].nSequence
;
466 if (old
.vin
[i
].nSequence
< nLowest
)
469 nLowest
= old
.vin
[i
].nSequence
;
476 bool IsCoinBase() const
478 return (vin
.size() == 1 && vin
[0].prevout
.IsNull());
481 /** Check for standard transaction types
482 @return True if all outputs (scriptPubKeys) use only standard transaction forms
484 bool IsStandard() const;
486 /** Check for standard transaction types
487 @param[in] mapInputs Map of previous transactions that have outputs we're spending
488 @return True if all inputs (scriptSigs) use only standard transaction forms
489 @see CTransaction::FetchInputs
491 bool AreInputsStandard(const MapPrevTx
& mapInputs
) const;
493 /** Count ECDSA signature operations the old-fashioned (pre-0.6) way
494 @return number of sigops this transaction's outputs will produce when spent
495 @see CTransaction::FetchInputs
497 unsigned int GetLegacySigOpCount() const;
499 /** Count ECDSA signature operations in pay-to-script-hash inputs.
501 @param[in] mapInputs Map of previous transactions that have outputs we're spending
502 @return maximum number of sigops required to validate this transaction's inputs
503 @see CTransaction::FetchInputs
505 unsigned int GetP2SHSigOpCount(const MapPrevTx
& mapInputs
) const;
507 /** Amount of bitcoins spent by this transaction.
508 @return sum of all outputs (note: does not include fees)
510 int64
GetValueOut() const
513 BOOST_FOREACH(const CTxOut
& txout
, vout
)
515 nValueOut
+= txout
.nValue
;
516 if (!MoneyRange(txout
.nValue
) || !MoneyRange(nValueOut
))
517 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
522 /** Amount of bitcoins coming in to this transaction
523 Note that lightweight clients may not know anything besides the hash of previous transactions,
524 so may not be able to calculate this.
526 @param[in] mapInputs Map of previous transactions that have outputs we're spending
527 @return Sum of value of all inputs (scriptSigs)
528 @see CTransaction::FetchInputs
530 int64
GetValueIn(const MapPrevTx
& mapInputs
) const;
532 static bool AllowFree(double dPriority
)
534 // Large (in bytes) low-priority (new, small-coin) transactions
536 return dPriority
> COIN
* 144 / 250;
539 int64
GetMinFee(unsigned int nBlockSize
=1, bool fAllowFree
=true, enum GetMinFee_mode mode
=GMF_BLOCK
) const
541 // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
542 int64 nBaseFee
= (mode
== GMF_RELAY
) ? MIN_RELAY_TX_FEE
: MIN_TX_FEE
;
544 unsigned int nBytes
= ::GetSerializeSize(*this, SER_NETWORK
, PROTOCOL_VERSION
);
545 unsigned int nNewBlockSize
= nBlockSize
+ nBytes
;
546 int64 nMinFee
= (1 + (int64
)nBytes
/ 1000) * nBaseFee
;
552 // Transactions under 10K are free
553 // (about 4500bc if made of 50bc inputs)
559 // Free transaction area
560 if (nNewBlockSize
< 27000)
565 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
566 if (nMinFee
< nBaseFee
)
568 BOOST_FOREACH(const CTxOut
& txout
, vout
)
569 if (txout
.nValue
< CENT
)
573 // Raise the price as the block approaches full
574 if (nBlockSize
!= 1 && nNewBlockSize
>= MAX_BLOCK_SIZE_GEN
/2)
576 if (nNewBlockSize
>= MAX_BLOCK_SIZE_GEN
)
578 nMinFee
*= MAX_BLOCK_SIZE_GEN
/ (MAX_BLOCK_SIZE_GEN
- nNewBlockSize
);
581 if (!MoneyRange(nMinFee
))
587 bool ReadFromDisk(CDiskTxPos pos
, FILE** pfileRet
=NULL
)
589 CAutoFile filein
= CAutoFile(OpenBlockFile(pos
.nFile
, 0, pfileRet
? "rb+" : "rb"), SER_DISK
, CLIENT_VERSION
);
591 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
594 if (fseek(filein
, pos
.nTxPos
, SEEK_SET
) != 0)
595 return error("CTransaction::ReadFromDisk() : fseek failed");
598 // Return file pointer
601 if (fseek(filein
, pos
.nTxPos
, SEEK_SET
) != 0)
602 return error("CTransaction::ReadFromDisk() : second fseek failed");
603 *pfileRet
= filein
.release();
608 friend bool operator==(const CTransaction
& a
, const CTransaction
& b
)
610 return (a
.nVersion
== b
.nVersion
&&
613 a
.nLockTime
== b
.nLockTime
);
616 friend bool operator!=(const CTransaction
& a
, const CTransaction
& b
)
622 std::string
ToString() const
625 str
+= strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
626 GetHash().ToString().substr(0,10).c_str(),
631 for (unsigned int i
= 0; i
< vin
.size(); i
++)
632 str
+= " " + vin
[i
].ToString() + "\n";
633 for (unsigned int i
= 0; i
< vout
.size(); i
++)
634 str
+= " " + vout
[i
].ToString() + "\n";
640 printf("%s", ToString().c_str());
644 bool ReadFromDisk(CTxDB
& txdb
, COutPoint prevout
, CTxIndex
& txindexRet
);
645 bool ReadFromDisk(CTxDB
& txdb
, COutPoint prevout
);
646 bool ReadFromDisk(COutPoint prevout
);
647 bool DisconnectInputs(CTxDB
& txdb
);
649 /** Fetch from memory and/or disk. inputsRet keys are transaction hashes.
651 @param[in] txdb Transaction database
652 @param[in] mapTestPool List of pending changes to the transaction index database
653 @param[in] fBlock True if being called to add a new best-block to the chain
654 @param[in] fMiner True if being called by CreateNewBlock
655 @param[out] inputsRet Pointers to this transaction's inputs
656 @param[out] fInvalid returns true if transaction is invalid
657 @return Returns true if all inputs are in txdb or mapTestPool
659 bool FetchInputs(CTxDB
& txdb
, const std::map
<uint256
, CTxIndex
>& mapTestPool
,
660 bool fBlock
, bool fMiner
, MapPrevTx
& inputsRet
, bool& fInvalid
);
662 /** Sanity check previous transactions, then, if all checks succeed,
663 mark them as spent by this transaction.
665 @param[in] inputs Previous transactions (from FetchInputs)
666 @param[out] mapTestPool Keeps track of inputs that need to be updated on disk
667 @param[in] posThisTx Position of this transaction on disk
668 @param[in] pindexBlock
669 @param[in] fBlock true if called from ConnectBlock
670 @param[in] fMiner true if called from CreateNewBlock
671 @param[in] fStrictPayToScriptHash true if fully validating p2sh transactions
672 @return Returns true if all checks succeed
674 bool ConnectInputs(MapPrevTx inputs
,
675 std::map
<uint256
, CTxIndex
>& mapTestPool
, const CDiskTxPos
& posThisTx
,
676 const CBlockIndex
* pindexBlock
, bool fBlock
, bool fMiner
, bool fStrictPayToScriptHash
=true);
677 bool ClientConnectInputs();
678 bool CheckTransaction() const;
679 bool AcceptToMemoryPool(CTxDB
& txdb
, bool fCheckInputs
=true, bool* pfMissingInputs
=NULL
);
682 const CTxOut
& GetOutputFor(const CTxIn
& input
, const MapPrevTx
& inputs
) const;
689 /** A transaction with a merkle branch linking it to the block chain. */
690 class CMerkleTx
: public CTransaction
694 std::vector
<uint256
> vMerkleBranch
;
698 mutable bool fMerkleVerified
;
706 CMerkleTx(const CTransaction
& txIn
) : CTransaction(txIn
)
715 fMerkleVerified
= false;
721 nSerSize
+= SerReadWrite(s
, *(CTransaction
*)this, nType
, nVersion
, ser_action
);
722 nVersion
= this->nVersion
;
723 READWRITE(hashBlock
);
724 READWRITE(vMerkleBranch
);
729 int SetMerkleBranch(const CBlock
* pblock
=NULL
);
730 int GetDepthInMainChain(CBlockIndex
* &pindexRet
) const;
731 int GetDepthInMainChain() const { CBlockIndex
*pindexRet
; return GetDepthInMainChain(pindexRet
); }
732 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
733 int GetBlocksToMaturity() const;
734 bool AcceptToMemoryPool(CTxDB
& txdb
, bool fCheckInputs
=true);
735 bool AcceptToMemoryPool();
741 /** A txdb record that contains the disk location of a transaction and the
742 * locations of transactions that spend its outputs. vSpent is really only
743 * used as a flag, but having the location is very helpful for debugging.
749 std::vector
<CDiskTxPos
> vSpent
;
756 CTxIndex(const CDiskTxPos
& posIn
, unsigned int nOutputs
)
759 vSpent
.resize(nOutputs
);
764 if (!(nType
& SER_GETHASH
))
781 friend bool operator==(const CTxIndex
& a
, const CTxIndex
& b
)
783 return (a
.pos
== b
.pos
&&
784 a
.vSpent
== b
.vSpent
);
787 friend bool operator!=(const CTxIndex
& a
, const CTxIndex
& b
)
791 int GetDepthInMainChain() const;
799 /** Nodes collect new transactions into a block, hash them into a hash tree,
800 * and scan through nonce values to make the block's hash satisfy proof-of-work
801 * requirements. When they solve the proof-of-work, they broadcast the block
802 * to everyone and the block is added to the block chain. The first transaction
803 * in the block is a special one that creates a new coin owned by the creator
806 * Blocks are appended to blk0001.dat files on disk. Their location on disk
807 * is indexed by CBlockIndex objects in memory.
814 uint256 hashPrevBlock
;
815 uint256 hashMerkleRoot
;
821 std::vector
<CTransaction
> vtx
;
824 mutable std::vector
<uint256
> vMerkleTree
;
826 // Denial-of-service detection:
828 bool DoS(int nDoSIn
, bool fIn
) const { nDoS
+= nDoSIn
; return fIn
; }
837 READWRITE(this->nVersion
);
838 nVersion
= this->nVersion
;
839 READWRITE(hashPrevBlock
);
840 READWRITE(hashMerkleRoot
);
845 // ConnectBlock depends on vtx being last so it can calculate offset
846 if (!(nType
& (SER_GETHASH
|SER_BLOCKHEADERONLY
)))
849 const_cast<CBlock
*>(this)->vtx
.clear();
870 uint256
GetHash() const
872 return Hash(BEGIN(nVersion
), END(nNonce
));
875 int64
GetBlockTime() const
880 void UpdateTime(const CBlockIndex
* pindexPrev
);
883 uint256
BuildMerkleTree() const
886 BOOST_FOREACH(const CTransaction
& tx
, vtx
)
887 vMerkleTree
.push_back(tx
.GetHash());
889 for (int nSize
= vtx
.size(); nSize
> 1; nSize
= (nSize
+ 1) / 2)
891 for (int i
= 0; i
< nSize
; i
+= 2)
893 int i2
= std::min(i
+1, nSize
-1);
894 vMerkleTree
.push_back(Hash(BEGIN(vMerkleTree
[j
+i
]), END(vMerkleTree
[j
+i
]),
895 BEGIN(vMerkleTree
[j
+i2
]), END(vMerkleTree
[j
+i2
])));
899 return (vMerkleTree
.empty() ? 0 : vMerkleTree
.back());
902 std::vector
<uint256
> GetMerkleBranch(int nIndex
) const
904 if (vMerkleTree
.empty())
906 std::vector
<uint256
> vMerkleBranch
;
908 for (int nSize
= vtx
.size(); nSize
> 1; nSize
= (nSize
+ 1) / 2)
910 int i
= std::min(nIndex
^1, nSize
-1);
911 vMerkleBranch
.push_back(vMerkleTree
[j
+i
]);
915 return vMerkleBranch
;
918 static uint256
CheckMerkleBranch(uint256 hash
, const std::vector
<uint256
>& vMerkleBranch
, int nIndex
)
922 BOOST_FOREACH(const uint256
& otherside
, vMerkleBranch
)
925 hash
= Hash(BEGIN(otherside
), END(otherside
), BEGIN(hash
), END(hash
));
927 hash
= Hash(BEGIN(hash
), END(hash
), BEGIN(otherside
), END(otherside
));
934 bool WriteToDisk(unsigned int& nFileRet
, unsigned int& nBlockPosRet
)
936 // Open history file to append
937 CAutoFile fileout
= CAutoFile(AppendBlockFile(nFileRet
), SER_DISK
, CLIENT_VERSION
);
939 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
941 // Write index header
942 unsigned int nSize
= fileout
.GetSerializeSize(*this);
943 fileout
<< FLATDATA(pchMessageStart
) << nSize
;
946 long fileOutPos
= ftell(fileout
);
948 return error("CBlock::WriteToDisk() : ftell failed");
949 nBlockPosRet
= fileOutPos
;
952 // Flush stdio buffers and commit to disk before returning
954 if (!IsInitialBlockDownload() || (nBestHeight
+1) % 500 == 0)
960 bool ReadFromDisk(unsigned int nFile
, unsigned int nBlockPos
, bool fReadTransactions
=true)
964 // Open history file to read
965 CAutoFile filein
= CAutoFile(OpenBlockFile(nFile
, nBlockPos
, "rb"), SER_DISK
, CLIENT_VERSION
);
967 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
968 if (!fReadTransactions
)
969 filein
.nType
|= SER_BLOCKHEADERONLY
;
975 if (!CheckProofOfWork(GetHash(), nBits
))
976 return error("CBlock::ReadFromDisk() : errors in block header");
985 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
986 GetHash().ToString().substr(0,20).c_str(),
988 hashPrevBlock
.ToString().substr(0,20).c_str(),
989 hashMerkleRoot
.ToString().substr(0,10).c_str(),
990 nTime
, nBits
, nNonce
,
992 for (unsigned int i
= 0; i
< vtx
.size(); i
++)
997 printf(" vMerkleTree: ");
998 for (unsigned int i
= 0; i
< vMerkleTree
.size(); i
++)
999 printf("%s ", vMerkleTree
[i
].ToString().substr(0,10).c_str());
1004 bool DisconnectBlock(CTxDB
& txdb
, CBlockIndex
* pindex
);
1005 bool ConnectBlock(CTxDB
& txdb
, CBlockIndex
* pindex
);
1006 bool ReadFromDisk(const CBlockIndex
* pindex
, bool fReadTransactions
=true);
1007 bool SetBestChain(CTxDB
& txdb
, CBlockIndex
* pindexNew
);
1008 bool AddToBlockIndex(unsigned int nFile
, unsigned int nBlockPos
);
1009 bool CheckBlock() const;
1013 bool SetBestChainInner(CTxDB
& txdb
, CBlockIndex
*pindexNew
);
1021 /** The block chain is a tree shaped structure starting with the
1022 * genesis block at the root, with each block potentially having multiple
1023 * candidates to be the next block. pprev and pnext link a path through the
1024 * main/longest chain. A blockindex may have multiple pprev pointing back
1025 * to it, but pnext will only point forward to the longest branch, or will
1026 * be null if the block is not part of the longest chain.
1031 const uint256
* phashBlock
;
1035 unsigned int nBlockPos
;
1037 CBigNum bnChainWork
;
1041 uint256 hashMerkleRoot
;
1044 unsigned int nNonce
;
1064 CBlockIndex(unsigned int nFileIn
, unsigned int nBlockPosIn
, CBlock
& block
)
1070 nBlockPos
= nBlockPosIn
;
1074 nVersion
= block
.nVersion
;
1075 hashMerkleRoot
= block
.hashMerkleRoot
;
1076 nTime
= block
.nTime
;
1077 nBits
= block
.nBits
;
1078 nNonce
= block
.nNonce
;
1081 CBlock
GetBlockHeader() const
1084 block
.nVersion
= nVersion
;
1086 block
.hashPrevBlock
= pprev
->GetBlockHash();
1087 block
.hashMerkleRoot
= hashMerkleRoot
;
1088 block
.nTime
= nTime
;
1089 block
.nBits
= nBits
;
1090 block
.nNonce
= nNonce
;
1094 uint256
GetBlockHash() const
1099 int64
GetBlockTime() const
1101 return (int64
)nTime
;
1104 CBigNum
GetBlockWork() const
1107 bnTarget
.SetCompact(nBits
);
1110 return (CBigNum(1)<<256) / (bnTarget
+1);
1113 bool IsInMainChain() const
1115 return (pnext
|| this == pindexBest
);
1118 bool CheckIndex() const
1120 return CheckProofOfWork(GetBlockHash(), nBits
);
1123 enum { nMedianTimeSpan
=11 };
1125 int64
GetMedianTimePast() const
1127 int64 pmedian
[nMedianTimeSpan
];
1128 int64
* pbegin
= &pmedian
[nMedianTimeSpan
];
1129 int64
* pend
= &pmedian
[nMedianTimeSpan
];
1131 const CBlockIndex
* pindex
= this;
1132 for (int i
= 0; i
< nMedianTimeSpan
&& pindex
; i
++, pindex
= pindex
->pprev
)
1133 *(--pbegin
) = pindex
->GetBlockTime();
1135 std::sort(pbegin
, pend
);
1136 return pbegin
[(pend
- pbegin
)/2];
1139 int64
GetMedianTime() const
1141 const CBlockIndex
* pindex
= this;
1142 for (int i
= 0; i
< nMedianTimeSpan
/2; i
++)
1145 return GetBlockTime();
1146 pindex
= pindex
->pnext
;
1148 return pindex
->GetMedianTimePast();
1153 std::string
ToString() const
1155 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
1156 pprev
, pnext
, nFile
, nBlockPos
, nHeight
,
1157 hashMerkleRoot
.ToString().substr(0,10).c_str(),
1158 GetBlockHash().ToString().substr(0,20).c_str());
1163 printf("%s\n", ToString().c_str());
1169 /** Used to marshal pointers into hashes for db storage. */
1170 class CDiskBlockIndex
: public CBlockIndex
1182 explicit CDiskBlockIndex(CBlockIndex
* pindex
) : CBlockIndex(*pindex
)
1184 hashPrev
= (pprev
? pprev
->GetBlockHash() : 0);
1185 hashNext
= (pnext
? pnext
->GetBlockHash() : 0);
1190 if (!(nType
& SER_GETHASH
))
1191 READWRITE(nVersion
);
1193 READWRITE(hashNext
);
1195 READWRITE(nBlockPos
);
1199 READWRITE(this->nVersion
);
1200 READWRITE(hashPrev
);
1201 READWRITE(hashMerkleRoot
);
1207 uint256
GetBlockHash() const
1210 block
.nVersion
= nVersion
;
1211 block
.hashPrevBlock
= hashPrev
;
1212 block
.hashMerkleRoot
= hashMerkleRoot
;
1213 block
.nTime
= nTime
;
1214 block
.nBits
= nBits
;
1215 block
.nNonce
= nNonce
;
1216 return block
.GetHash();
1220 std::string
ToString() const
1222 std::string str
= "CDiskBlockIndex(";
1223 str
+= CBlockIndex::ToString();
1224 str
+= strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1225 GetBlockHash().ToString().c_str(),
1226 hashPrev
.ToString().substr(0,20).c_str(),
1227 hashNext
.ToString().substr(0,20).c_str());
1233 printf("%s\n", ToString().c_str());
1244 /** Describes a place in the block chain to another node such that if the
1245 * other node doesn't have the same branch, it can find a recent common trunk.
1246 * The further back it is, the further before the fork it may be.
1251 std::vector
<uint256
> vHave
;
1258 explicit CBlockLocator(const CBlockIndex
* pindex
)
1263 explicit CBlockLocator(uint256 hashBlock
)
1265 std::map
<uint256
, CBlockIndex
*>::iterator mi
= mapBlockIndex
.find(hashBlock
);
1266 if (mi
!= mapBlockIndex
.end())
1270 CBlockLocator(const std::vector
<uint256
>& vHaveIn
)
1277 if (!(nType
& SER_GETHASH
))
1278 READWRITE(nVersion
);
1289 return vHave
.empty();
1292 void Set(const CBlockIndex
* pindex
)
1298 vHave
.push_back(pindex
->GetBlockHash());
1300 // Exponentially larger steps back
1301 for (int i
= 0; pindex
&& i
< nStep
; i
++)
1302 pindex
= pindex
->pprev
;
1303 if (vHave
.size() > 10)
1306 vHave
.push_back(hashGenesisBlock
);
1309 int GetDistanceBack()
1311 // Retrace how far back it was in the sender's branch
1314 BOOST_FOREACH(const uint256
& hash
, vHave
)
1316 std::map
<uint256
, CBlockIndex
*>::iterator mi
= mapBlockIndex
.find(hash
);
1317 if (mi
!= mapBlockIndex
.end())
1319 CBlockIndex
* pindex
= (*mi
).second
;
1320 if (pindex
->IsInMainChain())
1330 CBlockIndex
* GetBlockIndex()
1332 // Find the first block the caller has in the main chain
1333 BOOST_FOREACH(const uint256
& hash
, vHave
)
1335 std::map
<uint256
, CBlockIndex
*>::iterator mi
= mapBlockIndex
.find(hash
);
1336 if (mi
!= mapBlockIndex
.end())
1338 CBlockIndex
* pindex
= (*mi
).second
;
1339 if (pindex
->IsInMainChain())
1343 return pindexGenesisBlock
;
1346 uint256
GetBlockHash()
1348 // Find the first block the caller has in the main chain
1349 BOOST_FOREACH(const uint256
& hash
, vHave
)
1351 std::map
<uint256
, CBlockIndex
*>::iterator mi
= mapBlockIndex
.find(hash
);
1352 if (mi
!= mapBlockIndex
.end())
1354 CBlockIndex
* pindex
= (*mi
).second
;
1355 if (pindex
->IsInMainChain())
1359 return hashGenesisBlock
;
1364 CBlockIndex
* pindex
= GetBlockIndex();
1367 return pindex
->nHeight
;
1379 /** Alerts are for notifying old versions if they become too obsolete and
1380 * need to upgrade. The message is displayed in the status bar.
1381 * Alert messages are broadcast as a vector of signed data. Unserializing may
1382 * not read the entire buffer if the alert is for a newer version, but older
1383 * versions can still relay the original data.
1385 class CUnsignedAlert
1389 int64 nRelayUntil
; // when newer nodes stop relaying to newer nodes
1393 std::set
<int> setCancel
;
1394 int nMinVer
; // lowest version inclusive
1395 int nMaxVer
; // highest version inclusive
1396 std::set
<std::string
> setSubVer
; // empty matches all
1400 std::string strComment
;
1401 std::string strStatusBar
;
1402 std::string strReserved
;
1406 READWRITE(this->nVersion
);
1407 nVersion
= this->nVersion
;
1408 READWRITE(nRelayUntil
);
1409 READWRITE(nExpiration
);
1412 READWRITE(setCancel
);
1415 READWRITE(setSubVer
);
1416 READWRITE(nPriority
);
1418 READWRITE(strComment
);
1419 READWRITE(strStatusBar
);
1420 READWRITE(strReserved
);
1437 strStatusBar
.clear();
1438 strReserved
.clear();
1441 std::string
ToString() const
1443 std::string strSetCancel
;
1444 BOOST_FOREACH(int n
, setCancel
)
1445 strSetCancel
+= strprintf("%d ", n
);
1446 std::string strSetSubVer
;
1447 BOOST_FOREACH(std::string str
, setSubVer
)
1448 strSetSubVer
+= "\"" + str
+ "\" ";
1452 " nRelayUntil = %"PRI64d
"\n"
1453 " nExpiration = %"PRI64d
"\n"
1461 " strComment = \"%s\"\n"
1462 " strStatusBar = \"%s\"\n"
1469 strSetCancel
.c_str(),
1472 strSetSubVer
.c_str(),
1475 strStatusBar
.c_str());
1480 printf("%s", ToString().c_str());
1484 /** An alert is a combination of a serialized CUnsignedAlert and a signature. */
1485 class CAlert
: public CUnsignedAlert
1488 std::vector
<unsigned char> vchMsg
;
1489 std::vector
<unsigned char> vchSig
;
1504 CUnsignedAlert::SetNull();
1511 return (nExpiration
== 0);
1514 uint256
GetHash() const
1516 return SerializeHash(*this);
1519 bool IsInEffect() const
1521 return (GetAdjustedTime() < nExpiration
);
1524 bool Cancels(const CAlert
& alert
) const
1527 return false; // this was a no-op before 31403
1528 return (alert
.nID
<= nCancel
|| setCancel
.count(alert
.nID
));
1531 bool AppliesTo(int nVersion
, std::string strSubVerIn
) const
1533 // TODO: rework for client-version-embedded-in-strSubVer ?
1534 return (IsInEffect() &&
1535 nMinVer
<= nVersion
&& nVersion
<= nMaxVer
&&
1536 (setSubVer
.empty() || setSubVer
.count(strSubVerIn
)));
1539 bool AppliesToMe() const
1541 return AppliesTo(PROTOCOL_VERSION
, FormatSubVersion(CLIENT_NAME
, CLIENT_VERSION
, std::vector
<std::string
>()));
1544 bool RelayTo(CNode
* pnode
) const
1548 // returns true if wasn't already contained in the set
1549 if (pnode
->setKnown
.insert(GetHash()).second
)
1551 if (AppliesTo(pnode
->nVersion
, pnode
->strSubVer
) ||
1553 GetAdjustedTime() < nRelayUntil
)
1555 pnode
->PushMessage("alert", *this);
1562 bool CheckSignature()
1565 if (!key
.SetPubKey(ParseHex("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284")))
1566 return error("CAlert::CheckSignature() : SetPubKey failed");
1567 if (!key
.Verify(Hash(vchMsg
.begin(), vchMsg
.end()), vchSig
))
1568 return error("CAlert::CheckSignature() : verify signature failed");
1570 // Now unserialize the data
1571 CDataStream
sMsg(vchMsg
, SER_NETWORK
, PROTOCOL_VERSION
);
1572 sMsg
>> *(CUnsignedAlert
*)this;
1576 bool ProcessAlert();
1582 mutable CCriticalSection cs
;
1583 std::map
<uint256
, CTransaction
> mapTx
;
1584 std::map
<COutPoint
, CInPoint
> mapNextTx
;
1586 bool accept(CTxDB
& txdb
, CTransaction
&tx
,
1587 bool fCheckInputs
, bool* pfMissingInputs
);
1588 bool addUnchecked(CTransaction
&tx
);
1589 bool remove(CTransaction
&tx
);
1591 unsigned long size()
1594 return mapTx
.size();
1597 bool exists(uint256 hash
)
1599 return (mapTx
.count(hash
) != 0);
1602 CTransaction
& lookup(uint256 hash
)
1608 extern CTxMemPool mempool
;