Projects : bitcoin : bitcoin_dumpblock_no_losers

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