Projects : bitcoin : bitcoin_tx_fee_cleanup

bitcoin/src/main.cpp

Dir - Raw

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