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