Projects : bitcoin : bitcoin_dumpblock_no_losers

bitcoin/src/main.h

Dir - Raw

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 license.txt or http://www.opensource.org/licenses/mit-license.php.
5#ifndef BITCOIN_MAIN_H
6#define BITCOIN_MAIN_H
7
8#include "bignum.h"
9#include "net.h"
10#include "key.h"
11#include "script.h"
12#include "db.h"
13
14#include <list>
15
16class CBlock;
17class CBlockIndex;
18class CWalletTx;
19class CWallet;
20class CKeyItem;
21class CReserveKey;
22class CWalletDB;
23
24class CAddress;
25class CInv;
26class CRequestTracker;
27class CNode;
28class CBlockIndex;
29
30static const unsigned int MAX_BLOCK_SIZE = 1000000;
31static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/2;
32static const int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
33static const int64 COIN = 100000000;
34static const int64 CENT = 1000000;
35static const int64 MIN_TX_FEE = 50000;
36static const int64 MIN_RELAY_TX_FEE = 10000;
37static const int64 MAX_MONEY = 21000000 * COIN;
38inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
39static const int COINBASE_MATURITY = 100;
40// Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp.
41static const int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC
42
43
44
45
46
47
48extern CCriticalSection cs_main;
49extern std::map<uint256, CBlockIndex*> mapBlockIndex;
50extern uint256 hashGenesisBlock;
51extern CBlockIndex* pindexGenesisBlock;
52extern int nBestHeight;
53extern CBigNum bnBestChainWork;
54extern CBigNum bnBestInvalidWork;
55extern uint256 hashBestChain;
56extern CBlockIndex* pindexBest;
57extern unsigned int nTransactionsUpdated;
58extern double dHashesPerSec;
59extern int64 nHPSTimerStart;
60extern int64 nTimeBestReceived;
61extern CCriticalSection cs_setpwalletRegistered;
62extern std::set<CWallet*> setpwalletRegistered;
63
64// Settings
65extern int fGenerateBitcoins;
66extern int64 nTransactionFee;
67extern int fLimitProcessors;
68extern int nLimitProcessors;
69extern int fMinimizeToTray;
70extern int fMinimizeOnClose;
71
72
73
74
75
76class CReserveKey;
77class CTxDB;
78class CTxIndex;
79
80bool GetMempoolTx(const uint256 &hash, CTransaction &tx);
81bool MempoolContainsTx(const uint256 &hash);
82void RegisterWallet(CWallet* pwalletIn);
83void UnregisterWallet(CWallet* pwalletIn);
84void SyncWithWallets(const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false);
85bool ProcessBlock(CNode* pfrom, CBlock* pblock);
86bool CheckDiskSpace(uint64 nAdditionalBytes=0);
87FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
88FILE* AppendBlockFile(unsigned int& nFileRet);
89bool LoadBlockIndex(bool fAllowNew=true);
90void PrintBlockTree();
91bool ProcessMessages(CNode* pfrom);
92bool SendMessages(CNode* pto, bool fSendTrickle);
93void GenerateBitcoins(bool fGenerate, CWallet* pwallet);
94CBlock* CreateNewBlock(CReserveKey& reservekey);
95void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce);
96void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
97bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey);
98bool CheckProofOfWork(uint256 hash, unsigned int nBits);
99unsigned int ComputeMinWork(unsigned int nBase, int64 nTime);
100int GetNumBlocksOfPeers();
101bool IsInitialBlockDownload();
102std::string GetWarnings(std::string strFor);
103
104
105
106
107
108
109
110
111
112
113
114
115bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
116
117template<typename T>
118bool WriteSetting(const std::string& strKey, const T& value)
119{
120 bool fOk = false;
121 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
122 {
123 std::string strWalletFile;
124 if (!GetWalletFile(pwallet, strWalletFile))
125 continue;
126 fOk |= CWalletDB(strWalletFile).WriteSetting(strKey, value);
127 }
128 return fOk;
129}
130
131
132class CDiskTxPos
133{
134public:
135 unsigned int nFile;
136 unsigned int nBlockPos;
137 unsigned int nTxPos;
138
139 CDiskTxPos()
140 {
141 SetNull();
142 }
143
144 CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
145 {
146 nFile = nFileIn;
147 nBlockPos = nBlockPosIn;
148 nTxPos = nTxPosIn;
149 }
150
151 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
152 void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
153 bool IsNull() const { return (nFile == -1); }
154
155 friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
156 {
157 return (a.nFile == b.nFile &&
158 a.nBlockPos == b.nBlockPos &&
159 a.nTxPos == b.nTxPos);
160 }
161
162 friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
163 {
164 return !(a == b);
165 }
166
167 std::string ToString() const
168 {
169 if (IsNull())
170 return strprintf("null");
171 else
172 return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
173 }
174
175 void print() const
176 {
177 printf("%s", ToString().c_str());
178 }
179};
180
181
182
183
184class CInPoint
185{
186public:
187 CTransaction* ptx;
188 unsigned int n;
189
190 CInPoint() { SetNull(); }
191 CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
192 void SetNull() { ptx = NULL; n = -1; }
193 bool IsNull() const { return (ptx == NULL && n == -1); }
194};
195
196
197
198
199class COutPoint
200{
201public:
202 uint256 hash;
203 unsigned int n;
204
205 COutPoint() { SetNull(); }
206 COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
207 IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
208 void SetNull() { hash = 0; n = -1; }
209 bool IsNull() const { return (hash == 0 && n == -1); }
210
211 friend bool operator<(const COutPoint& a, const COutPoint& b)
212 {
213 return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
214 }
215
216 friend bool operator==(const COutPoint& a, const COutPoint& b)
217 {
218 return (a.hash == b.hash && a.n == b.n);
219 }
220
221 friend bool operator!=(const COutPoint& a, const COutPoint& b)
222 {
223 return !(a == b);
224 }
225
226 std::string ToString() const
227 {
228 return strprintf("COutPoint(%s, %d)", hash.ToString().c_str(), n);
229 }
230
231 void print() const
232 {
233 printf("%s\n", ToString().c_str());
234 }
235};
236
237
238
239
240//
241// An input of a transaction. It contains the location of the previous
242// transaction's output that it claims and a signature that matches the
243// output's public key.
244//
245class CTxIn
246{
247public:
248 COutPoint prevout;
249 CScript scriptSig;
250 unsigned int nSequence;
251
252 CTxIn()
253 {
254 nSequence = UINT_MAX;
255 }
256
257 explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
258 {
259 prevout = prevoutIn;
260 scriptSig = scriptSigIn;
261 nSequence = nSequenceIn;
262 }
263
264 CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
265 {
266 prevout = COutPoint(hashPrevTx, nOut);
267 scriptSig = scriptSigIn;
268 nSequence = nSequenceIn;
269 }
270
271 IMPLEMENT_SERIALIZE
272 (
273 READWRITE(prevout);
274 READWRITE(scriptSig);
275 READWRITE(nSequence);
276 )
277
278 bool IsFinal() const
279 {
280 return (nSequence == UINT_MAX);
281 }
282
283 friend bool operator==(const CTxIn& a, const CTxIn& b)
284 {
285 return (a.prevout == b.prevout &&
286 a.scriptSig == b.scriptSig &&
287 a.nSequence == b.nSequence);
288 }
289
290 friend bool operator!=(const CTxIn& a, const CTxIn& b)
291 {
292 return !(a == b);
293 }
294
295 std::string ToString() const
296 {
297 std::string str;
298 str += strprintf("CTxIn(");
299 str += prevout.ToString();
300 if (prevout.IsNull())
301 str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
302 else
303 str += strprintf(", scriptSig=%s", scriptSig.ToString().c_str());
304 if (nSequence != UINT_MAX)
305 str += strprintf(", nSequence=%u", nSequence);
306 str += ")";
307 return str;
308 }
309
310 void print() const
311 {
312 printf("%s\n", ToString().c_str());
313 }
314};
315
316
317
318
319//
320// An output of a transaction. It contains the public key that the next input
321// must be able to sign with to claim it.
322//
323class CTxOut
324{
325public:
326 int64 nValue;
327 CScript scriptPubKey;
328
329 CTxOut()
330 {
331 SetNull();
332 }
333
334 CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
335 {
336 nValue = nValueIn;
337 scriptPubKey = scriptPubKeyIn;
338 }
339
340 IMPLEMENT_SERIALIZE
341 (
342 READWRITE(nValue);
343 READWRITE(scriptPubKey);
344 )
345
346 void SetNull()
347 {
348 nValue = -1;
349 scriptPubKey.clear();
350 }
351
352 bool IsNull()
353 {
354 return (nValue == -1);
355 }
356
357 uint256 GetHash() const
358 {
359 return SerializeHash(*this);
360 }
361
362 friend bool operator==(const CTxOut& a, const CTxOut& b)
363 {
364 return (a.nValue == b.nValue &&
365 a.scriptPubKey == b.scriptPubKey);
366 }
367
368 friend bool operator!=(const CTxOut& a, const CTxOut& b)
369 {
370 return !(a == b);
371 }
372
373 std::string ToString() const
374 {
375 if (scriptPubKey.size() < 6)
376 return "CTxOut(error)";
377 return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().c_str());
378 }
379
380 void print() const
381 {
382 printf("%s\n", ToString().c_str());
383 }
384};
385
386
387
388
389//
390// The basic transaction that is broadcasted on the network and contained in
391// blocks. A transaction can contain multiple inputs and outputs.
392//
393class CTransaction
394{
395public:
396 int nVersion;
397 std::vector<CTxIn> vin;
398 std::vector<CTxOut> vout;
399 unsigned int nLockTime;
400
401 // Denial-of-service detection:
402 mutable int nDoS;
403 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
404
405 CTransaction()
406 {
407 SetNull();
408 }
409
410 IMPLEMENT_SERIALIZE
411 (
412 READWRITE(this->nVersion);
413 nVersion = this->nVersion;
414 READWRITE(vin);
415 READWRITE(vout);
416 READWRITE(nLockTime);
417 )
418
419 void SetNull()
420 {
421 nVersion = 1;
422 vin.clear();
423 vout.clear();
424 nLockTime = 0;
425 nDoS = 0; // Denial-of-service prevention
426 }
427
428 bool IsNull() const
429 {
430 return (vin.empty() && vout.empty());
431 }
432
433 uint256 GetHash() const
434 {
435 return SerializeHash(*this);
436 }
437
438 bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
439 {
440 // Time based nLockTime implemented in 0.1.6
441 if (nLockTime == 0)
442 return true;
443 if (nBlockHeight == 0)
444 nBlockHeight = nBestHeight;
445 if (nBlockTime == 0)
446 nBlockTime = GetAdjustedTime();
447 if ((int64)nLockTime < (nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
448 return true;
449 BOOST_FOREACH(const CTxIn& txin, vin)
450 if (!txin.IsFinal())
451 return false;
452 return true;
453 }
454
455 bool IsNewerThan(const CTransaction& old) const
456 {
457 if (vin.size() != old.vin.size())
458 return false;
459 for (int i = 0; i < vin.size(); i++)
460 if (vin[i].prevout != old.vin[i].prevout)
461 return false;
462
463 bool fNewer = false;
464 unsigned int nLowest = UINT_MAX;
465 for (int i = 0; i < vin.size(); i++)
466 {
467 if (vin[i].nSequence != old.vin[i].nSequence)
468 {
469 if (vin[i].nSequence <= nLowest)
470 {
471 fNewer = false;
472 nLowest = vin[i].nSequence;
473 }
474 if (old.vin[i].nSequence < nLowest)
475 {
476 fNewer = true;
477 nLowest = old.vin[i].nSequence;
478 }
479 }
480 }
481 return fNewer;
482 }
483
484 bool IsCoinBase() const
485 {
486 return (vin.size() == 1 && vin[0].prevout.IsNull());
487 }
488
489 int GetSigOpCount() const
490 {
491 int n = 0;
492 BOOST_FOREACH(const CTxIn& txin, vin)
493 n += txin.scriptSig.GetSigOpCount();
494 BOOST_FOREACH(const CTxOut& txout, vout)
495 n += txout.scriptPubKey.GetSigOpCount();
496 return n;
497 }
498
499 bool IsStandard() const
500 {
501 BOOST_FOREACH(const CTxIn& txin, vin)
502 if (!txin.scriptSig.IsPushOnly())
503 return error("nonstandard txin: %s", txin.scriptSig.ToString().c_str());
504 BOOST_FOREACH(const CTxOut& txout, vout)
505 if (!::IsStandard(txout.scriptPubKey))
506 return error("nonstandard txout: %s", txout.scriptPubKey.ToString().c_str());
507 return true;
508 }
509
510 int64 GetValueOut() const
511 {
512 int64 nValueOut = 0;
513 BOOST_FOREACH(const CTxOut& txout, vout)
514 {
515 nValueOut += txout.nValue;
516 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
517 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
518 }
519 return nValueOut;
520 }
521
522 static bool AllowFree(double dPriority)
523 {
524 // Large (in bytes) low-priority (new, small-coin) transactions
525 // need a fee.
526 return dPriority > COIN * 144 / 250;
527 }
528
529 int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=true, bool fForRelay=false) const
530 {
531 // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
532 int64 nBaseFee = fForRelay ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
533
534 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);
535 unsigned int nNewBlockSize = nBlockSize + nBytes;
536 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
537
538 if (fAllowFree)
539 {
540 if (nBlockSize == 1)
541 {
542 // Transactions under 10K are free
543 // (about 4500bc if made of 50bc inputs)
544 if (nBytes < 10000)
545 nMinFee = 0;
546 }
547 else
548 {
549 // Free transaction area
550 if (nNewBlockSize < 27000)
551 nMinFee = 0;
552 }
553 }
554
555 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
556 if (nMinFee < nBaseFee)
557 BOOST_FOREACH(const CTxOut& txout, vout)
558 if (txout.nValue < CENT)
559 nMinFee = nBaseFee;
560
561 // Raise the price as the block approaches full
562 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
563 {
564 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
565 return MAX_MONEY;
566 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
567 }
568
569 if (!MoneyRange(nMinFee))
570 nMinFee = MAX_MONEY;
571 return nMinFee;
572 }
573
574
575 bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
576 {
577 CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");
578 if (!filein)
579 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
580
581 // Read transaction
582 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
583 return error("CTransaction::ReadFromDisk() : fseek failed");
584 filein >> *this;
585
586 // Return file pointer
587 if (pfileRet)
588 {
589 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
590 return error("CTransaction::ReadFromDisk() : second fseek failed");
591 *pfileRet = filein.release();
592 }
593 return true;
594 }
595
596 friend bool operator==(const CTransaction& a, const CTransaction& b)
597 {
598 return (a.nVersion == b.nVersion &&
599 a.vin == b.vin &&
600 a.vout == b.vout &&
601 a.nLockTime == b.nLockTime);
602 }
603
604 friend bool operator!=(const CTransaction& a, const CTransaction& b)
605 {
606 return !(a == b);
607 }
608
609
610 std::string ToString() const
611 {
612 std::string str;
613 str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
614 GetHash().ToString().c_str(),
615 nVersion,
616 vin.size(),
617 vout.size(),
618 nLockTime);
619 for (int i = 0; i < vin.size(); i++)
620 str += " " + vin[i].ToString() + "\n";
621 for (int i = 0; i < vout.size(); i++)
622 str += " " + vout[i].ToString() + "\n";
623 return str;
624 }
625
626 void print() const
627 {
628 printf("%s", ToString().c_str());
629 }
630
631
632 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
633 bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
634 bool ReadFromDisk(COutPoint prevout);
635 bool DisconnectInputs(CTxDB& txdb);
636 bool ConnectInputs(CTxDB& txdb, std::map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
637 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee,
638 bool& fInvalid);
639 bool ClientConnectInputs();
640 bool CheckTransaction() const;
641 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
642 bool AcceptToMemoryPool(bool fCheckInputs=true, bool* pfMissingInputs=NULL);
643protected:
644 bool AddToMemoryPoolUnchecked();
645public:
646 bool RemoveFromMemoryPool();
647};
648
649
650
651
652
653//
654// A transaction with a merkle branch linking it to the block chain
655//
656class CMerkleTx : public CTransaction
657{
658public:
659 uint256 hashBlock;
660 std::vector<uint256> vMerkleBranch;
661 int nIndex;
662
663 // memory only
664 mutable char fMerkleVerified;
665
666
667 CMerkleTx()
668 {
669 Init();
670 }
671
672 CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
673 {
674 Init();
675 }
676
677 void Init()
678 {
679 hashBlock = 0;
680 nIndex = -1;
681 fMerkleVerified = false;
682 }
683
684
685 IMPLEMENT_SERIALIZE
686 (
687 nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
688 nVersion = this->nVersion;
689 READWRITE(hashBlock);
690 READWRITE(vMerkleBranch);
691 READWRITE(nIndex);
692 )
693
694
695 int SetMerkleBranch(const CBlock* pblock=NULL);
696 int GetDepthInMainChain(int& nHeightRet) const;
697 int GetDepthInMainChain() const { int nHeight; return GetDepthInMainChain(nHeight); }
698 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
699 int GetBlocksToMaturity() const;
700 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
701 bool AcceptToMemoryPool();
702};
703
704
705
706
707//
708// A txdb record that contains the disk location of a transaction and the
709// locations of transactions that spend its outputs. vSpent is really only
710// used as a flag, but having the location is very helpful for debugging.
711//
712class CTxIndex
713{
714public:
715 CDiskTxPos pos;
716 std::vector<CDiskTxPos> vSpent;
717
718 CTxIndex()
719 {
720 SetNull();
721 }
722
723 CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
724 {
725 pos = posIn;
726 vSpent.resize(nOutputs);
727 }
728
729 IMPLEMENT_SERIALIZE
730 (
731 if (!(nType & SER_GETHASH))
732 READWRITE(nVersion);
733 READWRITE(pos);
734 READWRITE(vSpent);
735 )
736
737 void SetNull()
738 {
739 pos.SetNull();
740 vSpent.clear();
741 }
742
743 bool IsNull()
744 {
745 return pos.IsNull();
746 }
747
748 friend bool operator==(const CTxIndex& a, const CTxIndex& b)
749 {
750 return (a.pos == b.pos &&
751 a.vSpent == b.vSpent);
752 }
753
754 friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
755 {
756 return !(a == b);
757 }
758 int GetDepthInMainChain() const;
759};
760
761
762
763
764
765//
766// Nodes collect new transactions into a block, hash them into a hash tree,
767// and scan through nonce values to make the block's hash satisfy proof-of-work
768// requirements. When they solve the proof-of-work, they broadcast the block
769// to everyone and the block is added to the block chain. The first transaction
770// in the block is a special one that creates a new coin owned by the creator
771// of the block.
772//
773// Blocks are appended to blk0001.dat files on disk. Their location on disk
774// is indexed by CBlockIndex objects in memory.
775//
776class CBlock
777{
778public:
779 // header
780 int nVersion;
781 uint256 hashPrevBlock;
782 uint256 hashMerkleRoot;
783 unsigned int nTime;
784 unsigned int nBits;
785 unsigned int nNonce;
786
787 // network and disk
788 std::vector<CTransaction> vtx;
789
790 // memory only
791 mutable std::vector<uint256> vMerkleTree;
792
793 // Denial-of-service detection:
794 mutable int nDoS;
795 bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
796
797 CBlock()
798 {
799 SetNull();
800 }
801
802 IMPLEMENT_SERIALIZE
803 (
804 READWRITE(this->nVersion);
805 nVersion = this->nVersion;
806 READWRITE(hashPrevBlock);
807 READWRITE(hashMerkleRoot);
808 READWRITE(nTime);
809 READWRITE(nBits);
810 READWRITE(nNonce);
811
812 // ConnectBlock depends on vtx being last so it can calculate offset
813 if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
814 READWRITE(vtx);
815 else if (fRead)
816 const_cast<CBlock*>(this)->vtx.clear();
817 )
818
819 void SetNull()
820 {
821 nVersion = 1;
822 hashPrevBlock = 0;
823 hashMerkleRoot = 0;
824 nTime = 0;
825 nBits = 0;
826 nNonce = 0;
827 vtx.clear();
828 vMerkleTree.clear();
829 nDoS = 0;
830 }
831
832 bool IsNull() const
833 {
834 return (nBits == 0);
835 }
836
837 uint256 GetHash() const
838 {
839 return Hash(BEGIN(nVersion), END(nNonce));
840 }
841
842 int64 GetBlockTime() const
843 {
844 return (int64)nTime;
845 }
846
847 int GetSigOpCount() const
848 {
849 int n = 0;
850 BOOST_FOREACH(const CTransaction& tx, vtx)
851 n += tx.GetSigOpCount();
852 return n;
853 }
854
855
856 uint256 BuildMerkleTree() const
857 {
858 vMerkleTree.clear();
859 BOOST_FOREACH(const CTransaction& tx, vtx)
860 vMerkleTree.push_back(tx.GetHash());
861 int j = 0;
862 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
863 {
864 for (int i = 0; i < nSize; i += 2)
865 {
866 int i2 = std::min(i+1, nSize-1);
867 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
868 BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
869 }
870 j += nSize;
871 }
872 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
873 }
874
875 std::vector<uint256> GetMerkleBranch(int nIndex) const
876 {
877 if (vMerkleTree.empty())
878 BuildMerkleTree();
879 std::vector<uint256> vMerkleBranch;
880 int j = 0;
881 for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
882 {
883 int i = std::min(nIndex^1, nSize-1);
884 vMerkleBranch.push_back(vMerkleTree[j+i]);
885 nIndex >>= 1;
886 j += nSize;
887 }
888 return vMerkleBranch;
889 }
890
891 static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
892 {
893 if (nIndex == -1)
894 return 0;
895 BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
896 {
897 if (nIndex & 1)
898 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
899 else
900 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
901 nIndex >>= 1;
902 }
903 return hash;
904 }
905
906
907 bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
908 {
909 // Open history file to append
910 CAutoFile fileout = AppendBlockFile(nFileRet);
911 if (!fileout)
912 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
913
914 // Write index header
915 unsigned int nSize = fileout.GetSerializeSize(*this);
916 fileout << FLATDATA(pchMessageStart) << nSize;
917
918 // Write block
919 nBlockPosRet = ftell(fileout);
920 if (nBlockPosRet == -1)
921 return error("CBlock::WriteToDisk() : ftell failed");
922 fileout << *this;
923
924 // Flush stdio buffers and commit to disk before returning
925 fflush(fileout);
926 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
927 {
928 fsync(fileno(fileout));
929 }
930
931 return true;
932 }
933
934 bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
935 {
936 SetNull();
937
938 // Open history file to read
939 CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");
940 if (!filein)
941 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
942 if (!fReadTransactions)
943 filein.nType |= SER_BLOCKHEADERONLY;
944
945 // Read block
946 filein >> *this;
947
948 // Check the header
949 if (!CheckProofOfWork(GetHash(), nBits))
950 return error("CBlock::ReadFromDisk() : errors in block header");
951
952 return true;
953 }
954
955
956
957 void print() const
958 {
959 printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
960 GetHash().ToString().c_str(),
961 nVersion,
962 hashPrevBlock.ToString().c_str(),
963 hashMerkleRoot.ToString().c_str(),
964 nTime, nBits, nNonce,
965 vtx.size());
966 for (int i = 0; i < vtx.size(); i++)
967 {
968 printf(" ");
969 vtx[i].print();
970 }
971 printf(" vMerkleTree: ");
972 for (int i = 0; i < vMerkleTree.size(); i++)
973 printf("%s ", vMerkleTree[i].ToString().c_str());
974 printf("\n");
975 }
976
977
978 bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
979 bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
980 bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
981 bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
982 bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
983 bool CheckBlock() const;
984 bool AcceptBlock();
985};
986
987
988
989
990
991
992//
993// The block chain is a tree shaped structure starting with the
994// genesis block at the root, with each block potentially having multiple
995// candidates to be the next block. pprev and pnext link a path through the
996// main/longest chain. A blockindex may have multiple pprev pointing back
997// to it, but pnext will only point forward to the longest branch, or will
998// be null if the block is not part of the longest chain.
999//
1000class CBlockIndex
1001{
1002public:
1003 const uint256* phashBlock;
1004 CBlockIndex* pprev;
1005 CBlockIndex* pnext;
1006 unsigned int nFile;
1007 unsigned int nBlockPos;
1008 int nHeight;
1009 CBigNum bnChainWork;
1010
1011 // block header
1012 int nVersion;
1013 uint256 hashMerkleRoot;
1014 unsigned int nTime;
1015 unsigned int nBits;
1016 unsigned int nNonce;
1017
1018
1019 CBlockIndex()
1020 {
1021 phashBlock = NULL;
1022 pprev = NULL;
1023 pnext = NULL;
1024 nFile = 0;
1025 nBlockPos = 0;
1026 nHeight = 0;
1027 bnChainWork = 0;
1028
1029 nVersion = 0;
1030 hashMerkleRoot = 0;
1031 nTime = 0;
1032 nBits = 0;
1033 nNonce = 0;
1034 }
1035
1036 CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1037 {
1038 phashBlock = NULL;
1039 pprev = NULL;
1040 pnext = NULL;
1041 nFile = nFileIn;
1042 nBlockPos = nBlockPosIn;
1043 nHeight = 0;
1044 bnChainWork = 0;
1045
1046 nVersion = block.nVersion;
1047 hashMerkleRoot = block.hashMerkleRoot;
1048 nTime = block.nTime;
1049 nBits = block.nBits;
1050 nNonce = block.nNonce;
1051 }
1052
1053 CBlock GetBlockHeader() const
1054 {
1055 CBlock block;
1056 block.nVersion = nVersion;
1057 if (pprev)
1058 block.hashPrevBlock = pprev->GetBlockHash();
1059 block.hashMerkleRoot = hashMerkleRoot;
1060 block.nTime = nTime;
1061 block.nBits = nBits;
1062 block.nNonce = nNonce;
1063 return block;
1064 }
1065
1066 uint256 GetBlockHash() const
1067 {
1068 return *phashBlock;
1069 }
1070
1071 int64 GetBlockTime() const
1072 {
1073 return (int64)nTime;
1074 }
1075
1076 CBigNum GetBlockWork() const
1077 {
1078 CBigNum bnTarget;
1079 bnTarget.SetCompact(nBits);
1080 if (bnTarget <= 0)
1081 return 0;
1082 return (CBigNum(1)<<256) / (bnTarget+1);
1083 }
1084
1085 bool IsInMainChain() const
1086 {
1087 return (pnext || this == pindexBest);
1088 }
1089
1090 bool CheckIndex() const
1091 {
1092 return CheckProofOfWork(GetBlockHash(), nBits);
1093 }
1094
1095 bool EraseBlockFromDisk()
1096 {
1097 // Open history file
1098 CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");
1099 if (!fileout)
1100 return false;
1101
1102 // Overwrite with empty null block
1103 CBlock block;
1104 block.SetNull();
1105 fileout << block;
1106
1107 return true;
1108 }
1109
1110 enum { nMedianTimeSpan=11 };
1111
1112 int64 GetMedianTimePast() const
1113 {
1114 int64 pmedian[nMedianTimeSpan];
1115 int64* pbegin = &pmedian[nMedianTimeSpan];
1116 int64* pend = &pmedian[nMedianTimeSpan];
1117
1118 const CBlockIndex* pindex = this;
1119 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1120 *(--pbegin) = pindex->GetBlockTime();
1121
1122 std::sort(pbegin, pend);
1123 return pbegin[(pend - pbegin)/2];
1124 }
1125
1126 int64 GetMedianTime() const
1127 {
1128 const CBlockIndex* pindex = this;
1129 for (int i = 0; i < nMedianTimeSpan/2; i++)
1130 {
1131 if (!pindex->pnext)
1132 return GetBlockTime();
1133 pindex = pindex->pnext;
1134 }
1135 return pindex->GetMedianTimePast();
1136 }
1137
1138
1139
1140 std::string ToString() const
1141 {
1142 return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
1143 pprev, pnext, nFile, nBlockPos, nHeight,
1144 hashMerkleRoot.ToString().c_str(),
1145 GetBlockHash().ToString().c_str());
1146 }
1147
1148 void print() const
1149 {
1150 printf("%s\n", ToString().c_str());
1151 }
1152};
1153
1154
1155
1156//
1157// Used to marshal pointers into hashes for db storage.
1158//
1159class CDiskBlockIndex : public CBlockIndex
1160{
1161public:
1162 uint256 hashPrev;
1163 uint256 hashNext;
1164
1165 CDiskBlockIndex()
1166 {
1167 hashPrev = 0;
1168 hashNext = 0;
1169 }
1170
1171 explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1172 {
1173 hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1174 hashNext = (pnext ? pnext->GetBlockHash() : 0);
1175 }
1176
1177 IMPLEMENT_SERIALIZE
1178 (
1179 if (!(nType & SER_GETHASH))
1180 READWRITE(nVersion);
1181
1182 READWRITE(hashNext);
1183 READWRITE(nFile);
1184 READWRITE(nBlockPos);
1185 READWRITE(nHeight);
1186
1187 // block header
1188 READWRITE(this->nVersion);
1189 READWRITE(hashPrev);
1190 READWRITE(hashMerkleRoot);
1191 READWRITE(nTime);
1192 READWRITE(nBits);
1193 READWRITE(nNonce);
1194 )
1195
1196 uint256 GetBlockHash() const
1197 {
1198 CBlock block;
1199 block.nVersion = nVersion;
1200 block.hashPrevBlock = hashPrev;
1201 block.hashMerkleRoot = hashMerkleRoot;
1202 block.nTime = nTime;
1203 block.nBits = nBits;
1204 block.nNonce = nNonce;
1205 return block.GetHash();
1206 }
1207
1208
1209 std::string ToString() const
1210 {
1211 std::string str = "CDiskBlockIndex(";
1212 str += CBlockIndex::ToString();
1213 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
1214 GetBlockHash().ToString().c_str(),
1215 hashPrev.ToString().c_str(),
1216 hashNext.ToString().c_str());
1217 return str;
1218 }
1219
1220 void print() const
1221 {
1222 printf("%s\n", ToString().c_str());
1223 }
1224};
1225
1226
1227
1228
1229
1230
1231
1232
1233//
1234// Describes a place in the block chain to another node such that if the
1235// other node doesn't have the same branch, it can find a recent common trunk.
1236// The further back it is, the further before the fork it may be.
1237//
1238class CBlockLocator
1239{
1240protected:
1241 std::vector<uint256> vHave;
1242public:
1243
1244 CBlockLocator()
1245 {
1246 }
1247
1248 explicit CBlockLocator(const CBlockIndex* pindex)
1249 {
1250 Set(pindex);
1251 }
1252
1253 explicit CBlockLocator(uint256 hashBlock)
1254 {
1255 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1256 if (mi != mapBlockIndex.end())
1257 Set((*mi).second);
1258 }
1259
1260 IMPLEMENT_SERIALIZE
1261 (
1262 if (!(nType & SER_GETHASH))
1263 READWRITE(nVersion);
1264 READWRITE(vHave);
1265 )
1266
1267 void SetNull()
1268 {
1269 vHave.clear();
1270 }
1271
1272 bool IsNull()
1273 {
1274 return vHave.empty();
1275 }
1276
1277 void Set(const CBlockIndex* pindex)
1278 {
1279 vHave.clear();
1280 int nStep = 1;
1281 while (pindex)
1282 {
1283 vHave.push_back(pindex->GetBlockHash());
1284
1285 // Exponentially larger steps back
1286 for (int i = 0; pindex && i < nStep; i++)
1287 pindex = pindex->pprev;
1288 if (vHave.size() > 10)
1289 nStep *= 2;
1290 }
1291 vHave.push_back(hashGenesisBlock);
1292 }
1293
1294 int GetDistanceBack()
1295 {
1296 // Retrace how far back it was in the sender's branch
1297 int nDistance = 0;
1298 int nStep = 1;
1299 BOOST_FOREACH(const uint256& hash, vHave)
1300 {
1301 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1302 if (mi != mapBlockIndex.end())
1303 {
1304 CBlockIndex* pindex = (*mi).second;
1305 if (pindex->IsInMainChain())
1306 return nDistance;
1307 }
1308 nDistance += nStep;
1309 if (nDistance > 10)
1310 nStep *= 2;
1311 }
1312 return nDistance;
1313 }
1314
1315 CBlockIndex* GetBlockIndex()
1316 {
1317 // Find the first block the caller has in the main chain
1318 BOOST_FOREACH(const uint256& hash, vHave)
1319 {
1320 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1321 if (mi != mapBlockIndex.end())
1322 {
1323 CBlockIndex* pindex = (*mi).second;
1324 if (pindex->IsInMainChain())
1325 return pindex;
1326 }
1327 }
1328 return pindexGenesisBlock;
1329 }
1330
1331 uint256 GetBlockHash()
1332 {
1333 // Find the first block the caller has in the main chain
1334 BOOST_FOREACH(const uint256& hash, vHave)
1335 {
1336 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1337 if (mi != mapBlockIndex.end())
1338 {
1339 CBlockIndex* pindex = (*mi).second;
1340 if (pindex->IsInMainChain())
1341 return hash;
1342 }
1343 }
1344 return hashGenesisBlock;
1345 }
1346
1347 int GetHeight()
1348 {
1349 CBlockIndex* pindex = GetBlockIndex();
1350 if (!pindex)
1351 return 0;
1352 return pindex->nHeight;
1353 }
1354};
1355
1356#endif