Projects : bitcoin : bitcoin_getblockindex_etc

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