Projects : bitcoin : bitcoin_checkblocks_cleanup

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