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