Projects : bitcoin : bitcoin_reorg_bounded_space

bitcoin/src/main.cpp

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#include "headers.h"
6#include "checkpoints.h"
7#include "db.h"
8#include "net.h"
9#include "init.h"
10#include <boost/filesystem.hpp>
11#include <boost/filesystem/fstream.hpp>
12
13// v0.5.4 RELEASE (keccak)
14
15using namespace std;
16using namespace boost;
17
18//
19// Global state
20//
21
22// This verbose variable naming is to rule out confusion with prior local names such as "nClientVersion".
23int nClientVersionNum = 99999; // Was 50400 prior to programmable-versionstring patch. May affect network protocol, serialization, peer acceptance and such.
24std::string strClientVersionName("jwrd.net");
25
26CCriticalSection cs_setpwalletRegistered;
27set<CWallet*> setpwalletRegistered;
28
29CCriticalSection cs_main;
30
31static map<uint256, CTransaction> mapTransactions;
32CCriticalSection cs_mapTransactions;
33unsigned int nTransactionsUpdated = 0;
34map<COutPoint, CInPoint> mapNextTx;
35
36map<uint256, CBlockIndex*> mapBlockIndex;
37uint256 hashGenesisBlock("0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f");
38static CBigNum bnProofOfWorkLimit(~uint256(0) >> 32);
39CBlockIndex* pindexGenesisBlock = NULL;
40int nBestHeight = -1;
41CBigNum bnBestChainWork = 0;
42CBigNum bnBestInvalidWork = 0;
43uint256 hashBestChain = 0;
44CBlockIndex* pindexBest = NULL;
45int64 nTimeBestReceived = 0;
46
47CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have
48
49
50
51double dHashesPerSec;
52int64 nHPSTimerStart;
53
54// Settings
55int fGenerateBitcoins = false;
56int fLimitProcessors = false;
57int nLimitProcessors = 1;
58int fMinimizeToTray = true;
59int fMinimizeOnClose = true;
60int nCheckBlocks = 144;
61static int64 nTransactionFee = 10000;
62static int64 nMinRelayTxFee = 10000;
63static CCriticalSection cs_settings;
64
65int64 GetTransactionFee()
66{
67 SCOPED_LOCK(cs_settings);
68 return nTransactionFee;
69}
70
71void SetTransactionFee(int64 nFee)
72{
73 SCOPED_LOCK(cs_settings);
74 nTransactionFee = nFee;
75}
76
77int64 GetMinRelayTxFee()
78{
79 SCOPED_LOCK(cs_settings);
80 return nMinRelayTxFee;
81}
82
83void SetMinRelayTxFee(int64 nFee)
84{
85 SCOPED_LOCK(cs_settings);
86 nMinRelayTxFee = nFee;
87}
88
89int64 ScaleTxFee(int64 nFeePerKB, unsigned int nBytes)
90{
91 if (nFeePerKB < 0) nFeePerKB = 0; // should probably never happen
92 if (nBytes > MAX_BLOCK_SIZE) nBytes = MAX_BLOCK_SIZE; // should probably never happen
93 int64 nFee = (nFeePerKB > INT64_MAX / (int64) MAX_BLOCK_SIZE)
94 ? INT64_MAX // multiplication overflow, should never happen for "reasonable" fee
95 : nFeePerKB * (int64) nBytes;
96 nFee /= 1024;
97 return (nFee > MAX_MONEY) ? MAX_MONEY : nFee;
98}
99
100bool GetMempoolTx(const uint256 &hash, CTransaction &tx)
101{
102 CRITICAL_BLOCK(cs_mapTransactions)
103 {
104 map<uint256, CTransaction>::iterator it = mapTransactions.find(hash);
105 if (it == mapTransactions.end())
106 return false;
107 tx = it->second;
108 }
109 return true;
110}
111
112bool MempoolContainsTx(const uint256 &hash)
113{
114 SCOPED_LOCK(cs_mapTransactions);
115 return mapTransactions.count(hash) != 0;
116}
117
118//////////////////////////////////////////////////////////////////////////////
119//
120// dispatching functions
121//
122
123// These functions dispatch to one or all registered wallets
124
125
126void RegisterWallet(CWallet* pwalletIn)
127{
128 CRITICAL_BLOCK(cs_setpwalletRegistered)
129 {
130 setpwalletRegistered.insert(pwalletIn);
131 }
132}
133
134void UnregisterWallet(CWallet* pwalletIn)
135{
136 CRITICAL_BLOCK(cs_setpwalletRegistered)
137 {
138 setpwalletRegistered.erase(pwalletIn);
139 }
140}
141
142// get the wallet transaction with the given hash (if it exists)
143bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
144{
145 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
146 if (pwallet->GetTransaction(hashTx,wtx))
147 return true;
148 return false;
149}
150
151// erases transaction with the given hash from all wallets
152void static EraseFromWallets(uint256 hash)
153{
154 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
155 pwallet->EraseFromWallet(hash);
156}
157
158// make sure all wallets know about the given transaction, in the given block
159void SyncWithWallets(const CTransaction& tx, const CBlock* pblock, bool fUpdate)
160{
161 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
162 pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate);
163}
164
165// notify wallets about a new best chain
166void static SetBestChain(const CBlockLocator& loc)
167{
168 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
169 pwallet->SetBestChain(loc);
170}
171
172// notify wallets about an updated transaction
173void static UpdatedTransaction(const uint256& hashTx)
174{
175 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
176 pwallet->UpdatedTransaction(hashTx);
177}
178
179// dump all wallets
180void static PrintWallets(const CBlock& block)
181{
182 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
183 pwallet->PrintWallet(block);
184}
185
186// notify wallets about an incoming inventory (for request counts)
187void static Inventory(const uint256& hash)
188{
189 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
190 pwallet->Inventory(hash);
191}
192
193// ask wallets to resend their transactions
194void static ResendWalletTransactions()
195{
196 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
197 pwallet->ResendWalletTransactions();
198}
199
200
201//////////////////////////////////////////////////////////////////////////////
202//
203// CTransaction and CTxIndex
204//
205
206bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
207{
208 SetNull();
209 if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
210 return false;
211 if (!ReadFromDisk(txindexRet.pos))
212 return false;
213 if (prevout.n >= vout.size())
214 {
215 SetNull();
216 return false;
217 }
218 return true;
219}
220
221bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
222{
223 CTxIndex txindex;
224 return ReadFromDisk(txdb, prevout, txindex);
225}
226
227int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
228{
229 if (fClient)
230 {
231 if (hashBlock == 0)
232 return 0;
233 }
234 else
235 {
236 CBlock blockTmp;
237 if (pblock == NULL)
238 {
239 // Load the block this tx is in
240 CTxIndex txindex;
241 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
242 return 0;
243 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
244 return 0;
245 pblock = &blockTmp;
246 }
247
248 // Update the tx's hashBlock
249 hashBlock = pblock->GetHash();
250
251 // Locate the transaction
252 for (nIndex = 0; nIndex < pblock->vtx.size(); nIndex++)
253 if (pblock->vtx[nIndex] == *(CTransaction*)this)
254 break;
255 if (nIndex == pblock->vtx.size())
256 {
257 vMerkleBranch.clear();
258 nIndex = -1;
259 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
260 return 0;
261 }
262
263 // Fill in merkle branch
264 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
265 }
266
267 // Is the tx in a block that's in the main chain
268 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
269 if (mi == mapBlockIndex.end())
270 return 0;
271 CBlockIndex* pindex = (*mi).second;
272 if (!pindex || !pindex->IsInMainChain())
273 return 0;
274
275 return pindexBest->nHeight - pindex->nHeight + 1;
276}
277
278
279
280
281
282
283
284bool CTransaction::CheckTransaction() const
285{
286 // Basic checks that don't depend on any context
287 if (vin.empty())
288 return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
289 if (vout.empty())
290 return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
291 // Size limits
292 if (::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
293 return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
294
295 // Check for negative or overflow output values
296 int64 nValueOut = 0;
297 BOOST_FOREACH(const CTxOut& txout, vout)
298 {
299 if (txout.nValue < 0)
300 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue negative"));
301 if (txout.nValue > MAX_MONEY)
302 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
303 nValueOut += txout.nValue;
304 if (!MoneyRange(nValueOut))
305 return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
306 }
307
308 // Check for duplicate inputs
309 set<COutPoint> vInOutPoints;
310 BOOST_FOREACH(const CTxIn& txin, vin)
311 {
312 if (vInOutPoints.count(txin.prevout))
313 return false;
314 vInOutPoints.insert(txin.prevout);
315 }
316
317 if (IsCoinBase())
318 {
319 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
320 return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size"));
321 }
322 else
323 {
324 BOOST_FOREACH(const CTxIn& txin, vin)
325 if (txin.prevout.IsNull())
326 return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
327 }
328
329 return true;
330}
331
332bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
333{
334 if (pfMissingInputs)
335 *pfMissingInputs = false;
336
337 if (!CheckTransaction())
338 return error("AcceptToMemoryPool() : CheckTransaction failed");
339
340 // Coinbase is only valid in a block, not as a loose transaction
341 if (IsCoinBase())
342 return DoS(100, error("AcceptToMemoryPool() : coinbase as individual tx"));
343
344 // To help v0.1.5 clients who would see it as a negative number
345 if ((int64)nLockTime > INT_MAX)
346 return error("AcceptToMemoryPool() : not accepting nLockTime beyond 2038 yet");
347
348 // Safety limits
349 unsigned int nSize = ::GetSerializeSize(*this, SER_NETWORK);
350 // Checking ECDSA signatures is a CPU bottleneck, so to avoid denial-of-service
351 // attacks disallow transactions with more than one SigOp per 34 bytes.
352 // 34 bytes because a TxOut is:
353 // 20-byte address + 8 byte bitcoin amount + 5 bytes of ops + 1 byte script length
354 if (GetSigOpCount() > nSize / 34 || nSize < 100)
355 return error("AcceptToMemoryPool() : transaction with out-of-bounds SigOpCount");
356
357 // Rather not work on nonstandard transactions
358 if (!IsStandard())
359 return error("AcceptToMemoryPool() : nonstandard transaction type");
360
361 // Do we already have it?
362 uint256 hash = GetHash();
363 if (MempoolContainsTx(hash))
364 return false;
365 if (fCheckInputs)
366 if (txdb.ContainsTx(hash))
367 return false;
368
369 // Check for conflicts with in-memory transactions
370 CTransaction* ptxOld = NULL;
371 for (int i = 0; i < vin.size(); i++)
372 {
373 COutPoint outpoint = vin[i].prevout;
374 if (mapNextTx.count(outpoint))
375 {
376 // Disable replacement feature for now
377 return false;
378
379 // Allow replacing with a newer version of the same transaction
380 if (i != 0)
381 return false;
382 ptxOld = mapNextTx[outpoint].ptx;
383 if (ptxOld->IsFinal())
384 return false;
385 if (!IsNewerThan(*ptxOld))
386 return false;
387 for (int i = 0; i < vin.size(); i++)
388 {
389 COutPoint outpoint = vin[i].prevout;
390 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
391 return false;
392 }
393 break;
394 }
395 }
396
397 if (fCheckInputs)
398 {
399 // Check against previous transactions
400 map<uint256, CTxIndex> mapUnused;
401 int64 nFees = 0;
402 bool fInvalid = false;
403 if (!ConnectInputs(txdb, mapUnused, CDiskTxPos(1,1,1), pindexBest, nFees, false, false, 0, fInvalid))
404 {
405 if (fInvalid)
406 return error("AcceptToMemoryPool() : FetchInputs found invalid tx %s", hash.ToString().c_str());
407 return error("AcceptToMemoryPool() : ConnectInputs failed %s", hash.ToString().c_str());
408 }
409
410 // Don't accept it if its fee is below the current threshold
411 if (nFees < GetMinFee())
412 return error("AcceptToMemoryPool() : not enough fees");
413 }
414
415 // Store transaction in memory
416 CRITICAL_BLOCK(cs_mapTransactions)
417 {
418 if (ptxOld)
419 {
420 printf("AcceptToMemoryPool() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
421 ptxOld->RemoveFromMemoryPool();
422 }
423 AddToMemoryPoolUnchecked();
424 }
425
426 ///// are we sure this is ok when loading transactions or restoring block txes
427 // If updated, erase old tx from wallet
428 if (ptxOld)
429 EraseFromWallets(ptxOld->GetHash());
430
431 printf("AcceptToMemoryPool(): accepted %s\n", hash.ToString().c_str());
432 return true;
433}
434
435bool CTransaction::AcceptToMemoryPool(bool fCheckInputs, bool* pfMissingInputs)
436{
437 CTxDB txdb("r");
438 return AcceptToMemoryPool(txdb, fCheckInputs, pfMissingInputs);
439}
440
441bool CTransaction::AddToMemoryPoolUnchecked()
442{
443 // Add to memory pool without checking anything. Don't call this directly,
444 // call AcceptToMemoryPool to properly check the transaction first.
445 CRITICAL_BLOCK(cs_mapTransactions)
446 {
447 uint256 hash = GetHash();
448 mapTransactions[hash] = *this;
449 for (int i = 0; i < vin.size(); i++)
450 mapNextTx[vin[i].prevout] = CInPoint(&mapTransactions[hash], i);
451 nTransactionsUpdated++;
452 }
453 return true;
454}
455
456
457bool CTransaction::RemoveFromMemoryPool()
458{
459 // Remove transaction from memory pool
460 CRITICAL_BLOCK(cs_mapTransactions)
461 {
462 BOOST_FOREACH(const CTxIn& txin, vin)
463 mapNextTx.erase(txin.prevout);
464 mapTransactions.erase(GetHash());
465 nTransactionsUpdated++;
466 }
467 return true;
468}
469
470
471
472
473
474
475int CMerkleTx::GetDepthInMainChain(int& nHeightRet) const
476{
477 if (hashBlock == 0 || nIndex == -1)
478 return 0;
479
480 // Find the block it claims to be in
481 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
482 if (mi == mapBlockIndex.end())
483 return 0;
484 CBlockIndex* pindex = (*mi).second;
485 if (!pindex || !pindex->IsInMainChain())
486 return 0;
487
488 // Make sure the merkle branch connects to this block
489 if (!fMerkleVerified)
490 {
491 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
492 return 0;
493 fMerkleVerified = true;
494 }
495
496 nHeightRet = pindex->nHeight;
497 return pindexBest->nHeight - pindex->nHeight + 1;
498}
499
500
501int CMerkleTx::GetBlocksToMaturity() const
502{
503 if (!IsCoinBase())
504 return 0;
505 return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
506}
507
508
509bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
510{
511 if (fClient)
512 {
513 if (!IsInMainChain() && !ClientConnectInputs())
514 return false;
515 return CTransaction::AcceptToMemoryPool(txdb, false);
516 }
517 else
518 {
519 return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
520 }
521}
522
523bool CMerkleTx::AcceptToMemoryPool()
524{
525 CTxDB txdb("r");
526 return AcceptToMemoryPool(txdb);
527}
528
529
530
531bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
532{
533 CRITICAL_BLOCK(cs_mapTransactions)
534 {
535 // Add previous supporting transactions first
536 BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
537 {
538 if (!tx.IsCoinBase())
539 {
540 uint256 hash = tx.GetHash();
541 if (!mapTransactions.count(hash) && !txdb.ContainsTx(hash))
542 tx.AcceptToMemoryPool(txdb, fCheckInputs);
543 }
544 }
545 return AcceptToMemoryPool(txdb, fCheckInputs);
546 }
547 return false;
548}
549
550int CTxIndex::GetDepthInMainChain() const
551{
552 // Read block header
553 CBlock block;
554 if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
555 return 0;
556 // Find the block in the index
557 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
558 if (mi == mapBlockIndex.end())
559 return 0;
560 CBlockIndex* pindex = (*mi).second;
561 if (!pindex || !pindex->IsInMainChain())
562 return 0;
563 return 1 + nBestHeight - pindex->nHeight;
564}
565
566
567
568
569
570
571
572
573
574
575//////////////////////////////////////////////////////////////////////////////
576//
577// CBlock and CBlockIndex
578//
579
580bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
581{
582 if (!fReadTransactions)
583 {
584 *this = pindex->GetBlockHeader();
585 return true;
586 }
587 if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
588 return false;
589 if (GetHash() != pindex->GetBlockHash())
590 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
591 return true;
592}
593
594int64 static GetBlockValue(int nHeight, int64 nFees)
595{
596 int64 nSubsidy = 50 * COIN;
597
598 // Subsidy is cut in half every 4 years
599 nSubsidy >>= (nHeight / 210000);
600
601 return nSubsidy + nFees;
602}
603
604static const int64 nTargetTimespan = 14 * 24 * 60 * 60; // two weeks
605static const int64 nTargetSpacing = 10 * 60;
606static const int64 nInterval = nTargetTimespan / nTargetSpacing;
607
608//
609// minimum amount of work that could possibly be required nTime after
610// minimum work required was nBase
611//
612unsigned int ComputeMinWork(unsigned int nBase, int64 nTime)
613{
614 CBigNum bnResult;
615 bnResult.SetCompact(nBase);
616 while (nTime > 0 && bnResult < bnProofOfWorkLimit)
617 {
618 // Maximum 400% adjustment...
619 bnResult *= 4;
620 // ... in best-case exactly 4-times-normal target time
621 nTime -= nTargetTimespan*4;
622 }
623 if (bnResult > bnProofOfWorkLimit)
624 bnResult = bnProofOfWorkLimit;
625 return bnResult.GetCompact();
626}
627
628unsigned int static GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlock *pblock)
629{
630 unsigned int nProofOfWorkLimit = bnProofOfWorkLimit.GetCompact();
631
632 // Genesis block
633 if (pindexLast == NULL)
634 return nProofOfWorkLimit;
635
636 // Only change once per interval
637 if ((pindexLast->nHeight+1) % nInterval != 0)
638 {
639 return pindexLast->nBits;
640 }
641
642 // Go back by what we want to be 14 days worth of blocks
643 const CBlockIndex* pindexFirst = pindexLast;
644 for (int i = 0; pindexFirst && i < nInterval-1; i++)
645 pindexFirst = pindexFirst->pprev;
646 assert(pindexFirst);
647
648 // Limit adjustment step
649 int64 nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();
650 printf(" nActualTimespan = %"PRI64d" before bounds\n", nActualTimespan);
651 if (nActualTimespan < nTargetTimespan/4)
652 nActualTimespan = nTargetTimespan/4;
653 if (nActualTimespan > nTargetTimespan*4)
654 nActualTimespan = nTargetTimespan*4;
655
656 // Retarget
657 CBigNum bnNew;
658 bnNew.SetCompact(pindexLast->nBits);
659 bnNew *= nActualTimespan;
660 bnNew /= nTargetTimespan;
661
662 if (bnNew > bnProofOfWorkLimit)
663 bnNew = bnProofOfWorkLimit;
664
665 /// debug print
666 printf("GetNextWorkRequired RETARGET\n");
667 printf("nTargetTimespan = %"PRI64d" nActualTimespan = %"PRI64d"\n", nTargetTimespan, nActualTimespan);
668 printf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());
669 printf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());
670
671 return bnNew.GetCompact();
672}
673
674bool CheckProofOfWork(uint256 hash, unsigned int nBits)
675{
676 CBigNum bnTarget;
677 bnTarget.SetCompact(nBits);
678
679 // Check range
680 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
681 return error("CheckProofOfWork() : nBits below minimum work");
682
683 // Check proof of work matches claimed amount
684 if (hash > bnTarget.getuint256())
685 return error("CheckProofOfWork() : hash doesn't match nBits");
686
687 return true;
688}
689
690// Return maximum amount of blocks that other nodes claim to have
691int GetNumBlocksOfPeers()
692{
693 return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
694}
695
696bool IsInitialBlockDownload()
697{
698 if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
699 return true;
700 static int64 nLastUpdate;
701 static CBlockIndex* pindexLastBest;
702 if (pindexBest != pindexLastBest)
703 {
704 pindexLastBest = pindexBest;
705 nLastUpdate = GetTime();
706 }
707 return (GetTime() - nLastUpdate < 10 &&
708 pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
709}
710
711void static InvalidChainFound(CBlockIndex* pindexNew)
712{
713 if (pindexNew->bnChainWork > bnBestInvalidWork)
714 {
715 bnBestInvalidWork = pindexNew->bnChainWork;
716 CTxDB().WriteBestInvalidWork(bnBestInvalidWork);
717 MainFrameRepaint();
718 }
719 printf("InvalidChainFound: invalid block=%s height=%d work=%s\n", pindexNew->GetBlockHash().ToString().c_str(), pindexNew->nHeight, pindexNew->bnChainWork.ToString().c_str());
720 printf("InvalidChainFound: current best=%s height=%d work=%s\n", hashBestChain.ToString().c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
721 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
722 // message partially duplicated in GetWarnings
723 printf("InvalidChainFound: WARNING: Failed to validate chain with greater proof-of-work. Displayed transactions may not be correct! Your database or other nodes may be corrupted.\n");
724}
725
726
727
728
729
730
731
732
733
734
735
736bool CTransaction::DisconnectInputs(CTxDB& txdb)
737{
738 // Relinquish previous transactions' spent pointers
739 if (!IsCoinBase())
740 {
741 BOOST_FOREACH(const CTxIn& txin, vin)
742 {
743 COutPoint prevout = txin.prevout;
744
745 // Get prev txindex from disk
746 CTxIndex txindex;
747 if (!txdb.ReadTxIndex(prevout.hash, txindex))
748 return error("DisconnectInputs() : ReadTxIndex failed");
749
750 if (prevout.n >= txindex.vSpent.size())
751 return error("DisconnectInputs() : prevout.n out of range");
752
753 // Mark outpoint as not spent
754 txindex.vSpent[prevout.n].SetNull();
755
756 // Write back
757 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
758 return error("DisconnectInputs() : UpdateTxIndex failed");
759 }
760 }
761
762 // Remove transaction from index
763 // This can fail if a duplicate of this transaction was in a chain that got
764 // reorganized away. This is only possible if this transaction was completely
765 // spent, so erasing it would be a no-op anway.
766 txdb.EraseTxIndex(*this);
767
768 return true;
769}
770
771
772bool CTransaction::ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
773 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee,
774 bool& fInvalid)
775{
776 // FetchInputs can return false either because we just haven't seen some inputs
777 // (in which case the transaction should be stored as an orphan)
778 // or because the transaction is malformed (in which case the transaction should
779 // be dropped). If tx is definitely invalid, fInvalid will be set to true.
780 fInvalid = false;
781
782 // Take over previous transactions' spent pointers
783 // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
784 // fMiner is true when called from the internal bitcoin miner
785 // ... both are false when called from CTransaction::AcceptToMemoryPool
786 if (!IsCoinBase())
787 {
788 int64 nValueIn = 0;
789 for (int i = 0; i < vin.size(); i++)
790 {
791 COutPoint prevout = vin[i].prevout;
792
793 // Read txindex
794 CTxIndex txindex;
795 bool fFound = true;
796 if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
797 {
798 // Get txindex from current proposed changes
799 txindex = mapTestPool[prevout.hash];
800 }
801 else
802 {
803 // Read txindex from txdb
804 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
805 }
806 if (!fFound && (fBlock || fMiner))
807 return fMiner ? false : error("ConnectInputs() : %s prev tx %s index entry not found", GetHash().ToString().c_str(), prevout.hash.ToString().c_str());
808
809 // Read txPrev
810 CTransaction txPrev;
811 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
812 {
813 // Get prev tx from single transactions in memory
814 if (!GetMempoolTx(prevout.hash, txPrev))
815 return error("ConnectInputs() : %s mapTransactions prev not found %s", GetHash().ToString().c_str(), prevout.hash.ToString().c_str());
816 if (!fFound)
817 txindex.vSpent.resize(txPrev.vout.size());
818 }
819 else
820 {
821 // Get prev tx from disk
822 if (!txPrev.ReadFromDisk(txindex.pos))
823 return error("ConnectInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().c_str(), prevout.hash.ToString().c_str());
824 }
825
826 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
827 {
828 // Revisit this if/when transaction replacement is implemented and allows
829 // adding inputs:
830 fInvalid = true;
831 return DoS(100, error("ConnectInputs() : %s prevout.n out of range %d %d %d prev tx %s\n%s", GetHash().ToString().c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().c_str(), txPrev.ToString().c_str()));
832 }
833
834 // If prev is coinbase, check that it's matured
835 if (txPrev.IsCoinBase())
836 for (CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev)
837 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
838 return error("ConnectInputs() : tried to spend coinbase at depth %d", pindexBlock->nHeight - pindex->nHeight);
839
840 // Skip ECDSA signature verification when connecting blocks (fBlock=true)
841 // before the last blockchain checkpoint. This is safe because block merkle hashes are
842 // still computed and checked, and any change will be caught at the next checkpoint.
843 if (fVerifyAll || (!(fBlock && (nBestHeight < Checkpoints::GetTotalBlocksEstimate()))))
844 // Verify signature
845 if (!VerifySignature(txPrev, *this, i))
846 return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().c_str()));
847
848 // Check for conflicts (double-spend)
849 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
850 // for an attacker to attempt to split the network.
851 if (!txindex.vSpent[prevout.n].IsNull())
852 return fMiner ? false : error("ConnectInputs() : %s prev tx already used at %s", GetHash().ToString().c_str(), txindex.vSpent[prevout.n].ToString().c_str());
853
854 // Check for negative or overflow input values
855 nValueIn += txPrev.vout[prevout.n].nValue;
856 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
857 return DoS(100, error("ConnectInputs() : txin values out of range"));
858
859 // Mark outpoints as spent
860 txindex.vSpent[prevout.n] = posThisTx;
861
862 // Write back
863 if (fBlock || fMiner)
864 {
865 mapTestPool[prevout.hash] = txindex;
866 }
867 }
868
869 if (nValueIn < GetValueOut())
870 return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().c_str()));
871
872 // Tally transaction fees
873 int64 nTxFee = nValueIn - GetValueOut();
874 if (nTxFee < 0)
875 return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().c_str()));
876 if (nTxFee < nMinFee)
877 return false;
878 nFees += nTxFee;
879 if (!MoneyRange(nFees))
880 return DoS(100, error("ConnectInputs() : nFees out of range"));
881 }
882
883 if (fBlock)
884 {
885 // Add transaction to changes
886 mapTestPool[GetHash()] = CTxIndex(posThisTx, vout.size());
887 }
888 else if (fMiner)
889 {
890 // Add transaction to test pool
891 mapTestPool[GetHash()] = CTxIndex(CDiskTxPos(1,1,1), vout.size());
892 }
893
894 return true;
895}
896
897
898bool CTransaction::ClientConnectInputs()
899{
900 if (IsCoinBase())
901 return false;
902
903 // Take over previous transactions' spent pointers
904 CRITICAL_BLOCK(cs_mapTransactions)
905 {
906 int64 nValueIn = 0;
907 for (int i = 0; i < vin.size(); i++)
908 {
909 // Get prev tx from single transactions in memory
910 COutPoint prevout = vin[i].prevout;
911 if (!mapTransactions.count(prevout.hash))
912 return false;
913 CTransaction& txPrev = mapTransactions[prevout.hash];
914
915 if (prevout.n >= txPrev.vout.size())
916 return false;
917
918 // Verify signature
919 if (!VerifySignature(txPrev, *this, i))
920 return error("ConnectInputs() : VerifySignature failed");
921
922 ///// this is redundant with the mapNextTx stuff, not sure which I want to get rid of
923 ///// this has to go away now that posNext is gone
924 // // Check for conflicts
925 // if (!txPrev.vout[prevout.n].posNext.IsNull())
926 // return error("ConnectInputs() : prev tx already used");
927 //
928 // // Flag outpoints as used
929 // txPrev.vout[prevout.n].posNext = posThisTx;
930
931 nValueIn += txPrev.vout[prevout.n].nValue;
932
933 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
934 return error("ClientConnectInputs() : txin values out of range");
935 }
936 if (GetValueOut() > nValueIn)
937 return false;
938 }
939
940 return true;
941}
942
943
944
945
946bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
947{
948 printf("DisconnectBlock(%s)\n", GetHash().ToString().c_str());
949
950 // Disconnect in reverse order
951 for (int i = vtx.size()-1; i >= 0; i--)
952 if (!vtx[i].DisconnectInputs(txdb))
953 return false;
954
955 // Update block index on disk without changing it in memory.
956 // The memory index structure will be changed after the db commits.
957 if (pindex->pprev)
958 {
959 CDiskBlockIndex blockindexPrev(pindex->pprev);
960 blockindexPrev.hashNext = 0;
961 if (!txdb.WriteBlockIndex(blockindexPrev))
962 return error("DisconnectBlock() : WriteBlockIndex failed");
963 }
964
965 return true;
966}
967
968bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
969{
970 printf("ConnectBlock(%s)\n", GetHash().ToString().c_str());
971
972 // Check it again in case a previous version let a bad block in
973 if (!CheckBlock())
974 return false;
975
976 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
977 // unless those are already completely spent.
978 // If such overwrites are allowed, coinbases and transactions depending upon those
979 // can be duplicated to remove the ability to spend the first instance -- even after
980 // being sent to another address.
981 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
982 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
983 // already refuses previously-known transaction id's entirely.
984 // This rule applies to all blocks whose timestamp is after March 15, 2012, 0:00 UTC.
985 if (pindex->nTime > 1331769600)
986 {
987 BOOST_FOREACH(CTransaction& tx, vtx)
988 {
989 CTxIndex txindexOld;
990 if (txdb.ReadTxIndex(tx.GetHash(), txindexOld))
991 {
992 BOOST_FOREACH(CDiskTxPos &pos, txindexOld.vSpent)
993 {
994 if (pos.IsNull())
995 return false;
996 }
997 }
998 }
999 }
1000
1001 //// issue here: it doesn't know the version
1002 unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK) - 1 + GetSizeOfCompactSize(vtx.size());
1003
1004 map<uint256, CTxIndex> mapQueuedChanges;
1005 int64 nFees = 0;
1006 BOOST_FOREACH(CTransaction& tx, vtx)
1007 {
1008 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1009 nTxPos += ::GetSerializeSize(tx, SER_DISK);
1010
1011 bool fInvalid;
1012 if (!tx.ConnectInputs(txdb, mapQueuedChanges, posThisTx, pindex, nFees, true, false, 0, fInvalid))
1013 return false;
1014 }
1015 // Write queued txindex changes
1016 for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
1017 {
1018 if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
1019 return error("ConnectBlock() : UpdateTxIndex failed");
1020 }
1021
1022 if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))
1023 return false;
1024
1025 // Update block index on disk without changing it in memory.
1026 // The memory index structure will be changed after the db commits.
1027 if (pindex->pprev)
1028 {
1029 CDiskBlockIndex blockindexPrev(pindex->pprev);
1030 blockindexPrev.hashNext = pindex->GetBlockHash();
1031 if (!txdb.WriteBlockIndex(blockindexPrev))
1032 return error("ConnectBlock() : WriteBlockIndex failed");
1033 }
1034
1035 // Watch for transactions paying to me
1036 BOOST_FOREACH(CTransaction& tx, vtx)
1037 SyncWithWallets(tx, this, true);
1038
1039 return true;
1040}
1041
1042bool static ReorgFailAbort(CTxDB& txdb, char const *msg)
1043{
1044 error("Reorganize() : %s", msg);
1045 txdb.TxnAbort();
1046 return false;
1047}
1048
1049bool static ReorgFailLate()
1050{
1051 error("Reorganize() : system failure while updating memory pool after db commit ; clearing pool so as not to leave it inconsistent");
1052 SCOPED_LOCK(cs_mapTransactions);
1053 mapTransactions.clear();
1054 mapNextTx.clear();
1055 nTransactionsUpdated++;
1056 return false;
1057}
1058
1059bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1060{
1061 printf("REORGANIZE\n");
1062
1063 // Find the fork
1064 CBlockIndex* pfork = pindexBest;
1065 CBlockIndex* plonger = pindexNew;
1066 while (pfork != plonger)
1067 {
1068 while (plonger->nHeight > pfork->nHeight)
1069 if (!(plonger = plonger->pprev))
1070 return ReorgFailAbort(txdb, "plonger->pprev is null");
1071 if (pfork == plonger)
1072 break;
1073 if (!(pfork = pfork->pprev))
1074 return ReorgFailAbort(txdb, "pfork->pprev is null");
1075 }
1076
1077 printf("Reorganize() : fork height=%d with %d to disconnect, %d to connect\n",
1078 pfork->nHeight,
1079 pindexBest->nHeight - pfork->nHeight,
1080 pindexNew->nHeight - pfork->nHeight);
1081
1082 // List of what to disconnect
1083 vector<CBlockIndex*> vDisconnect;
1084 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1085 vDisconnect.push_back(pindex);
1086
1087 // List of what to connect
1088 vector<CBlockIndex*> vConnect;
1089 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1090 vConnect.push_back(pindex);
1091 reverse(vConnect.begin(), vConnect.end());
1092
1093 // Disconnect shorter branch
1094 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1095 {
1096 CBlock block;
1097 if (!block.ReadFromDisk(pindex))
1098 return ReorgFailAbort(txdb, "ReadFromDisk for disconnect failed");
1099 if (!block.DisconnectBlock(txdb, pindex))
1100 return ReorgFailAbort(txdb, "DisconnectBlock failed");
1101 }
1102
1103 // Connect longer branch
1104 for (int i = 0; i < vConnect.size(); i++)
1105 {
1106 CBlockIndex* pindex = vConnect[i];
1107 CBlock block;
1108 if (!block.ReadFromDisk(pindex))
1109 return ReorgFailAbort(txdb, "ReadFromDisk for connect failed");
1110 if (!block.ConnectBlock(txdb, pindex))
1111 {
1112 // Invalid block (OR database failure...)
1113 return ReorgFailAbort(txdb, "ConnectBlock failed");
1114 }
1115 }
1116 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1117 return ReorgFailAbort(txdb, "WriteHashBestChain failed");
1118
1119 // Make sure it's successfully written to disk before changing memory structure
1120 printf("Reorganize() : successfully connected longer branch; committing now\n");
1121 if (!txdb.TxnCommit())
1122 return ReorgFailAbort(txdb, "TxnCommit failed");
1123
1124 printf("Reorganize() : updating memory block index\n");
1125
1126 // Disconnect shorter branch
1127 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1128 if (pindex->pprev)
1129 pindex->pprev->pnext = NULL;
1130
1131 // Connect longer branch
1132 BOOST_FOREACH(CBlockIndex* pindex, vConnect)
1133 if (pindex->pprev)
1134 pindex->pprev->pnext = pindex;
1135
1136 printf("Reorganize() : updating memory pool transactions\n");
1137
1138 // Resurrect memory transactions that were in the disconnected branch
1139 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1140 {
1141 CBlock block;
1142 if (!block.ReadFromDisk(pindex))
1143 return ReorgFailLate();
1144 BOOST_FOREACH(CTransaction& tx, block.vtx)
1145 {
1146 if (!tx.IsCoinBase())
1147 // XXX using fCheckInputs=true repeats more expensive checks that were already done when accepting the block, but is currently required to derive the fee and thus enforce mempool entry requirements
1148 tx.AcceptToMemoryPool(txdb, true);
1149 }
1150 }
1151
1152 // Delete redundant memory transactions that are in the connected branch
1153 BOOST_FOREACH(CBlockIndex* pindex, vConnect)
1154 {
1155 CBlock block;
1156 if (!block.ReadFromDisk(pindex))
1157 return ReorgFailLate();
1158 BOOST_FOREACH(CTransaction& tx, block.vtx)
1159 tx.RemoveFromMemoryPool();
1160 }
1161
1162 return true;
1163}
1164
1165
1166bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1167{
1168 uint256 hash = GetHash();
1169
1170 txdb.TxnBegin();
1171 if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)
1172 {
1173 txdb.WriteHashBestChain(hash);
1174 if (!txdb.TxnCommit())
1175 return error("SetBestChain() : TxnCommit failed");
1176 pindexGenesisBlock = pindexNew;
1177 }
1178 else if (hashPrevBlock == hashBestChain)
1179 {
1180 // Adding to current best branch
1181 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1182 {
1183 txdb.TxnAbort();
1184 InvalidChainFound(pindexNew);
1185 return error("SetBestChain() : ConnectBlock failed");
1186 }
1187 if (!txdb.TxnCommit())
1188 return error("SetBestChain() : TxnCommit failed");
1189
1190 // Add to current best branch
1191 pindexNew->pprev->pnext = pindexNew;
1192
1193 // Delete redundant memory transactions
1194 BOOST_FOREACH(CTransaction& tx, vtx)
1195 tx.RemoveFromMemoryPool();
1196 }
1197 else
1198 {
1199 // New best branch
1200 if (!Reorganize(txdb, pindexNew))
1201 {
1202 // Reorganize() is responsible for either committing or aborting; a false return doesn't necessarily mean it didn't commit.
1203 // XXX it also doesn't mean an invalid chain was positively found; e.g. it could be a database I/O error. But this confusion applies fractally and recursively, so at this point InvalidChainFound is the only way to signal the gravity of the situation.
1204 InvalidChainFound(pindexNew);
1205 return error("SetBestChain() : Reorganize failed");
1206 }
1207 }
1208
1209 // Update best block in wallet (so we can detect restored wallets)
1210 if (!IsInitialBlockDownload())
1211 {
1212 const CBlockLocator locator(pindexNew);
1213 ::SetBestChain(locator);
1214 }
1215
1216 // New best block
1217 hashBestChain = hash;
1218 pindexBest = pindexNew;
1219 nBestHeight = pindexBest->nHeight;
1220 bnBestChainWork = pindexNew->bnChainWork;
1221 nTimeBestReceived = GetTime();
1222 nTransactionsUpdated++;
1223 printf("SetBestChain: new best=%s height=%d work=%s\n", hashBestChain.ToString().c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
1224
1225 return true;
1226}
1227
1228
1229bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
1230{
1231 // Check for duplicate
1232 uint256 hash = GetHash();
1233 if (mapBlockIndex.count(hash))
1234 return error("AddToBlockIndex() : %s already exists", hash.ToString().c_str());
1235
1236 // Construct new block index object
1237 CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
1238 if (!pindexNew)
1239 return error("AddToBlockIndex() : new CBlockIndex failed");
1240 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
1241 pindexNew->phashBlock = &((*mi).first);
1242 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
1243 if (miPrev != mapBlockIndex.end())
1244 {
1245 pindexNew->pprev = (*miPrev).second;
1246 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
1247 }
1248 pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork();
1249
1250 CTxDB txdb;
1251 txdb.TxnBegin();
1252 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
1253 if (!txdb.TxnCommit())
1254 return false;
1255
1256 // New best
1257 if (pindexNew->bnChainWork > bnBestChainWork)
1258 if (!SetBestChain(txdb, pindexNew))
1259 return false;
1260
1261 txdb.Close();
1262
1263 if (pindexNew == pindexBest)
1264 {
1265 // Notify UI to display prev block's coinbase if it was ours
1266 static uint256 hashPrevBestCoinBase;
1267 UpdatedTransaction(hashPrevBestCoinBase);
1268 hashPrevBestCoinBase = vtx[0].GetHash();
1269 }
1270
1271 MainFrameRepaint();
1272 return true;
1273}
1274
1275
1276
1277
1278bool CBlock::CheckBlock() const
1279{
1280 // These are checks that are independent of context
1281 // that can be verified before saving an orphan block.
1282
1283 // Size limits
1284 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
1285 return DoS(100, error("CheckBlock() : size limits failed"));
1286
1287 // Check proof of work matches claimed amount
1288 if (!CheckProofOfWork(GetHash(), nBits))
1289 return DoS(50, error("CheckBlock() : proof of work failed"));
1290
1291 // Check timestamp
1292 if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
1293 return error("CheckBlock() : block timestamp too far in the future");
1294
1295 // First transaction must be coinbase, the rest must not be
1296 if (vtx.empty() || !vtx[0].IsCoinBase())
1297 return DoS(100, error("CheckBlock() : first tx is not coinbase"));
1298 for (int i = 1; i < vtx.size(); i++)
1299 if (vtx[i].IsCoinBase())
1300 return DoS(100, error("CheckBlock() : more than one coinbase"));
1301
1302 // Check transactions
1303 BOOST_FOREACH(const CTransaction& tx, vtx)
1304 if (!tx.CheckTransaction())
1305 return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
1306
1307 // Check that it's not full of nonstandard transactions
1308 if (GetSigOpCount() > MAX_BLOCK_SIGOPS)
1309 return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
1310
1311 // Check merkleroot
1312 if (hashMerkleRoot != BuildMerkleTree())
1313 return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
1314
1315 return true;
1316}
1317
1318bool CBlock::AcceptBlock()
1319{
1320 // Check for duplicate
1321 uint256 hash = GetHash();
1322 if (mapBlockIndex.count(hash))
1323 return error("AcceptBlock() : block already in mapBlockIndex");
1324
1325 // Get prev block index
1326 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
1327 if (mi == mapBlockIndex.end())
1328 return DoS(10, error("AcceptBlock() : prev block not found"));
1329 CBlockIndex* pindexPrev = (*mi).second;
1330 int nHeight = pindexPrev->nHeight+1;
1331
1332 // Check proof of work
1333 if (nBits != GetNextWorkRequired(pindexPrev, this))
1334 return DoS(100, error("AcceptBlock() : incorrect proof of work"));
1335
1336 // Check timestamp against prev
1337 if (GetBlockTime() <= pindexPrev->GetMedianTimePast())
1338 return error("AcceptBlock() : block's timestamp is too early");
1339
1340 // Check that all transactions are finalized
1341 BOOST_FOREACH(const CTransaction& tx, vtx)
1342 if (!tx.IsFinal(nHeight, GetBlockTime()))
1343 return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
1344
1345 // Check that the block chain matches the known block chain up to a checkpoint
1346 if (!Checkpoints::CheckBlock(nHeight, hash))
1347 return DoS(100, error("AcceptBlock() : rejected by checkpoint lockin at %d", nHeight));
1348
1349 // Write block to history file
1350 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK)))
1351 return error("AcceptBlock() : out of disk space");
1352 unsigned int nFile = -1;
1353 unsigned int nBlockPos = 0;
1354 if (!WriteToDisk(nFile, nBlockPos))
1355 return error("AcceptBlock() : WriteToDisk failed");
1356 if (!AddToBlockIndex(nFile, nBlockPos))
1357 return error("AcceptBlock() : AddToBlockIndex failed");
1358
1359 // Relay inventory, but don't relay old inventory during initial block download
1360 if (hashBestChain == hash)
1361 {
1362 SCOPED_LOCK(cs_vNodes);
1363 BOOST_FOREACH(CNode* pnode, vNodes)
1364 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 140700))
1365 pnode->PushInventory(CInv(MSG_BLOCK, hash));
1366 }
1367
1368 return true;
1369}
1370
1371bool ProcessBlock(CNode* pfrom, CBlock* pblock)
1372{
1373 // Whose block we are trying.
1374 string peer_ip;
1375
1376 if (pfrom != NULL) {
1377 peer_ip = pfrom->addr.ToStringIP(); // if candidate block came from a peer
1378 } else {
1379 peer_ip = "LOCAL"; // if it came from, e.g., EatBlock
1380 }
1381
1382 // Check for duplicate
1383 uint256 hash = pblock->GetHash();
1384 if (mapBlockIndex.count(hash))
1385 return error("ProcessBlock() : already have block %d %s from peer %s",
1386 mapBlockIndex[hash]->nHeight, hash.ToString().c_str(),
1387 peer_ip.c_str());
1388
1389 // Preliminary checks
1390 if (!pblock->CheckBlock())
1391 return error("ProcessBlock() : CheckBlock FAILED from peer %s", peer_ip.c_str());
1392
1393 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(mapBlockIndex);
1394 if (pcheckpoint && pblock->hashPrevBlock != hashBestChain)
1395 {
1396 // Extra checks to prevent "fill up memory by spamming with bogus blocks"
1397 int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
1398 if (deltaTime < 0)
1399 {
1400 if (pfrom)
1401 pfrom->Misbehaving(100);
1402 return error("ProcessBlock() : block with timestamp before last checkpoint from peer %s",
1403 peer_ip.c_str());
1404 }
1405 CBigNum bnNewBlock;
1406 bnNewBlock.SetCompact(pblock->nBits);
1407 CBigNum bnRequired;
1408 bnRequired.SetCompact(ComputeMinWork(pcheckpoint->nBits, deltaTime));
1409 if (bnNewBlock > bnRequired)
1410 {
1411 if (pfrom)
1412 pfrom->Misbehaving(100);
1413 return error("ProcessBlock() : block with too little proof-of-work from peer %s",
1414 peer_ip.c_str());
1415 }
1416 }
1417
1418 // If don't already have its previous block, throw it out!
1419 if (!mapBlockIndex.count(pblock->hashPrevBlock))
1420 {
1421 printf("ProcessBlock: BASTARD BLOCK, prev=%s, DISCARDED from peer %s\n",
1422 pblock->hashPrevBlock.ToString().c_str(),
1423 peer_ip.c_str());
1424
1425 // Ask this guy to fill in what we're missing
1426 if (pfrom)
1427 pfrom->PushGetBlocks(pindexBest, pblock->hashPrevBlock);
1428
1429 return true;
1430 }
1431
1432 // Store to disk
1433 if (!pblock->AcceptBlock())
1434 return error("ProcessBlock() : AcceptBlock FAILED from peer %s", peer_ip.c_str());
1435
1436 printf("ProcessBlock: ACCEPTED block %s from: %s\n",
1437 hash.ToString().c_str(), peer_ip.c_str());
1438
1439 return true;
1440}
1441
1442
1443
1444
1445
1446
1447
1448
1449bool CheckDiskSpace(uint64 nAdditionalBytes)
1450{
1451 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
1452
1453 // Check for 15MB because database could create another 10MB log file at any time
1454 if (nFreeBytesAvailable < (uint64)15000000 + nAdditionalBytes)
1455 {
1456 fShutdown = true;
1457 string strMessage = _("Warning: Disk space is low ");
1458 strMiscWarning = strMessage;
1459 printf("*** %s\n", strMessage.c_str());
1460 ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION);
1461 CreateThread(Shutdown, NULL);
1462 return false;
1463 }
1464 return true;
1465}
1466
1467FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
1468{
1469 if (nFile == -1)
1470 return NULL;
1471 FILE* file = fopen(strprintf("%s/blk%04d.dat", GetDataDir().c_str(), nFile).c_str(), pszMode);
1472 if (!file)
1473 return NULL;
1474 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
1475 {
1476 if (fseek(file, nBlockPos, SEEK_SET) != 0)
1477 {
1478 fclose(file);
1479 return NULL;
1480 }
1481 }
1482 return file;
1483}
1484
1485static unsigned int nCurrentBlockFile = 1;
1486
1487FILE* AppendBlockFile(unsigned int& nFileRet)
1488{
1489 nFileRet = 0;
1490 loop
1491 {
1492 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
1493 if (!file)
1494 return NULL;
1495 if (fseek(file, 0, SEEK_END) != 0)
1496 return NULL;
1497 // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
1498 if (ftell(file) < 0x7F000000 - MAX_SIZE)
1499 {
1500 nFileRet = nCurrentBlockFile;
1501 return file;
1502 }
1503 fclose(file);
1504 nCurrentBlockFile++;
1505 }
1506}
1507
1508bool LoadBlockIndex(bool fAllowNew)
1509{
1510 //
1511 // Load block index
1512 //
1513 CTxDB txdb("cr");
1514 if (!txdb.LoadBlockIndex())
1515 return false;
1516 txdb.Close();
1517
1518 //
1519 // Init with genesis block
1520 //
1521 if (mapBlockIndex.empty())
1522 {
1523 if (!fAllowNew)
1524 return false;
1525
1526 // Genesis Block:
1527 // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
1528 // CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
1529 // CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
1530 // CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
1531 // vMerkleTree: 4a5e1e
1532
1533 // Genesis block
1534 const char* pszTimestamp = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks";
1535 CTransaction txNew;
1536 txNew.vin.resize(1);
1537 txNew.vout.resize(1);
1538 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
1539 txNew.vout[0].nValue = 50 * COIN;
1540 txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG;
1541 CBlock block;
1542 block.vtx.push_back(txNew);
1543 block.hashPrevBlock = 0;
1544 block.hashMerkleRoot = block.BuildMerkleTree();
1545 block.nVersion = 1;
1546 block.nTime = 1231006505;
1547 block.nBits = 0x1d00ffff;
1548 block.nNonce = 2083236893;
1549
1550 //// debug print
1551 printf("%s\n", block.GetHash().ToString().c_str());
1552 printf("%s\n", hashGenesisBlock.ToString().c_str());
1553 printf("%s\n", block.hashMerkleRoot.ToString().c_str());
1554 assert(block.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));
1555 block.print();
1556 assert(block.GetHash() == hashGenesisBlock);
1557
1558 // Start new block file
1559 unsigned int nFile;
1560 unsigned int nBlockPos;
1561 if (!block.WriteToDisk(nFile, nBlockPos))
1562 return error("LoadBlockIndex() : writing genesis block to disk failed");
1563 if (!block.AddToBlockIndex(nFile, nBlockPos))
1564 return error("LoadBlockIndex() : genesis block not accepted");
1565 }
1566
1567 return true;
1568}
1569
1570
1571
1572void PrintBlockTree()
1573{
1574 // precompute tree structure
1575 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
1576 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
1577 {
1578 CBlockIndex* pindex = (*mi).second;
1579 mapNext[pindex->pprev].push_back(pindex);
1580 // test
1581 //while (rand() % 3 == 0)
1582 // mapNext[pindex->pprev].push_back(pindex);
1583 }
1584
1585 vector<pair<int, CBlockIndex*> > vStack;
1586 vStack.push_back(make_pair(0, pindexGenesisBlock));
1587
1588 int nPrevCol = 0;
1589 while (!vStack.empty())
1590 {
1591 int nCol = vStack.back().first;
1592 CBlockIndex* pindex = vStack.back().second;
1593 vStack.pop_back();
1594
1595 // print split or gap
1596 if (nCol > nPrevCol)
1597 {
1598 for (int i = 0; i < nCol-1; i++)
1599 printf("| ");
1600 printf("|\\\n");
1601 }
1602 else if (nCol < nPrevCol)
1603 {
1604 for (int i = 0; i < nCol; i++)
1605 printf("| ");
1606 printf("|\n");
1607 }
1608 nPrevCol = nCol;
1609
1610 // print columns
1611 for (int i = 0; i < nCol; i++)
1612 printf("| ");
1613
1614 // print item
1615 CBlock block;
1616 block.ReadFromDisk(pindex);
1617 printf("%d (%u,%u) %s %s tx %d",
1618 pindex->nHeight,
1619 pindex->nFile,
1620 pindex->nBlockPos,
1621 block.GetHash().ToString().c_str(),
1622 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
1623 block.vtx.size());
1624
1625 PrintWallets(block);
1626
1627 // put the main timechain first
1628 vector<CBlockIndex*>& vNext = mapNext[pindex];
1629 for (int i = 0; i < vNext.size(); i++)
1630 {
1631 if (vNext[i]->pnext)
1632 {
1633 swap(vNext[0], vNext[i]);
1634 break;
1635 }
1636 }
1637
1638 // iterate children
1639 for (int i = 0; i < vNext.size(); i++)
1640 vStack.push_back(make_pair(nCol+i, vNext[i]));
1641 }
1642}
1643
1644
1645
1646//////////////////////////////////////////////////////////////////////////////
1647//
1648// Warnings (was: CAlert)
1649//
1650
1651string GetWarnings(string strFor)
1652{
1653 string strStatusBar;
1654 string strRPC;
1655 if (fTestSafeMode)
1656 strRPC = "test";
1657
1658 // Misc warnings like out of disk space and clock is wrong
1659 if (strMiscWarning != "")
1660 strStatusBar = strMiscWarning;
1661
1662 // Longer proof-of-work chain that failed validation
1663 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
1664 // message partially duplicated in InvalidChainFound
1665 strStatusBar = strRPC = "WARNING: Failed to validate chain with greater proof-of-work. Displayed transactions may not be correct! Your database or other nodes may be corrupted.";
1666
1667 if (strFor == "statusbar")
1668 return strStatusBar;
1669 else if (strFor == "rpc")
1670 return strRPC;
1671 assert(!"GetWarnings() : invalid parameter");
1672 return "error";
1673}
1674
1675
1676//////////////////////////////////////////////////////////////////////////////
1677//
1678// Messages
1679//
1680
1681
1682bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
1683{
1684 switch (inv.type)
1685 {
1686 case MSG_TX: return mapTransactions.count(inv.hash) || txdb.ContainsTx(inv.hash);
1687 case MSG_BLOCK: return mapBlockIndex.count(inv.hash);
1688 }
1689 // Don't know what it is, just say we already got one
1690 return true;
1691}
1692
1693
1694
1695
1696// The message start string is designed to be unlikely to occur in normal data.
1697// The characters are rarely used upper ascii, not valid as UTF-8, and produce
1698// a large 4-byte int at any alignment.
1699unsigned char pchMessageStart[4] = { 0xf9, 0xbe, 0xb4, 0xd9 };
1700
1701
1702bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
1703{
1704 RandAddSeedPerfmon();
1705 if (fDebug) {
1706 printf("recv %s %s (%d B)\n", pfrom->addr.ToString().c_str(), strCommand.c_str(), vRecv.size());
1707 }
1708 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
1709 {
1710 printf("dropmessagestest DROPPING RECV MESSAGE\n");
1711 return true;
1712 }
1713
1714
1715
1716
1717
1718 if (strCommand == "version")
1719 {
1720 // Each connection can only send one version message
1721 if (pfrom->nVersion != 0)
1722 {
1723 pfrom->Misbehaving(1);
1724 return false;
1725 }
1726
1727 int64 nTime;
1728 CAddress addrMe;
1729 CAddress addrFrom;
1730 uint64 nNonce = 1;
1731 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
1732 if (pfrom->nVersion == 10300)
1733 pfrom->nVersion = 300;
1734 if (pfrom->nVersion >= 106 && !vRecv.empty())
1735 vRecv >> addrFrom >> nNonce;
1736 if (pfrom->nVersion >= 106 && !vRecv.empty())
1737 vRecv >> pfrom->strSubVer;
1738 if (pfrom->nVersion >= 209 && !vRecv.empty())
1739 vRecv >> pfrom->nStartingHeight;
1740
1741 if (pfrom->nVersion == 0)
1742 return false;
1743
1744 // Disconnect if we connected to ourself
1745 if (nNonce == nLocalHostNonce && nNonce > 1)
1746 {
1747 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
1748 pfrom->fDisconnect = true;
1749 return true;
1750 }
1751
1752 // Be shy and don't send version until we hear
1753 if (pfrom->fInbound)
1754 pfrom->PushVersion();
1755
1756 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
1757
1758 AddTimeData(pfrom->addr.ip, nTime);
1759
1760 // Change version
1761 if (pfrom->nVersion >= 209)
1762 pfrom->PushMessage("verack");
1763 pfrom->vSend.SetVersion(min(pfrom->nVersion, VERSION));
1764 if (pfrom->nVersion < 209)
1765 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
1766
1767 if (!pfrom->fInbound)
1768 {
1769 // Advertise our address
1770 if (addrLocalHost.IsRoutable() && !fUseProxy)
1771 {
1772 CAddress addr(addrLocalHost);
1773 addr.nTime = GetAdjustedTime();
1774 pfrom->PushAddress(addr);
1775 }
1776
1777 // Get recent addresses
1778 if (pfrom->nVersion >= 31402 || mapAddresses.size() < 1000)
1779 {
1780 pfrom->PushMessage("getaddr");
1781 pfrom->fGetAddr = true;
1782 }
1783 }
1784
1785 // Ask EVERY connected node (other than self) for block updates
1786 if (!pfrom->fClient)
1787 {
1788 pfrom->PushGetBlocks(pindexBest, uint256(0));
1789 }
1790
1791 pfrom->fSuccessfullyConnected = true;
1792
1793 printf("version message: version %d, blocks=%d\n", pfrom->nVersion, pfrom->nStartingHeight);
1794
1795 cPeerBlockCounts.input(pfrom->nStartingHeight);
1796 }
1797
1798
1799 else if (pfrom->nVersion == 0)
1800 {
1801 // Must have a version message before anything else
1802 pfrom->Misbehaving(1);
1803 return false;
1804 }
1805
1806
1807 else if (strCommand == "verack")
1808 {
1809 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
1810 }
1811
1812
1813 else if (strCommand == "addr")
1814 {
1815 vector<CAddress> vAddr;
1816 vRecv >> vAddr;
1817
1818 // Don't want addr from older versions unless seeding
1819 if (pfrom->nVersion < 209)
1820 return true;
1821 if (pfrom->nVersion < 31402 && mapAddresses.size() > 1000)
1822 return true;
1823 if (vAddr.size() > 1000)
1824 {
1825 pfrom->Misbehaving(20);
1826 return error("message addr size() = %d", vAddr.size());
1827 }
1828
1829 // Store the new addresses
1830 CAddrDB addrDB;
1831 addrDB.TxnBegin();
1832 int64 nNow = GetAdjustedTime();
1833 int64 nSince = nNow - 10 * 60;
1834 BOOST_FOREACH(CAddress& addr, vAddr)
1835 {
1836 if (fShutdown)
1837 return true;
1838 // ignore IPv6 for now, since it isn't implemented anyway
1839 if (!addr.IsIPv4())
1840 continue;
1841 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
1842 addr.nTime = nNow - 5 * 24 * 60 * 60;
1843 AddAddress(addr, 2 * 60 * 60, &addrDB);
1844 pfrom->AddAddressKnown(addr);
1845 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
1846 {
1847 // Relay to a limited number of other nodes
1848 CRITICAL_BLOCK(cs_vNodes)
1849 {
1850 // Use deterministic randomness to send to the same nodes for 24 hours
1851 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
1852 static uint256 hashSalt;
1853 if (hashSalt == 0)
1854 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
1855 uint256 hashRand = hashSalt ^ (((int64)addr.ip)<<32) ^ ((GetTime()+addr.ip)/(24*60*60));
1856 hashRand = Hash(BEGIN(hashRand), END(hashRand));
1857 multimap<uint256, CNode*> mapMix;
1858 BOOST_FOREACH(CNode* pnode, vNodes)
1859 {
1860 if (pnode->nVersion < 31402)
1861 continue;
1862 unsigned int nPointer;
1863 memcpy(&nPointer, &pnode, sizeof(nPointer));
1864 uint256 hashKey = hashRand ^ nPointer;
1865 hashKey = Hash(BEGIN(hashKey), END(hashKey));
1866 mapMix.insert(make_pair(hashKey, pnode));
1867 }
1868 int nRelayNodes = 2;
1869 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
1870 ((*mi).second)->PushAddress(addr);
1871 }
1872 }
1873 }
1874 addrDB.TxnCommit(); // Save addresses (it's ok if this fails)
1875 if (vAddr.size() < 1000)
1876 pfrom->fGetAddr = false;
1877 }
1878
1879
1880 else if (strCommand == "inv")
1881 {
1882 vector<CInv> vInv;
1883 vRecv >> vInv;
1884 if (vInv.size() > 50000)
1885 {
1886 pfrom->Misbehaving(20);
1887 return error("message inv size() = %d", vInv.size());
1888 }
1889
1890 CTxDB txdb("r");
1891 BOOST_FOREACH(const CInv& inv, vInv)
1892 {
1893 if (fShutdown)
1894 return true;
1895 pfrom->AddInventoryKnown(inv);
1896
1897 bool fAlreadyHave = AlreadyHave(txdb, inv);
1898 if (fDebug)
1899 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
1900
1901 if (!fAlreadyHave)
1902 pfrom->AskFor(inv);
1903
1904 // Track requests for our stuff
1905 Inventory(inv.hash);
1906 }
1907 }
1908
1909
1910 else if (strCommand == "getdata")
1911 {
1912 vector<CInv> vInv;
1913 vRecv >> vInv;
1914 if (vInv.size() > 50000)
1915 {
1916 pfrom->Misbehaving(20);
1917 return error("message getdata size() = %d", vInv.size());
1918 }
1919
1920 BOOST_FOREACH(const CInv& inv, vInv)
1921 {
1922 if (fShutdown)
1923 return true;
1924 printf("received getdata for: %s\n", inv.ToString().c_str());
1925
1926 if (inv.type == MSG_BLOCK)
1927 {
1928 // Send block from disk
1929 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
1930 if (mi != mapBlockIndex.end())
1931 {
1932 CBlock block;
1933 block.ReadFromDisk((*mi).second);
1934 pfrom->PushMessage("block", pfrom->SendingStream() << block);
1935
1936 // Trigger them to send a getblocks request for the next batch of inventory
1937 if (inv.hash == pfrom->hashContinue)
1938 {
1939 // Bypass PushInventory, this must send even if redundant,
1940 // and we want it right after the last block so they don't
1941 // wait for other stuff first.
1942 vector<CInv> vInv;
1943 vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
1944 pfrom->PushMessage("inv", pfrom->SendingStream() << vInv);
1945 pfrom->hashContinue = 0;
1946 }
1947 }
1948 }
1949 else if (inv.IsKnownType())
1950 {
1951 // Send stream from relay memory
1952 CRITICAL_BLOCK(cs_mapRelay)
1953 {
1954 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
1955 if (mi != mapRelay.end())
1956 // It's OK to pass the existing CDataStream directly. With the prior family of PushMessage templates it got re-serialized (<<) into vSend while now it's appended (+=), but these are equivalent as per the "Special case" in serialize.h.
1957 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
1958 }
1959 }
1960 else if (!fPermissive)
1961 {
1962 pfrom->Misbehaving(100);
1963 return error("BANNED peer issuing unknown inv type.");
1964 }
1965
1966 // Track requests for our stuff
1967 Inventory(inv.hash);
1968 }
1969 }
1970
1971
1972 else if (strCommand == "getblocks")
1973 {
1974 CBlockLocator locator;
1975 uint256 hashStop;
1976 vRecv >> locator >> hashStop;
1977
1978 // Find the last block the caller has in the main chain
1979 CBlockIndex* pindex = locator.GetBlockIndex();
1980
1981 // Send the rest of the chain
1982 if (!pindex)
1983 {
1984 printf("getblocks: null locator block index (shouldn't happen!)\n");
1985 return false;
1986 }
1987 unsigned int nStartHeight = pindex->nHeight + 1;
1988 pindex = pindex->pnext;
1989 // Set a conservative limit to avoid flooding the sending buffer and ensure hashContinue is reached when processing the anticipated followup getdata, yet keeping the processing and I/O for this response low. Think of it as a pipeline depth for the download process.
1990 unsigned int nLimit = SendBufferSize() / MAX_BLOCK_SIZE / 2;
1991 if (nLimit == 0) nLimit = 1;
1992 printf("getblocks %d to %s limit %d\n", nStartHeight, hashStop.ToString().c_str(), nLimit);
1993 for (; pindex && pindex->GetBlockHash() != hashStop; pindex = pindex->pnext)
1994 {
1995 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
1996 if (--nLimit == 0)
1997 {
1998 // When this block is requested, we'll send an inv that'll make them
1999 // getblocks the next batch of inventory.
2000 printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
2001 // TODO somehow move this state tracking to the recipient side because there's no guarantee that it sends a getdata for the continuation block.
2002 pfrom->hashContinue = pindex->GetBlockHash();
2003 break;
2004 }
2005 }
2006 }
2007
2008
2009 else if (strCommand == "getheaders")
2010 {
2011 CBlockLocator locator;
2012 uint256 hashStop;
2013 vRecv >> locator >> hashStop;
2014
2015 CBlockIndex* pindex = NULL;
2016 vector<CBlock> vHeaders;
2017 if (locator.IsNull())
2018 {
2019 // If locator is null, return the hashStop block
2020 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
2021 if (mi == mapBlockIndex.end())
2022 return true;
2023 pindex = (*mi).second;
2024 printf("getheaders %d at %s\n", pindex->nHeight, hashStop.ToString().c_str());
2025 vHeaders.push_back(pindex->GetBlockHeader());
2026 }
2027 else
2028 {
2029 // Find the last block the caller has in the main chain
2030 pindex = locator.GetBlockIndex();
2031 if (!pindex)
2032 {
2033 printf("getheaders: null locator block index (shouldn't happen!)\n");
2034 return false;
2035 }
2036 unsigned int nStartHeight = pindex->nHeight + 1;
2037 // Avoid flooding the sending buffer, with room to spare for overhead and other requests that may be pending.
2038 unsigned int nLimit = SendBufferSize() / pindex->GetBlockHeader().GetSerializeSize() / 2;
2039 if (nLimit == 0) nLimit = 1;
2040 pindex = pindex->pnext;
2041 printf("getheaders %d to %s limit %d\n", nStartHeight, hashStop.ToString().c_str(), nLimit);
2042 for (; pindex; pindex = pindex->pnext)
2043 {
2044 vHeaders.push_back(pindex->GetBlockHeader());
2045 if (--nLimit == 0 || pindex->GetBlockHash() == hashStop)
2046 break;
2047 }
2048 }
2049 pfrom->PushMessage("headers", pfrom->SendingStream() << vHeaders);
2050 }
2051
2052
2053 else if (strCommand == "tx")
2054 {
2055 vector<uint256> vWorkQueue;
2056 CDataStream vMsg(vRecv);
2057 CTransaction tx;
2058 vRecv >> tx;
2059
2060 CInv inv(MSG_TX, tx.GetHash());
2061 pfrom->AddInventoryKnown(inv);
2062
2063 bool fMissingInputs = false;
2064 if (tx.AcceptToMemoryPool(true, &fMissingInputs))
2065 {
2066 SyncWithWallets(tx, NULL, true);
2067 RelayMessage(inv, vMsg);
2068 mapAlreadyAskedFor.erase(inv);
2069 vWorkQueue.push_back(inv.hash);
2070 }
2071 else if (fMissingInputs)
2072 {
2073 printf("REJECTED orphan tx %s\n", inv.hash.ToString().c_str());
2074 }
2075 if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
2076 }
2077
2078
2079 else if (strCommand == "block")
2080 {
2081 CBlock block;
2082 vRecv >> block;
2083
2084 printf("received block %s\n", block.GetHash().ToString().c_str());
2085 // block.print();
2086
2087 CInv inv(MSG_BLOCK, block.GetHash());
2088 pfrom->AddInventoryKnown(inv);
2089
2090 if (ProcessBlock(pfrom, &block))
2091 mapAlreadyAskedFor.erase(inv);
2092 if (block.nDoS) pfrom->Misbehaving(block.nDoS);
2093 }
2094
2095
2096 else if (strCommand == "getaddr")
2097 {
2098 // Nodes rebroadcast an addr every 24 hours
2099 pfrom->vAddrToSend.clear();
2100 int64 nSince = GetAdjustedTime() - 3 * 60 * 60; // in the last 3 hours
2101 CRITICAL_BLOCK(cs_mapAddresses)
2102 {
2103 unsigned int nCount = 0;
2104 BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2105 {
2106 const CAddress& addr = item.second;
2107 if (addr.nTime > nSince)
2108 nCount++;
2109 }
2110 BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2111 {
2112 const CAddress& addr = item.second;
2113 if (addr.nTime > nSince && GetRand(nCount) < 2500)
2114 pfrom->PushAddress(addr);
2115 }
2116 }
2117 }
2118
2119
2120 else if (strCommand == "checkorder")
2121 {
2122 uint256 hashReply;
2123 vRecv >> hashReply;
2124
2125 // receive-by-IP feature permanently disabled
2126 pfrom->PushMessage("reply", pfrom->SendingStream() << hashReply << (int)2 << string(""));
2127 }
2128
2129
2130 else if (strCommand == "ping")
2131 {
2132 }
2133
2134
2135 else if (!fPermissive)
2136 {
2137 // He who comes to us with a turd, by the turd shall perish.
2138 pfrom->Misbehaving(100);
2139 return error("BANNED peer issuing heathen command.");
2140 }
2141
2142
2143 // Update the last seen time for this node's address
2144 if (pfrom->fNetworkNode)
2145 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
2146 AddressCurrentlyConnected(pfrom->addr);
2147
2148
2149 return true;
2150}
2151
2152bool ProcessMessages(CNode* pfrom)
2153{
2154 CDataStream& vRecv = pfrom->vRecv;
2155 if (vRecv.empty())
2156 return true;
2157 //if (fDebug)
2158 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
2159
2160 //
2161 // Message format
2162 // (4) message start
2163 // (12) command
2164 // (4) size
2165 // (4) checksum
2166 // (x) data
2167 //
2168
2169 loop
2170 {
2171 // Scan for message start
2172 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
2173 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
2174 if (vRecv.end() - pstart < nHeaderSize)
2175 {
2176 if (vRecv.size() > nHeaderSize)
2177 {
2178 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
2179 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
2180 }
2181 break;
2182 }
2183 if (pstart - vRecv.begin() > 0)
2184 printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());
2185 vRecv.erase(vRecv.begin(), pstart);
2186
2187 // Read header
2188 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
2189 CMessageHeader hdr;
2190 vRecv >> hdr;
2191 if (!hdr.IsValid())
2192 {
2193 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
2194 continue;
2195 }
2196 string strCommand = hdr.GetCommand();
2197
2198 // Message size
2199 unsigned int nMessageSize = hdr.nMessageSize;
2200 if (nMessageSize > MAX_SIZE)
2201 {
2202 printf("ProcessMessage(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
2203 continue;
2204 }
2205 if (nMessageSize > vRecv.size())
2206 {
2207 // Rewind and wait for rest of message
2208 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
2209 break;
2210 }
2211
2212 // Checksum
2213 if (vRecv.GetVersion() >= 209)
2214 {
2215 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
2216 unsigned int nChecksum = 0;
2217 memcpy(&nChecksum, &hash, sizeof(nChecksum));
2218 if (nChecksum != hdr.nChecksum)
2219 {
2220 printf("ProcessMessage(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
2221 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
2222 continue;
2223 }
2224 }
2225
2226 // Copy message to its own buffer
2227 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
2228 vRecv.ignore(nMessageSize);
2229
2230 // Process message
2231 bool fRet = false;
2232 try
2233 {
2234 CRITICAL_BLOCK(cs_main)
2235 fRet = ProcessMessage(pfrom, strCommand, vMsg);
2236 if (fShutdown)
2237 return true;
2238 }
2239 catch (std::ios_base::failure& e)
2240 {
2241 if (strstr(e.what(), "end of data"))
2242 {
2243 // Allow exceptions from underlength message on vRecv
2244 printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught, normally caused by a message being shorter than its stated length\n", strCommand.c_str(), nMessageSize, e.what());
2245 }
2246 else if (strstr(e.what(), "size too large"))
2247 {
2248 // Allow exceptions from overlong size
2249 printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
2250 }
2251 else
2252 {
2253 throw;
2254 }
2255 }
2256
2257 if (!fRet)
2258 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
2259 }
2260
2261 vRecv.Compact();
2262 return true;
2263}
2264
2265
2266bool SendMessages(CNode* pto, bool fSendTrickle)
2267{
2268 CRITICAL_BLOCK(cs_main)
2269 {
2270 // Don't send anything until we get their version message
2271 if (pto->nVersion == 0)
2272 return true;
2273
2274 // Keep-alive ping
2275 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty())
2276 pto->PushMessage("ping");
2277
2278 // Resend wallet transactions that haven't gotten in a block yet
2279 ResendWalletTransactions();
2280
2281 // Address refresh broadcast
2282 static int64 nLastRebroadcast;
2283 if (GetTime() - nLastRebroadcast > 24 * 60 * 60)
2284 {
2285 nLastRebroadcast = GetTime();
2286 CRITICAL_BLOCK(cs_vNodes)
2287 {
2288 BOOST_FOREACH(CNode* pnode, vNodes)
2289 {
2290 // Periodically clear setAddrKnown to allow refresh broadcasts
2291 pnode->setAddrKnown.clear();
2292
2293 // Rebroadcast our address
2294 if (addrLocalHost.IsRoutable() && !fUseProxy)
2295 {
2296 CAddress addr(addrLocalHost);
2297 addr.nTime = GetAdjustedTime();
2298 pnode->PushAddress(addr);
2299 }
2300 }
2301 }
2302 }
2303
2304 // Clear out old addresses periodically so it's not too much work at once
2305 static int64 nLastClear;
2306 if (nLastClear == 0)
2307 nLastClear = GetTime();
2308 if (GetTime() - nLastClear > 10 * 60 && vNodes.size() >= 3)
2309 {
2310 nLastClear = GetTime();
2311 CRITICAL_BLOCK(cs_mapAddresses)
2312 {
2313 CAddrDB addrdb;
2314 int64 nSince = GetAdjustedTime() - 14 * 24 * 60 * 60;
2315 for (map<vector<unsigned char>, CAddress>::iterator mi = mapAddresses.begin();
2316 mi != mapAddresses.end();)
2317 {
2318 const CAddress& addr = (*mi).second;
2319 if (addr.nTime < nSince)
2320 {
2321 if (mapAddresses.size() < 1000 || GetTime() > nLastClear + 20)
2322 break;
2323 addrdb.EraseAddress(addr);
2324 mapAddresses.erase(mi++);
2325 }
2326 else
2327 mi++;
2328 }
2329 }
2330 }
2331
2332
2333 //
2334 // Message: addr
2335 //
2336 if (fSendTrickle)
2337 {
2338 vector<CAddress> vAddr;
2339 vAddr.reserve(pto->vAddrToSend.size());
2340 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
2341 {
2342 // returns true if wasn't already contained in the set
2343 if (pto->setAddrKnown.insert(addr).second)
2344 {
2345 vAddr.push_back(addr);
2346 // receiver rejects addr messages larger than 1000
2347 if (vAddr.size() >= 1000)
2348 {
2349 pto->PushMessage("addr", pto->SendingStream() << vAddr);
2350 vAddr.clear();
2351 }
2352 }
2353 }
2354 pto->vAddrToSend.clear();
2355 if (!vAddr.empty())
2356 pto->PushMessage("addr", pto->SendingStream() << vAddr);
2357 }
2358
2359
2360 //
2361 // Message: inventory
2362 //
2363 vector<CInv> vInv;
2364 vector<CInv> vInvWait;
2365 CRITICAL_BLOCK(pto->cs_inventory)
2366 {
2367 vInv.reserve(pto->vInventoryToSend.size());
2368 vInvWait.reserve(pto->vInventoryToSend.size());
2369 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
2370 {
2371 if (pto->setInventoryKnown.count(inv))
2372 continue;
2373
2374 // trickle out tx inv to protect privacy
2375 if (inv.type == MSG_TX && !fSendTrickle)
2376 {
2377 // 1/4 of tx invs blast to all immediately
2378 static uint256 hashSalt;
2379 if (hashSalt == 0)
2380 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2381 uint256 hashRand = inv.hash ^ hashSalt;
2382 hashRand = Hash(BEGIN(hashRand), END(hashRand));
2383 bool fTrickleWait = ((hashRand & 3) != 0);
2384
2385 // always trickle our own transactions
2386 if (!fTrickleWait)
2387 {
2388 CWalletTx wtx;
2389 if (GetTransaction(inv.hash, wtx))
2390 if (wtx.fFromMe)
2391 fTrickleWait = true;
2392 }
2393
2394 if (fTrickleWait)
2395 {
2396 vInvWait.push_back(inv);
2397 continue;
2398 }
2399 }
2400
2401 // returns true if wasn't already contained in the set
2402 if (pto->setInventoryKnown.insert(inv).second)
2403 {
2404 vInv.push_back(inv);
2405 if (vInv.size() >= 1000)
2406 {
2407 pto->PushMessage("inv", pto->SendingStream() << vInv);
2408 vInv.clear();
2409 }
2410 }
2411 }
2412 pto->vInventoryToSend = vInvWait;
2413 }
2414 if (!vInv.empty())
2415 pto->PushMessage("inv", pto->SendingStream() << vInv);
2416
2417
2418 //
2419 // Message: getdata
2420 //
2421 vector<CInv> vGetData;
2422 int64 nNow = GetTime() * 1000000;
2423 CTxDB txdb("r");
2424 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
2425 {
2426 const CInv& inv = (*pto->mapAskFor.begin()).second;
2427 if (!AlreadyHave(txdb, inv))
2428 {
2429 printf("sending getdata: %s\n", inv.ToString().c_str());
2430 vGetData.push_back(inv);
2431 if (vGetData.size() >= 1000)
2432 {
2433 pto->PushMessage("getdata", pto->SendingStream() << vGetData);
2434 vGetData.clear();
2435 }
2436 }
2437 mapAlreadyAskedFor[inv] = nNow;
2438 pto->mapAskFor.erase(pto->mapAskFor.begin());
2439 }
2440 if (!vGetData.empty())
2441 pto->PushMessage("getdata", pto->SendingStream() << vGetData);
2442
2443 }
2444 return true;
2445}
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460//////////////////////////////////////////////////////////////////////////////
2461//
2462// BitcoinMiner
2463//
2464
2465int static FormatHashBlocks(void* pbuffer, unsigned int len)
2466{
2467 unsigned char* pdata = (unsigned char*)pbuffer;
2468 unsigned int blocks = 1 + ((len + 8) / 64);
2469 unsigned char* pend = pdata + 64 * blocks;
2470 memset(pdata + len, 0, 64 * blocks - len);
2471 pdata[len] = 0x80;
2472 unsigned int bits = len * 8;
2473 pend[-1] = (bits >> 0) & 0xff;
2474 pend[-2] = (bits >> 8) & 0xff;
2475 pend[-3] = (bits >> 16) & 0xff;
2476 pend[-4] = (bits >> 24) & 0xff;
2477 return blocks;
2478}
2479
2480static const unsigned int pSHA256InitState[8] =
2481{0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
2482
2483void SHA256Transform(void* pstate, void* pinput, const void* pinit)
2484{
2485 SHA256_CTX ctx;
2486 unsigned char data[64];
2487
2488 SHA256_Init(&ctx);
2489
2490 for (int i = 0; i < 16; i++)
2491 ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);
2492
2493 for (int i = 0; i < 8; i++)
2494 ctx.h[i] = ((uint32_t*)pinit)[i];
2495
2496 SHA256_Update(&ctx, data, sizeof(data));
2497 for (int i = 0; i < 8; i++)
2498 ((uint32_t*)pstate)[i] = ctx.h[i];
2499}
2500
2501//
2502// ScanHash scans nonces looking for a hash with at least some zero bits.
2503// It operates on big endian data. Caller does the byte reversing.
2504// All input buffers are 16-byte aligned. nNonce is usually preserved
2505// between calls, but periodically or if nNonce is 0xffff0000 or above,
2506// the block is rebuilt and nNonce starts over at zero.
2507//
2508unsigned int static ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)
2509{
2510 unsigned int& nNonce = *(unsigned int*)(pdata + 12);
2511 for (;;)
2512 {
2513 // Crypto++ SHA-256
2514 // Hash pdata using pmidstate as the starting state into
2515 // preformatted buffer phash1, then hash phash1 into phash
2516 nNonce++;
2517 SHA256Transform(phash1, pdata, pmidstate);
2518 SHA256Transform(phash, phash1, pSHA256InitState);
2519
2520 // Return the nonce if the hash has at least some zero bits,
2521 // caller will check if it has enough to reach the target
2522 if (((unsigned short*)phash)[14] == 0)
2523 return nNonce;
2524
2525 // If nothing found after trying for a while, return -1
2526 if ((nNonce & 0xffff) == 0)
2527 {
2528 nHashesDone = 0xffff+1;
2529 return -1;
2530 }
2531 }
2532}
2533
2534// Some explaining would be appreciated
2535class COrphan
2536{
2537public:
2538 CTransaction* ptx;
2539 set<uint256> setDependsOn;
2540 double dPriority;
2541
2542 COrphan(CTransaction* ptxIn)
2543 {
2544 ptx = ptxIn;
2545 dPriority = 0;
2546 }
2547
2548 void print() const
2549 {
2550 printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().c_str(), dPriority);
2551 BOOST_FOREACH(uint256 hash, setDependsOn)
2552 printf(" setDependsOn %s\n", hash.ToString().c_str());
2553 }
2554};
2555
2556
2557CBlock* CreateNewBlock(CReserveKey& reservekey)
2558{
2559 CBlockIndex* pindexPrev = pindexBest;
2560
2561 // Create new block
2562 auto_ptr<CBlock> pblock(new CBlock());
2563 if (!pblock.get())
2564 return NULL;
2565
2566 // Create coinbase tx
2567 CTransaction txNew;
2568 txNew.vin.resize(1);
2569 txNew.vin[0].prevout.SetNull();
2570 txNew.vout.resize(1);
2571 SCOPED_LOCK(cs_main); // no later than here because GetReservedKey uses CWalletDB.
2572 txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
2573
2574 // Add our coinbase tx as first transaction
2575 pblock->vtx.push_back(txNew);
2576
2577 // Collect memory pool transactions into the block
2578 int64 nFees = 0;
2579 CRITICAL_BLOCK(cs_mapTransactions)
2580 {
2581 CTxDB txdb("r");
2582
2583 // Priority order to process transactions
2584 list<COrphan> vOrphan; // list memory doesn't move
2585 map<uint256, vector<COrphan*> > mapDependers;
2586 multimap<double, CTransaction*> mapPriority;
2587 for (map<uint256, CTransaction>::iterator mi = mapTransactions.begin(); mi != mapTransactions.end(); ++mi)
2588 {
2589 CTransaction& tx = (*mi).second;
2590 if (tx.IsCoinBase() || !tx.IsFinal())
2591 continue;
2592
2593 COrphan* porphan = NULL;
2594 double dPriority = 0;
2595 BOOST_FOREACH(const CTxIn& txin, tx.vin)
2596 {
2597 // Read prev transaction
2598 CTransaction txPrev;
2599 CTxIndex txindex;
2600 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
2601 {
2602 // Has to wait for dependencies
2603 if (!porphan)
2604 {
2605 // Use list for automatic deletion
2606 vOrphan.push_back(COrphan(&tx));
2607 porphan = &vOrphan.back();
2608 }
2609 mapDependers[txin.prevout.hash].push_back(porphan);
2610 porphan->setDependsOn.insert(txin.prevout.hash);
2611 continue;
2612 }
2613 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
2614
2615 // Read block header
2616 int nConf = txindex.GetDepthInMainChain();
2617
2618 dPriority += (double)nValueIn * nConf;
2619
2620 if (fDebug && GetBoolArg("-printpriority"))
2621 printf("priority nValueIn=%-12I64d nConf=%-5d dPriority=%-20.1f\n", nValueIn, nConf, dPriority);
2622 }
2623
2624 // Priority is sum(valuein * age) / txsize
2625 // XXX This should probably be (fee / txsize), but may need to refactor to get the fee
2626 dPriority /= ::GetSerializeSize(tx, SER_NETWORK);
2627
2628 if (porphan)
2629 porphan->dPriority = dPriority;
2630 else
2631 mapPriority.insert(make_pair(-dPriority, &(*mi).second));
2632
2633 if (fDebug && GetBoolArg("-printpriority"))
2634 {
2635 printf("priority %-20.1f %s\n%s", dPriority, tx.GetHash().ToString().c_str(), tx.ToString().c_str());
2636 if (porphan)
2637 porphan->print();
2638 printf("\n");
2639 }
2640 }
2641
2642 // Collect transactions into block
2643 map<uint256, CTxIndex> mapTestPool;
2644 uint64 nBlockSize = 1000;
2645 int nBlockSigOps = 100;
2646 while (!mapPriority.empty())
2647 {
2648 // Take highest priority transaction off priority queue
2649 double dPriority = -(*mapPriority.begin()).first;
2650 CTransaction& tx = *(*mapPriority.begin()).second;
2651 mapPriority.erase(mapPriority.begin());
2652
2653 // Size limits
2654 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK);
2655 if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN)
2656 continue;
2657 int nTxSigOps = tx.GetSigOpCount();
2658 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
2659 continue;
2660
2661 // Transaction fee required depends on size and current configuration
2662 // XXX Mostly redundant since tx was already accepted to mempool based on its fee. But perhaps the threshold has changed, and for now we need to maintain at least some way to prevent better-paying transactions from being drowned out.
2663 int64 nMinFee = tx.GetMinFee();
2664
2665 // Connecting shouldn't fail due to dependency on other memory pool transactions
2666 // because we're already processing them in order of dependency
2667 map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
2668 bool fInvalid;
2669 if (!tx.ConnectInputs(txdb, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, nFees, false, true, nMinFee, fInvalid))
2670 continue;
2671 swap(mapTestPool, mapTestPoolTmp);
2672
2673 // Added
2674 pblock->vtx.push_back(tx);
2675 nBlockSize += nTxSize;
2676 nBlockSigOps += nTxSigOps;
2677
2678 // Add transactions that depend on this one to the priority queue
2679 uint256 hash = tx.GetHash();
2680 if (mapDependers.count(hash))
2681 {
2682 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
2683 {
2684 if (!porphan->setDependsOn.empty())
2685 {
2686 porphan->setDependsOn.erase(hash);
2687 if (porphan->setDependsOn.empty())
2688 mapPriority.insert(make_pair(-porphan->dPriority, porphan->ptx));
2689 }
2690 }
2691 }
2692 }
2693 }
2694 pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);
2695
2696 // Fill in header
2697 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
2698 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
2699 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
2700 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock.get());
2701 pblock->nNonce = 0;
2702
2703 return pblock.release();
2704}
2705
2706
2707void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
2708{
2709 // Update nExtraNonce
2710 static uint256 hashPrevBlock;
2711 if (hashPrevBlock != pblock->hashPrevBlock)
2712 {
2713 nExtraNonce = 0;
2714 hashPrevBlock = pblock->hashPrevBlock;
2715 }
2716 ++nExtraNonce;
2717 pblock->vtx[0].vin[0].scriptSig = CScript() << pblock->nTime << CBigNum(nExtraNonce);
2718 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
2719}
2720
2721
2722void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
2723{
2724 //
2725 // Prebuild hash buffers
2726 //
2727 struct
2728 {
2729 struct unnamed2
2730 {
2731 int nVersion;
2732 uint256 hashPrevBlock;
2733 uint256 hashMerkleRoot;
2734 unsigned int nTime;
2735 unsigned int nBits;
2736 unsigned int nNonce;
2737 }
2738 block;
2739 unsigned char pchPadding0[64];
2740 uint256 hash1;
2741 unsigned char pchPadding1[64];
2742 }
2743 tmp;
2744 memset(&tmp, 0, sizeof(tmp));
2745
2746 tmp.block.nVersion = pblock->nVersion;
2747 tmp.block.hashPrevBlock = pblock->hashPrevBlock;
2748 tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
2749 tmp.block.nTime = pblock->nTime;
2750 tmp.block.nBits = pblock->nBits;
2751 tmp.block.nNonce = pblock->nNonce;
2752
2753 FormatHashBlocks(&tmp.block, sizeof(tmp.block));
2754 FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
2755
2756 // Byte swap all the input buffer
2757 for (int i = 0; i < sizeof(tmp)/4; i++)
2758 ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
2759
2760 // Precalc the first half of the first hash, which stays constant
2761 SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
2762
2763 memcpy(pdata, &tmp.block, 128);
2764 memcpy(phash1, &tmp.hash1, 64);
2765}
2766
2767
2768bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
2769{
2770 uint256 hash = pblock->GetHash();
2771 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
2772
2773 if (hash > hashTarget)
2774 return false;
2775
2776 //// debug print
2777 printf("BitcoinMiner:\n");
2778 printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
2779 pblock->print();
2780 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
2781 printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
2782
2783 // Found a solution
2784 CRITICAL_BLOCK(cs_main)
2785 {
2786 if (pblock->hashPrevBlock != hashBestChain)
2787 return error("BitcoinMiner : generated block is stale");
2788
2789 // Remove key from key pool
2790 reservekey.KeepKey();
2791
2792 // Track how many getdata requests this block gets
2793 CRITICAL_BLOCK(wallet.cs_wallet)
2794 wallet.mapRequestCount[pblock->GetHash()] = 0;
2795
2796 // Process this block the same as if we had received it from another node
2797 if (!ProcessBlock(NULL, pblock))
2798 return error("BitcoinMiner : ProcessBlock, block not accepted");
2799 }
2800
2801 return true;
2802}
2803
2804void static ThreadBitcoinMiner(void* parg);
2805
2806void static BitcoinMiner(CWallet *pwallet)
2807{
2808 printf("BitcoinMiner started\n");
2809 SetThreadPriority(THREAD_PRIORITY_LOWEST);
2810
2811 // Each thread has its own key and counter
2812 CReserveKey reservekey(pwallet);
2813 unsigned int nExtraNonce = 0;
2814
2815 while (fGenerateBitcoins)
2816 {
2817 if (AffinityBugWorkaround(ThreadBitcoinMiner))
2818 return;
2819 if (fShutdown)
2820 return;
2821 while (vNodes.empty() || IsInitialBlockDownload())
2822 {
2823 Sleep(1000);
2824 if (fShutdown)
2825 return;
2826 if (!fGenerateBitcoins)
2827 return;
2828 }
2829
2830
2831 //
2832 // Create new block
2833 //
2834 unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
2835 CBlockIndex* pindexPrev = pindexBest;
2836
2837 auto_ptr<CBlock> pblock(CreateNewBlock(reservekey));
2838 if (!pblock.get())
2839 return;
2840 IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce);
2841
2842 printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());
2843
2844
2845 //
2846 // Prebuild hash buffers
2847 //
2848 char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
2849 char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf);
2850 char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf);
2851
2852 FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1);
2853
2854 unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
2855 unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
2856
2857
2858 //
2859 // Search
2860 //
2861 int64 nStart = GetTime();
2862 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
2863 uint256 hashbuf[2];
2864 uint256& hash = *alignup<16>(hashbuf);
2865 loop
2866 {
2867 unsigned int nHashesDone = 0;
2868 unsigned int nNonceFound;
2869
2870 // Crypto++ SHA-256
2871 nNonceFound = ScanHash_CryptoPP(pmidstate, pdata + 64, phash1,
2872 (char*)&hash, nHashesDone);
2873
2874 // Check if something found
2875 if (nNonceFound != -1)
2876 {
2877 for (int i = 0; i < sizeof(hash)/4; i++)
2878 ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
2879
2880 if (hash <= hashTarget)
2881 {
2882 // Found a solution
2883 pblock->nNonce = ByteReverse(nNonceFound);
2884 assert(hash == pblock->GetHash());
2885
2886 SetThreadPriority(THREAD_PRIORITY_NORMAL);
2887 CheckWork(pblock.get(), *pwalletMain, reservekey);
2888 SetThreadPriority(THREAD_PRIORITY_LOWEST);
2889 break;
2890 }
2891 }
2892
2893 // Meter hashes/sec
2894 static int64 nHashCounter;
2895 if (nHPSTimerStart == 0)
2896 {
2897 nHPSTimerStart = GetTimeMillis();
2898 nHashCounter = 0;
2899 }
2900 else
2901 nHashCounter += nHashesDone;
2902 if (GetTimeMillis() - nHPSTimerStart > 4000)
2903 {
2904 static CCriticalSection cs;
2905 CRITICAL_BLOCK(cs)
2906 {
2907 if (GetTimeMillis() - nHPSTimerStart > 4000)
2908 {
2909 dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
2910 nHPSTimerStart = GetTimeMillis();
2911 nHashCounter = 0;
2912 string strStatus = strprintf(" %.0f khash/s", dHashesPerSec/1000.0);
2913 UIThreadCall(boost::bind(CalledSetStatusBar, strStatus, 0));
2914 static int64 nLogTime;
2915 if (GetTime() - nLogTime > 30 * 60)
2916 {
2917 nLogTime = GetTime();
2918 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
2919 printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[3], dHashesPerSec/1000.0);
2920 }
2921 }
2922 }
2923 }
2924
2925 // Check for stop or if block needs to be rebuilt
2926 if (fShutdown)
2927 return;
2928 if (!fGenerateBitcoins)
2929 return;
2930 if (fLimitProcessors && vnThreadsRunning[3] > nLimitProcessors)
2931 return;
2932 if (vNodes.empty())
2933 break;
2934 if (nBlockNonce >= 0xffff0000)
2935 break;
2936 if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
2937 break;
2938 if (pindexPrev != pindexBest)
2939 break;
2940
2941 // Update nTime every few seconds
2942 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
2943 nBlockTime = ByteReverse(pblock->nTime);
2944 }
2945 }
2946}
2947
2948void static ThreadBitcoinMiner(void* parg)
2949{
2950 CWallet* pwallet = (CWallet*)parg;
2951 try
2952 {
2953 vnThreadsRunning[3]++;
2954 BitcoinMiner(pwallet);
2955 vnThreadsRunning[3]--;
2956 }
2957 catch (std::exception& e) {
2958 vnThreadsRunning[3]--;
2959 PrintException(&e, "ThreadBitcoinMiner()");
2960 } catch (...) {
2961 vnThreadsRunning[3]--;
2962 PrintException(NULL, "ThreadBitcoinMiner()");
2963 }
2964 UIThreadCall(boost::bind(CalledSetStatusBar, "", 0));
2965 nHPSTimerStart = 0;
2966 if (vnThreadsRunning[3] == 0)
2967 dHashesPerSec = 0;
2968 printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[3]);
2969}
2970
2971
2972void GenerateBitcoins(CWallet* pwallet)
2973{
2974 if (fGenerateBitcoins)
2975 {
2976 int nProcessors = boost::thread::hardware_concurrency();
2977 printf("%d processors\n", nProcessors);
2978 if (nProcessors < 1)
2979 nProcessors = 1;
2980 if (fLimitProcessors && nProcessors > nLimitProcessors)
2981 nProcessors = nLimitProcessors;
2982 int nAddThreads = nProcessors - vnThreadsRunning[3];
2983 printf("Starting %d BitcoinMiner threads\n", nAddThreads);
2984 for (int i = 0; i < nAddThreads; i++)
2985 {
2986 if (!CreateThread(ThreadBitcoinMiner, pwallet))
2987 printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");
2988 Sleep(10);
2989 }
2990 }
2991}