Projects : bitcoin : bitcoin_rebranding

bitcoin/src/main.cpp

Dir - Raw

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