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