]> Git Repo - VerusCoin.git/blame - src/main.cpp
Merge pull request #1947 from centromere/freebsd_cpu_fix
[VerusCoin.git] / src / main.cpp
CommitLineData
0a61b0df 1// Copyright (c) 2009-2010 Satoshi Nakamoto
88216419 2// Copyright (c) 2009-2012 The Bitcoin developers
0a61b0df 3// Distributed under the MIT/X11 software license, see the accompanying
3a25a2b9
F
4// file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
f35c6c4f 6#include "alert.h"
eb5fff9e 7#include "checkpoints.h"
1512d5ce 8#include "db.h"
2d8a4829 9#include "txdb.h"
40c2614e 10#include "net.h"
edd309e5 11#include "init.h"
ed6d0b5f 12#include "ui_interface.h"
d237f62c 13#include <boost/algorithm/string/replace.hpp>
926e14b3 14#include <boost/filesystem.hpp>
31f29312 15#include <boost/filesystem/fstream.hpp>
0a61b0df 16
223b6f1b
WL
17using namespace std;
18using namespace boost;
0a61b0df 19
20//
21// Global state
22//
23
64c7ee7e
PW
24CCriticalSection cs_setpwalletRegistered;
25set<CWallet*> setpwalletRegistered;
26
0a61b0df 27CCriticalSection cs_main;
28
8e45ed66 29CTxMemPool mempool;
0a61b0df 30unsigned int nTransactionsUpdated = 0;
0a61b0df 31
32map<uint256, CBlockIndex*> mapBlockIndex;
5cbf7532 33uint256 hashGenesisBlock("0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f");
99860de3 34static CBigNum bnProofOfWorkLimit(~uint256(0) >> 32);
0a61b0df 35CBlockIndex* pindexGenesisBlock = NULL;
36int nBestHeight = -1;
37CBigNum bnBestChainWork = 0;
38CBigNum bnBestInvalidWork = 0;
39uint256 hashBestChain = 0;
40CBlockIndex* pindexBest = NULL;
857c61df 41set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexValid; // may contain all CBlockIndex*'s that have validness >=BLOCK_VALID_TRANSACTIONS, and must contain those who aren't failed
bde280b9 42int64 nTimeBestReceived = 0;
66b02c93 43bool fImporting = false;
0a61b0df 44
a8b95ce6
WL
45CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have
46
0a61b0df 47map<uint256, CBlock*> mapOrphanBlocks;
48multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
49
50map<uint256, CDataStream*> mapOrphanTransactions;
77b99cf7 51map<uint256, map<uint256, CDataStream*> > mapOrphanTransactionsByPrev;
0a61b0df 52
7bf8b7c2
GA
53// Constant stuff for coinbase transactions we create:
54CScript COINBASE_FLAGS;
0a61b0df 55
2bc4fd60
LD
56const string strMessageMagic = "Bitcoin Signed Message:\n";
57
0a61b0df 58double dHashesPerSec;
bde280b9 59int64 nHPSTimerStart;
0a61b0df 60
61// Settings
bde280b9 62int64 nTransactionFee = 0;
972060ce 63
8bb5edc1 64
0a61b0df 65
64c7ee7e
PW
66//////////////////////////////////////////////////////////////////////////////
67//
68// dispatching functions
69//
70
d825e6a3
PW
71// These functions dispatch to one or all registered wallets
72
73
64c7ee7e
PW
74void RegisterWallet(CWallet* pwalletIn)
75{
64c7ee7e 76 {
f8dcd5ca 77 LOCK(cs_setpwalletRegistered);
64c7ee7e
PW
78 setpwalletRegistered.insert(pwalletIn);
79 }
80}
81
82void UnregisterWallet(CWallet* pwalletIn)
83{
64c7ee7e 84 {
f8dcd5ca 85 LOCK(cs_setpwalletRegistered);
64c7ee7e
PW
86 setpwalletRegistered.erase(pwalletIn);
87 }
88}
89
d825e6a3 90// check whether the passed transaction is from us
64c7ee7e
PW
91bool static IsFromMe(CTransaction& tx)
92{
93 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
94 if (pwallet->IsFromMe(tx))
95 return true;
96 return false;
97}
98
d825e6a3 99// get the wallet transaction with the given hash (if it exists)
64c7ee7e
PW
100bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
101{
102 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
103 if (pwallet->GetTransaction(hashTx,wtx))
104 return true;
105 return false;
106}
107
d825e6a3 108// erases transaction with the given hash from all wallets
64c7ee7e
PW
109void static EraseFromWallets(uint256 hash)
110{
111 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
112 pwallet->EraseFromWallet(hash);
113}
114
d825e6a3 115// make sure all wallets know about the given transaction, in the given block
64dd46fd 116void SyncWithWallets(const uint256 &hash, const CTransaction& tx, const CBlock* pblock, bool fUpdate)
64c7ee7e
PW
117{
118 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
64dd46fd 119 pwallet->AddToWalletIfInvolvingMe(hash, tx, pblock, fUpdate);
64c7ee7e
PW
120}
121
d825e6a3 122// notify wallets about a new best chain
64c7ee7e
PW
123void static SetBestChain(const CBlockLocator& loc)
124{
125 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
126 pwallet->SetBestChain(loc);
127}
128
d825e6a3 129// notify wallets about an updated transaction
64c7ee7e
PW
130void static UpdatedTransaction(const uint256& hashTx)
131{
132 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
133 pwallet->UpdatedTransaction(hashTx);
134}
135
d825e6a3 136// dump all wallets
64c7ee7e
PW
137void static PrintWallets(const CBlock& block)
138{
139 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
140 pwallet->PrintWallet(block);
141}
142
d825e6a3 143// notify wallets about an incoming inventory (for request counts)
64c7ee7e
PW
144void static Inventory(const uint256& hash)
145{
146 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
147 pwallet->Inventory(hash);
148}
149
d825e6a3 150// ask wallets to resend their transactions
64c7ee7e
PW
151void static ResendWalletTransactions()
152{
153 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
154 pwallet->ResendWalletTransactions();
155}
156
157
158
159
160
161
162
450cbb09
PW
163//////////////////////////////////////////////////////////////////////////////
164//
165// CCoinsView implementations
166//
167
168bool CCoinsView::GetCoins(uint256 txid, CCoins &coins) { return false; }
169bool CCoinsView::SetCoins(uint256 txid, const CCoins &coins) { return false; }
170bool CCoinsView::HaveCoins(uint256 txid) { return false; }
171CBlockIndex *CCoinsView::GetBestBlock() { return NULL; }
172bool CCoinsView::SetBestBlock(CBlockIndex *pindex) { return false; }
ae8bfd12 173bool CCoinsView::BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex) { return false; }
beeb5761 174bool CCoinsView::GetStats(CCoinsStats &stats) { return false; }
450cbb09 175
13c51f20 176
450cbb09
PW
177CCoinsViewBacked::CCoinsViewBacked(CCoinsView &viewIn) : base(&viewIn) { }
178bool CCoinsViewBacked::GetCoins(uint256 txid, CCoins &coins) { return base->GetCoins(txid, coins); }
179bool CCoinsViewBacked::SetCoins(uint256 txid, const CCoins &coins) { return base->SetCoins(txid, coins); }
180bool CCoinsViewBacked::HaveCoins(uint256 txid) { return base->HaveCoins(txid); }
181CBlockIndex *CCoinsViewBacked::GetBestBlock() { return base->GetBestBlock(); }
182bool CCoinsViewBacked::SetBestBlock(CBlockIndex *pindex) { return base->SetBestBlock(pindex); }
183void CCoinsViewBacked::SetBackend(CCoinsView &viewIn) { base = &viewIn; }
ae8bfd12 184bool CCoinsViewBacked::BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex) { return base->BatchWrite(mapCoins, pindex); }
beeb5761 185bool CCoinsViewBacked::GetStats(CCoinsStats &stats) { return base->GetStats(stats); }
450cbb09
PW
186
187CCoinsViewCache::CCoinsViewCache(CCoinsView &baseIn, bool fDummy) : CCoinsViewBacked(baseIn), pindexTip(NULL) { }
188
189bool CCoinsViewCache::GetCoins(uint256 txid, CCoins &coins) {
190 if (cacheCoins.count(txid)) {
191 coins = cacheCoins[txid];
192 return true;
193 }
194 if (base->GetCoins(txid, coins)) {
195 cacheCoins[txid] = coins;
196 return true;
197 }
198 return false;
199}
200
13c51f20
PW
201std::map<uint256,CCoins>::iterator CCoinsViewCache::FetchCoins(uint256 txid) {
202 std::map<uint256,CCoins>::iterator it = cacheCoins.find(txid);
203 if (it != cacheCoins.end())
204 return it;
205 CCoins tmp;
206 if (!base->GetCoins(txid,tmp))
207 return it;
208 std::pair<std::map<uint256,CCoins>::iterator,bool> ret = cacheCoins.insert(std::make_pair(txid, tmp));
209 return ret.first;
210}
211
212CCoins &CCoinsViewCache::GetCoins(uint256 txid) {
213 std::map<uint256,CCoins>::iterator it = FetchCoins(txid);
214 assert(it != cacheCoins.end());
215 return it->second;
216}
217
450cbb09
PW
218bool CCoinsViewCache::SetCoins(uint256 txid, const CCoins &coins) {
219 cacheCoins[txid] = coins;
220 return true;
221}
222
223bool CCoinsViewCache::HaveCoins(uint256 txid) {
13c51f20 224 return FetchCoins(txid) != cacheCoins.end();
450cbb09
PW
225}
226
227CBlockIndex *CCoinsViewCache::GetBestBlock() {
228 if (pindexTip == NULL)
229 pindexTip = base->GetBestBlock();
230 return pindexTip;
231}
232
233bool CCoinsViewCache::SetBestBlock(CBlockIndex *pindex) {
234 pindexTip = pindex;
235 return true;
236}
237
ae8bfd12
PW
238bool CCoinsViewCache::BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex) {
239 for (std::map<uint256, CCoins>::const_iterator it = mapCoins.begin(); it != mapCoins.end(); it++)
240 cacheCoins[it->first] = it->second;
241 pindexTip = pindex;
450cbb09
PW
242 return true;
243}
244
ae8bfd12
PW
245bool CCoinsViewCache::Flush() {
246 bool fOk = base->BatchWrite(cacheCoins, pindexTip);
247 if (fOk)
248 cacheCoins.clear();
249 return fOk;
250}
251
252unsigned int CCoinsViewCache::GetCacheSize() {
253 return cacheCoins.size();
254}
255
450cbb09
PW
256/** CCoinsView that brings transactions from a memorypool into view.
257 It does not check for spendings by memory pool transactions. */
258CCoinsViewMemPool::CCoinsViewMemPool(CCoinsView &baseIn, CTxMemPool &mempoolIn) : CCoinsViewBacked(baseIn), mempool(mempoolIn) { }
259
260bool CCoinsViewMemPool::GetCoins(uint256 txid, CCoins &coins) {
261 if (base->GetCoins(txid, coins))
262 return true;
263 if (mempool.exists(txid)) {
264 const CTransaction &tx = mempool.lookup(txid);
265 coins = CCoins(tx, MEMPOOL_HEIGHT);
266 return true;
267 }
268 return false;
269}
270
271bool CCoinsViewMemPool::HaveCoins(uint256 txid) {
272 return mempool.exists(txid) || base->HaveCoins(txid);
273}
274
ae8bfd12 275CCoinsViewCache *pcoinsTip = NULL;
d979e6e3 276CBlockTreeDB *pblocktree = NULL;
450cbb09 277
0a61b0df 278//////////////////////////////////////////////////////////////////////////////
279//
280// mapOrphanTransactions
281//
282
77b99cf7 283bool AddOrphanTx(const CDataStream& vMsg)
0a61b0df 284{
285 CTransaction tx;
286 CDataStream(vMsg) >> tx;
287 uint256 hash = tx.GetHash();
288 if (mapOrphanTransactions.count(hash))
77b99cf7
GA
289 return false;
290
291 CDataStream* pvMsg = new CDataStream(vMsg);
142e6041 292
77b99cf7
GA
293 // Ignore big transactions, to avoid a
294 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
295 // large transaction with a missing parent then we assume
296 // it will rebroadcast it later, after the parent transaction(s)
297 // have been mined or received.
298 // 10,000 orphans, each of which is at most 5,000 bytes big is
299 // at most 500 megabytes of orphans:
300 if (pvMsg->size() > 5000)
301 {
d210f4f5 302 printf("ignoring large orphan tx (size: %"PRIszu", hash: %s)\n", pvMsg->size(), hash.ToString().substr(0,10).c_str());
c283b3c5 303 delete pvMsg;
77b99cf7
GA
304 return false;
305 }
142e6041 306
77b99cf7 307 mapOrphanTransactions[hash] = pvMsg;
223b6f1b 308 BOOST_FOREACH(const CTxIn& txin, tx.vin)
77b99cf7
GA
309 mapOrphanTransactionsByPrev[txin.prevout.hash].insert(make_pair(hash, pvMsg));
310
d210f4f5 311 printf("stored orphan tx %s (mapsz %"PRIszu")\n", hash.ToString().substr(0,10).c_str(),
77b99cf7
GA
312 mapOrphanTransactions.size());
313 return true;
0a61b0df 314}
315
64c7ee7e 316void static EraseOrphanTx(uint256 hash)
0a61b0df 317{
318 if (!mapOrphanTransactions.count(hash))
319 return;
320 const CDataStream* pvMsg = mapOrphanTransactions[hash];
321 CTransaction tx;
322 CDataStream(*pvMsg) >> tx;
223b6f1b 323 BOOST_FOREACH(const CTxIn& txin, tx.vin)
0a61b0df 324 {
77b99cf7
GA
325 mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash);
326 if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty())
327 mapOrphanTransactionsByPrev.erase(txin.prevout.hash);
0a61b0df 328 }
329 delete pvMsg;
330 mapOrphanTransactions.erase(hash);
331}
332
7bd9c3a3 333unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
142e6041 334{
7bd9c3a3 335 unsigned int nEvicted = 0;
142e6041
GA
336 while (mapOrphanTransactions.size() > nMaxOrphans)
337 {
338 // Evict a random orphan:
f718aedd 339 uint256 randomhash = GetRandHash();
142e6041
GA
340 map<uint256, CDataStream*>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
341 if (it == mapOrphanTransactions.end())
342 it = mapOrphanTransactions.begin();
343 EraseOrphanTx(it->first);
344 ++nEvicted;
345 }
346 return nEvicted;
347}
0a61b0df 348
349
350
351
352
353
354
355//////////////////////////////////////////////////////////////////////////////
356//
450cbb09 357// CTransaction
0a61b0df 358//
359
e679ec96
GA
360bool CTransaction::IsStandard() const
361{
dae3e10a
GA
362 if (nVersion > CTransaction::CURRENT_VERSION)
363 return false;
364
e679ec96
GA
365 BOOST_FOREACH(const CTxIn& txin, vin)
366 {
2a45a494 367 // Biggest 'standard' txin is a 3-signature 3-of-3 CHECKMULTISIG
922e8e29 368 // pay-to-script-hash, which is 3 ~80-byte signatures, 3
e679ec96 369 // ~65-byte public keys, plus a few script ops.
2a45a494 370 if (txin.scriptSig.size() > 500)
922e8e29 371 return false;
e679ec96 372 if (!txin.scriptSig.IsPushOnly())
922e8e29 373 return false;
e679ec96 374 }
65ce2156 375 BOOST_FOREACH(const CTxOut& txout, vout) {
e679ec96 376 if (!::IsStandard(txout.scriptPubKey))
922e8e29 377 return false;
65ce2156
PW
378 if (txout.nValue == 0)
379 return false;
380 }
e679ec96
GA
381 return true;
382}
383
384//
385// Check transaction inputs, and make sure any
922e8e29 386// pay-to-script-hash transactions are evaluating IsStandard scripts
e679ec96
GA
387//
388// Why bother? To avoid denial-of-service attacks; an attacker
922e8e29
GA
389// can submit a standard HASH... OP_EQUAL transaction,
390// which will get accepted into blocks. The redemption
391// script can be anything; an attacker could use a very
e679ec96
GA
392// expensive-to-check-upon-redemption script like:
393// DUP CHECKSIG DROP ... repeated 100 times... OP_1
394//
13c51f20 395bool CTransaction::AreInputsStandard(CCoinsViewCache& mapInputs) const
e679ec96 396{
8d7849b6 397 if (IsCoinBase())
575bdcde 398 return true; // Coinbases don't use vin normally
8d7849b6 399
c376ac35 400 for (unsigned int i = 0; i < vin.size(); i++)
e679ec96 401 {
8d7849b6 402 const CTxOut& prev = GetOutputFor(vin[i], mapInputs);
e679ec96
GA
403
404 vector<vector<unsigned char> > vSolutions;
2a45a494
GA
405 txnouttype whichType;
406 // get the scriptPubKey corresponding to this input:
8d7849b6 407 const CScript& prevScript = prev.scriptPubKey;
2a45a494 408 if (!Solver(prevScript, whichType, vSolutions))
922e8e29 409 return false;
39f0d968 410 int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
c0a0a93d
JG
411 if (nArgsExpected < 0)
412 return false;
39f0d968
GA
413
414 // Transactions with extra stuff in their scriptSigs are
415 // non-standard. Note that this EvalScript() call will
416 // be quick, because if there are any operations
417 // beside "push data" in the scriptSig the
418 // IsStandard() call returns false
419 vector<vector<unsigned char> > stack;
58bc86e3 420 if (!EvalScript(stack, vin[i].scriptSig, *this, i, false, 0))
39f0d968
GA
421 return false;
422
e679ec96
GA
423 if (whichType == TX_SCRIPTHASH)
424 {
922e8e29 425 if (stack.empty())
e679ec96 426 return false;
2a45a494 427 CScript subscript(stack.back().begin(), stack.back().end());
39f0d968
GA
428 vector<vector<unsigned char> > vSolutions2;
429 txnouttype whichType2;
430 if (!Solver(subscript, whichType2, vSolutions2))
922e8e29 431 return false;
39f0d968
GA
432 if (whichType2 == TX_SCRIPTHASH)
433 return false;
c0a0a93d
JG
434
435 int tmpExpected;
436 tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
437 if (tmpExpected < 0)
438 return false;
439 nArgsExpected += tmpExpected;
e679ec96 440 }
39f0d968 441
c0a0a93d 442 if (stack.size() != (unsigned int)nArgsExpected)
39f0d968 443 return false;
e679ec96
GA
444 }
445
446 return true;
447}
448
7bd9c3a3 449unsigned int
922e8e29
GA
450CTransaction::GetLegacySigOpCount() const
451{
7bd9c3a3 452 unsigned int nSigOps = 0;
922e8e29
GA
453 BOOST_FOREACH(const CTxIn& txin, vin)
454 {
455 nSigOps += txin.scriptSig.GetSigOpCount(false);
456 }
457 BOOST_FOREACH(const CTxOut& txout, vout)
458 {
459 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
460 }
461 return nSigOps;
462}
0a61b0df 463
464
465int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
466{
467 if (fClient)
468 {
469 if (hashBlock == 0)
470 return 0;
471 }
472 else
473 {
474 CBlock blockTmp;
450cbb09
PW
475
476 if (pblock == NULL) {
450cbb09 477 CCoins coins;
ae8bfd12 478 if (pcoinsTip->GetCoins(GetHash(), coins)) {
450cbb09
PW
479 CBlockIndex *pindex = FindBlockByHeight(coins.nHeight);
480 if (pindex) {
481 if (!blockTmp.ReadFromDisk(pindex))
482 return 0;
483 pblock = &blockTmp;
484 }
485 }
0a61b0df 486 }
487
450cbb09 488 if (pblock) {
0a61b0df 489 // Update the tx's hashBlock
490 hashBlock = pblock->GetHash();
491
492 // Locate the transaction
1d8c7a95 493 for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++)
0a61b0df 494 if (pblock->vtx[nIndex] == *(CTransaction*)this)
495 break;
1d8c7a95 496 if (nIndex == (int)pblock->vtx.size())
0a61b0df 497 {
498 vMerkleBranch.clear();
499 nIndex = -1;
500 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
501 return 0;
502 }
503
504 // Fill in merkle branch
505 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
450cbb09 506 }
0a61b0df 507 }
508
509 // Is the tx in a block that's in the main chain
510 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
511 if (mi == mapBlockIndex.end())
512 return 0;
513 CBlockIndex* pindex = (*mi).second;
514 if (!pindex || !pindex->IsInMainChain())
515 return 0;
516
517 return pindexBest->nHeight - pindex->nHeight + 1;
518}
519
520
521
0a61b0df 522
523
524
525
a790fa46 526bool CTransaction::CheckTransaction() const
527{
528 // Basic checks that don't depend on any context
d0d9486f 529 if (vin.empty())
3e52aaf2 530 return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
d0d9486f 531 if (vout.empty())
3e52aaf2 532 return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
a790fa46 533 // Size limits
6b6aaa16 534 if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
3e52aaf2 535 return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
a790fa46 536
537 // Check for negative or overflow output values
bde280b9 538 int64 nValueOut = 0;
223b6f1b 539 BOOST_FOREACH(const CTxOut& txout, vout)
a790fa46 540 {
541 if (txout.nValue < 0)
3e52aaf2 542 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue negative"));
a790fa46 543 if (txout.nValue > MAX_MONEY)
3e52aaf2 544 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
a790fa46 545 nValueOut += txout.nValue;
546 if (!MoneyRange(nValueOut))
3e52aaf2 547 return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
a790fa46 548 }
549
33208fb5
MC
550 // Check for duplicate inputs
551 set<COutPoint> vInOutPoints;
552 BOOST_FOREACH(const CTxIn& txin, vin)
553 {
554 if (vInOutPoints.count(txin.prevout))
555 return false;
556 vInOutPoints.insert(txin.prevout);
557 }
558
a790fa46 559 if (IsCoinBase())
560 {
561 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
3e52aaf2 562 return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size"));
a790fa46 563 }
564 else
565 {
223b6f1b 566 BOOST_FOREACH(const CTxIn& txin, vin)
a790fa46 567 if (txin.prevout.IsNull())
3e52aaf2 568 return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
a790fa46 569 }
570
571 return true;
572}
573
76970091
JG
574int64 CTransaction::GetMinFee(unsigned int nBlockSize, bool fAllowFree,
575 enum GetMinFee_mode mode) const
576{
577 // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
578 int64 nBaseFee = (mode == GMF_RELAY) ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
579
580 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION);
581 unsigned int nNewBlockSize = nBlockSize + nBytes;
582 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
583
584 if (fAllowFree)
585 {
586 if (nBlockSize == 1)
587 {
588 // Transactions under 10K are free
589 // (about 4500 BTC if made of 50 BTC inputs)
590 if (nBytes < 10000)
591 nMinFee = 0;
592 }
593 else
594 {
595 // Free transaction area
596 if (nNewBlockSize < 27000)
597 nMinFee = 0;
598 }
599 }
600
601 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
602 if (nMinFee < nBaseFee)
603 {
604 BOOST_FOREACH(const CTxOut& txout, vout)
605 if (txout.nValue < CENT)
606 nMinFee = nBaseFee;
607 }
608
609 // Raise the price as the block approaches full
610 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
611 {
612 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
613 return MAX_MONEY;
614 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
615 }
616
617 if (!MoneyRange(nMinFee))
618 nMinFee = MAX_MONEY;
619 return nMinFee;
620}
621
450cbb09
PW
622void CTxMemPool::pruneSpent(const uint256 &hashTx, CCoins &coins)
623{
624 LOCK(cs);
625
626 std::map<COutPoint, CInPoint>::iterator it = mapNextTx.lower_bound(COutPoint(hashTx, 0));
627
628 // iterate over all COutPoints in mapNextTx whose hash equals the provided hashTx
629 while (it != mapNextTx.end() && it->first.hash == hashTx) {
630 coins.Spend(it->first.n); // and remove those outputs from coins
631 it++;
632 }
633}
76970091 634
ae8bfd12 635bool CTxMemPool::accept(CTransaction &tx, bool fCheckInputs,
d01903e7 636 bool* pfMissingInputs)
0a61b0df 637{
638 if (pfMissingInputs)
639 *pfMissingInputs = false;
640
d01903e7
JG
641 if (!tx.CheckTransaction())
642 return error("CTxMemPool::accept() : CheckTransaction failed");
a790fa46 643
0a61b0df 644 // Coinbase is only valid in a block, not as a loose transaction
d01903e7
JG
645 if (tx.IsCoinBase())
646 return tx.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx"));
0a61b0df 647
0a61b0df 648 // To help v0.1.5 clients who would see it as a negative number
d01903e7
JG
649 if ((int64)tx.nLockTime > std::numeric_limits<int>::max())
650 return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet");
f1e1fb4b 651
5ec05f0a 652 // Rather not work on nonstandard transactions (unless -testnet)
d01903e7
JG
653 if (!fTestNet && !tx.IsStandard())
654 return error("CTxMemPool::accept() : nonstandard transaction type");
97ee01ad 655
450cbb09 656 // is it already in the memory pool?
d01903e7 657 uint256 hash = tx.GetHash();
f8dcd5ca 658 {
d01903e7
JG
659 LOCK(cs);
660 if (mapTx.count(hash))
0a61b0df 661 return false;
f8dcd5ca 662 }
0a61b0df 663
664 // Check for conflicts with in-memory transactions
665 CTransaction* ptxOld = NULL;
c23617fe 666 for (unsigned int i = 0; i < tx.vin.size(); i++)
0a61b0df 667 {
d01903e7 668 COutPoint outpoint = tx.vin[i].prevout;
0a61b0df 669 if (mapNextTx.count(outpoint))
670 {
671 // Disable replacement feature for now
672 return false;
673
674 // Allow replacing with a newer version of the same transaction
675 if (i != 0)
676 return false;
677 ptxOld = mapNextTx[outpoint].ptx;
683bcb91 678 if (ptxOld->IsFinal())
679 return false;
d01903e7 680 if (!tx.IsNewerThan(*ptxOld))
0a61b0df 681 return false;
c23617fe 682 for (unsigned int i = 0; i < tx.vin.size(); i++)
0a61b0df 683 {
d01903e7 684 COutPoint outpoint = tx.vin[i].prevout;
0a61b0df 685 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
686 return false;
687 }
688 break;
689 }
690 }
691
97ee01ad 692 if (fCheckInputs)
0a61b0df 693 {
4afc0b54
PW
694 CCoinsView dummy;
695 CCoinsViewCache view(dummy);
696
697 {
698 LOCK(cs);
699 CCoinsViewMemPool viewMemPool(*pcoinsTip, *this);
700 view.SetBackend(viewMemPool);
450cbb09
PW
701
702 // do we already have it?
703 if (view.HaveCoins(hash))
33a53bc1 704 return false;
450cbb09
PW
705
706 // do all inputs exist?
c2ed184f
PW
707 // Note that this does not check for the presence of actual outputs (see the next check for that),
708 // only helps filling in pfMissingInputs (to determine missing vs spent).
450cbb09
PW
709 BOOST_FOREACH(const CTxIn txin, tx.vin) {
710 if (!view.HaveCoins(txin.prevout.hash)) {
711 if (pfMissingInputs)
712 *pfMissingInputs = true;
713 return false;
714 }
e679ec96
GA
715 }
716
c2ed184f 717 // are the actual inputs available?
13c51f20
PW
718 if (!tx.HaveInputs(view))
719 return error("CTxMemPool::accept() : inputs already spent");
4afc0b54
PW
720
721 // Bring the best block into scope
722 view.GetBestBlock();
723
724 // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
725 view.SetBackend(dummy);
726 }
13c51f20 727
922e8e29 728 // Check for non-standard pay-to-script-hash in inputs
450cbb09 729 if (!tx.AreInputsStandard(view) && !fTestNet)
d01903e7 730 return error("CTxMemPool::accept() : nonstandard transaction input");
e679ec96 731
137d0685
GA
732 // Note: if you modify this code to accept non-standard transactions, then
733 // you should add code here to check that the transaction does a
734 // reasonable number of ECDSA signature verifications.
735
450cbb09 736 int64 nFees = tx.GetValueIn(view)-tx.GetValueOut();
c23617fe 737 unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
8d7849b6
GA
738
739 // Don't accept it if it can't get into a block
17f8d6e4
JG
740 int64 txMinFee = tx.GetMinFee(1000, true, GMF_RELAY);
741 if (nFees < txMinFee)
742 return error("CTxMemPool::accept() : not enough fees %s, %"PRI64d" < %"PRI64d,
b1d3e95a 743 hash.ToString().c_str(),
17f8d6e4 744 nFees, txMinFee);
922e8e29 745
5de8b54c 746 // Continuously rate-limit free transactions
88abf703 747 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
b49f1398 748 // be annoying or make others' transactions take longer to confirm.
2bfda1be 749 if (nFees < MIN_RELAY_TX_FEE)
97ee01ad 750 {
88abf703 751 static CCriticalSection cs;
5de8b54c 752 static double dFreeCount;
bde280b9
WL
753 static int64 nLastTime;
754 int64 nNow = GetTime();
88abf703 755
97ee01ad 756 {
88abf703
GA
757 // Use an exponentially decaying ~10-minute window:
758 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
759 nLastTime = nNow;
760 // -limitfreerelay unit is thousand-bytes-per-minute
761 // At default rate it would take over a month to fill 1GB
d01903e7
JG
762 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(tx))
763 return error("CTxMemPool::accept() : free transaction rejected by rate limiter");
88abf703
GA
764 if (fDebug)
765 printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
766 dFreeCount += nSize;
97ee01ad 767 }
97ee01ad 768 }
8d7849b6
GA
769
770 // Check against previous transactions
771 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
450cbb09 772 if (!tx.CheckInputs(view, CS_ALWAYS, true, false))
8d7849b6 773 {
d01903e7 774 return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
8d7849b6 775 }
0a61b0df 776 }
777
778 // Store transaction in memory
0a61b0df 779 {
d01903e7 780 LOCK(cs);
0a61b0df 781 if (ptxOld)
782 {
d01903e7
JG
783 printf("CTxMemPool::accept() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
784 remove(*ptxOld);
0a61b0df 785 }
f77654a0 786 addUnchecked(hash, tx);
0a61b0df 787 }
788
789 ///// are we sure this is ok when loading transactions or restoring block txes
790 // If updated, erase old tx from wallet
791 if (ptxOld)
64c7ee7e 792 EraseFromWallets(ptxOld->GetHash());
0a61b0df 793
d210f4f5 794 printf("CTxMemPool::accept() : accepted %s (poolsz %"PRIszu")\n",
133dce6a
JG
795 hash.ToString().substr(0,10).c_str(),
796 mapTx.size());
0a61b0df 797 return true;
798}
799
ae8bfd12 800bool CTransaction::AcceptToMemoryPool(bool fCheckInputs, bool* pfMissingInputs)
d01903e7 801{
ae8bfd12 802 return mempool.accept(*this, fCheckInputs, pfMissingInputs);
d01903e7 803}
340f0876 804
f77654a0 805bool CTxMemPool::addUnchecked(const uint256& hash, CTransaction &tx)
0a61b0df 806{
807 // Add to memory pool without checking anything. Don't call this directly,
d01903e7 808 // call CTxMemPool::accept to properly check the transaction first.
0a61b0df 809 {
8e45ed66 810 mapTx[hash] = tx;
c23617fe 811 for (unsigned int i = 0; i < tx.vin.size(); i++)
8e45ed66 812 mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i);
0a61b0df 813 nTransactionsUpdated++;
814 }
815 return true;
816}
817
818
8e45ed66 819bool CTxMemPool::remove(CTransaction &tx)
0a61b0df 820{
821 // Remove transaction from memory pool
0a61b0df 822 {
8e45ed66
JG
823 LOCK(cs);
824 uint256 hash = tx.GetHash();
825 if (mapTx.count(hash))
74f28bf1 826 {
8e45ed66 827 BOOST_FOREACH(const CTxIn& txin, tx.vin)
74f28bf1 828 mapNextTx.erase(txin.prevout);
8e45ed66 829 mapTx.erase(hash);
74f28bf1 830 nTransactionsUpdated++;
74f28bf1 831 }
0a61b0df 832 }
833 return true;
834}
835
bdab0cf5 836void CTxMemPool::clear()
639b61d7
LD
837{
838 LOCK(cs);
839 mapTx.clear();
840 mapNextTx.clear();
841 ++nTransactionsUpdated;
842}
843
25d5c195
JG
844void CTxMemPool::queryHashes(std::vector<uint256>& vtxid)
845{
846 vtxid.clear();
0a61b0df 847
25d5c195
JG
848 LOCK(cs);
849 vtxid.reserve(mapTx.size());
850 for (map<uint256, CTransaction>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
851 vtxid.push_back((*mi).first);
852}
0a61b0df 853
854
855
856
30ab2c9c 857int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
0a61b0df 858{
859 if (hashBlock == 0 || nIndex == -1)
860 return 0;
861
862 // Find the block it claims to be in
863 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
864 if (mi == mapBlockIndex.end())
865 return 0;
866 CBlockIndex* pindex = (*mi).second;
867 if (!pindex || !pindex->IsInMainChain())
868 return 0;
869
870 // Make sure the merkle branch connects to this block
871 if (!fMerkleVerified)
872 {
873 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
874 return 0;
875 fMerkleVerified = true;
876 }
877
30ab2c9c 878 pindexRet = pindex;
0a61b0df 879 return pindexBest->nHeight - pindex->nHeight + 1;
880}
881
882
883int CMerkleTx::GetBlocksToMaturity() const
884{
885 if (!IsCoinBase())
886 return 0;
887 return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
888}
889
890
ae8bfd12 891bool CMerkleTx::AcceptToMemoryPool(bool fCheckInputs)
0a61b0df 892{
893 if (fClient)
894 {
450cbb09 895 if (!IsInMainChain() && !ClientCheckInputs())
0a61b0df 896 return false;
ae8bfd12 897 return CTransaction::AcceptToMemoryPool(false);
0a61b0df 898 }
899 else
900 {
ae8bfd12 901 return CTransaction::AcceptToMemoryPool(fCheckInputs);
0a61b0df 902 }
903}
904
905
906
ae8bfd12 907bool CWalletTx::AcceptWalletTransaction(bool fCheckInputs)
0a61b0df 908{
0a61b0df 909 {
235507ae 910 LOCK(mempool.cs);
f1e1fb4b 911 // Add previous supporting transactions first
223b6f1b 912 BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
0a61b0df 913 {
914 if (!tx.IsCoinBase())
915 {
916 uint256 hash = tx.GetHash();
ae8bfd12
PW
917 if (!mempool.exists(hash) && pcoinsTip->HaveCoins(hash))
918 tx.AcceptToMemoryPool(fCheckInputs);
0a61b0df 919 }
920 }
ae8bfd12 921 return AcceptToMemoryPool(fCheckInputs);
0a61b0df 922 }
f1e1fb4b 923 return false;
0a61b0df 924}
925
395c1f44 926
c73ba23e 927// Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock
450cbb09 928bool GetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock, bool fAllowSlow)
c73ba23e 929{
450cbb09 930 CBlockIndex *pindexSlow = NULL;
c73ba23e
PW
931 {
932 LOCK(cs_main);
933 {
934 LOCK(mempool.cs);
935 if (mempool.exists(hash))
936 {
450cbb09 937 txOut = mempool.lookup(hash);
c73ba23e
PW
938 return true;
939 }
940 }
450cbb09
PW
941
942 if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
943 int nHeight = -1;
944 {
ae8bfd12 945 CCoinsViewCache &view = *pcoinsTip;
450cbb09
PW
946 CCoins coins;
947 if (view.GetCoins(hash, coins))
948 nHeight = coins.nHeight;
949 }
950 if (nHeight > 0)
951 pindexSlow = FindBlockByHeight(nHeight);
c73ba23e
PW
952 }
953 }
0a61b0df 954
450cbb09
PW
955 if (pindexSlow) {
956 CBlock block;
957 if (block.ReadFromDisk(pindexSlow)) {
958 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
959 if (tx.GetHash() == hash) {
960 txOut = tx;
961 hashBlock = pindexSlow->GetBlockHash();
962 return true;
963 }
964 }
965 }
966 }
0a61b0df 967
450cbb09
PW
968 return false;
969}
0a61b0df 970
971
972
973
974
975
976//////////////////////////////////////////////////////////////////////////////
977//
978// CBlock and CBlockIndex
979//
980
1be06419
LD
981static CBlockIndex* pblockindexFBBHLast;
982CBlockIndex* FindBlockByHeight(int nHeight)
983{
984 CBlockIndex *pblockindex;
985 if (nHeight < nBestHeight / 2)
986 pblockindex = pindexGenesisBlock;
987 else
988 pblockindex = pindexBest;
989 if (pblockindexFBBHLast && abs(nHeight - pblockindex->nHeight) > abs(nHeight - pblockindexFBBHLast->nHeight))
990 pblockindex = pblockindexFBBHLast;
991 while (pblockindex->nHeight > nHeight)
992 pblockindex = pblockindex->pprev;
993 while (pblockindex->nHeight < nHeight)
994 pblockindex = pblockindex->pnext;
995 pblockindexFBBHLast = pblockindex;
996 return pblockindex;
997}
998
0a61b0df 999bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
1000{
f03304a9 1001 if (!fReadTransactions)
1002 {
1003 *this = pindex->GetBlockHeader();
1004 return true;
1005 }
630fd8dc 1006 if (!ReadFromDisk(pindex->GetBlockPos(), fReadTransactions))
0a61b0df 1007 return false;
1008 if (GetHash() != pindex->GetBlockHash())
1009 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
1010 return true;
1011}
1012
64c7ee7e 1013uint256 static GetOrphanRoot(const CBlock* pblock)
0a61b0df 1014{
1015 // Work back to the first block in the orphan chain
1016 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
1017 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
1018 return pblock->GetHash();
1019}
1020
bde280b9 1021int64 static GetBlockValue(int nHeight, int64 nFees)
0a61b0df 1022{
bde280b9 1023 int64 nSubsidy = 50 * COIN;
0a61b0df 1024
5f2e4b05 1025 // Subsidy is cut in half every 210000 blocks, which will occur approximately every 4 years
0a61b0df 1026 nSubsidy >>= (nHeight / 210000);
1027
1028 return nSubsidy + nFees;
1029}
1030
bde280b9
WL
1031static const int64 nTargetTimespan = 14 * 24 * 60 * 60; // two weeks
1032static const int64 nTargetSpacing = 10 * 60;
1033static const int64 nInterval = nTargetTimespan / nTargetSpacing;
10fd7f66
GA
1034
1035//
1036// minimum amount of work that could possibly be required nTime after
1037// minimum work required was nBase
1038//
bde280b9 1039unsigned int ComputeMinWork(unsigned int nBase, int64 nTime)
10fd7f66 1040{
c52296a7
GA
1041 // Testnet has min-difficulty blocks
1042 // after nTargetSpacing*2 time between blocks:
1043 if (fTestNet && nTime > nTargetSpacing*2)
1044 return bnProofOfWorkLimit.GetCompact();
1045
10fd7f66
GA
1046 CBigNum bnResult;
1047 bnResult.SetCompact(nBase);
1048 while (nTime > 0 && bnResult < bnProofOfWorkLimit)
1049 {
1050 // Maximum 400% adjustment...
1051 bnResult *= 4;
1052 // ... in best-case exactly 4-times-normal target time
1053 nTime -= nTargetTimespan*4;
1054 }
1055 if (bnResult > bnProofOfWorkLimit)
1056 bnResult = bnProofOfWorkLimit;
1057 return bnResult.GetCompact();
1058}
1059
c52296a7 1060unsigned int static GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlock *pblock)
0a61b0df 1061{
c52296a7 1062 unsigned int nProofOfWorkLimit = bnProofOfWorkLimit.GetCompact();
0a61b0df 1063
1064 // Genesis block
1065 if (pindexLast == NULL)
c52296a7 1066 return nProofOfWorkLimit;
0a61b0df 1067
1068 // Only change once per interval
1069 if ((pindexLast->nHeight+1) % nInterval != 0)
c52296a7 1070 {
248bceb3
GA
1071 // Special difficulty rule for testnet:
1072 if (fTestNet)
c52296a7
GA
1073 {
1074 // If the new block's timestamp is more than 2* 10 minutes
1075 // then allow mining of a min-difficulty block.
248bceb3 1076 if (pblock->nTime > pindexLast->nTime + nTargetSpacing*2)
c52296a7
GA
1077 return nProofOfWorkLimit;
1078 else
1079 {
1080 // Return the last non-special-min-difficulty-rules-block
1081 const CBlockIndex* pindex = pindexLast;
1082 while (pindex->pprev && pindex->nHeight % nInterval != 0 && pindex->nBits == nProofOfWorkLimit)
1083 pindex = pindex->pprev;
1084 return pindex->nBits;
1085 }
1086 }
1087
0a61b0df 1088 return pindexLast->nBits;
c52296a7 1089 }
0a61b0df 1090
1091 // Go back by what we want to be 14 days worth of blocks
1092 const CBlockIndex* pindexFirst = pindexLast;
1093 for (int i = 0; pindexFirst && i < nInterval-1; i++)
1094 pindexFirst = pindexFirst->pprev;
1095 assert(pindexFirst);
1096
1097 // Limit adjustment step
bde280b9 1098 int64 nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();
0a61b0df 1099 printf(" nActualTimespan = %"PRI64d" before bounds\n", nActualTimespan);
1100 if (nActualTimespan < nTargetTimespan/4)
1101 nActualTimespan = nTargetTimespan/4;
1102 if (nActualTimespan > nTargetTimespan*4)
1103 nActualTimespan = nTargetTimespan*4;
1104
1105 // Retarget
1106 CBigNum bnNew;
1107 bnNew.SetCompact(pindexLast->nBits);
1108 bnNew *= nActualTimespan;
1109 bnNew /= nTargetTimespan;
1110
1111 if (bnNew > bnProofOfWorkLimit)
1112 bnNew = bnProofOfWorkLimit;
1113
1114 /// debug print
1115 printf("GetNextWorkRequired RETARGET\n");
1116 printf("nTargetTimespan = %"PRI64d" nActualTimespan = %"PRI64d"\n", nTargetTimespan, nActualTimespan);
1117 printf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());
1118 printf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());
1119
1120 return bnNew.GetCompact();
1121}
1122
1123bool CheckProofOfWork(uint256 hash, unsigned int nBits)
1124{
1125 CBigNum bnTarget;
1126 bnTarget.SetCompact(nBits);
1127
1128 // Check range
1129 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
1130 return error("CheckProofOfWork() : nBits below minimum work");
1131
1132 // Check proof of work matches claimed amount
1133 if (hash > bnTarget.getuint256())
1134 return error("CheckProofOfWork() : hash doesn't match nBits");
1135
1136 return true;
1137}
1138
c5aa1b13 1139// Return maximum amount of blocks that other nodes claim to have
d33cc2b5 1140int GetNumBlocksOfPeers()
c5aa1b13 1141{
eb5fff9e 1142 return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
c5aa1b13
WL
1143}
1144
0a61b0df 1145bool IsInitialBlockDownload()
1146{
fe358165 1147 if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
0a61b0df 1148 return true;
bde280b9 1149 static int64 nLastUpdate;
0a61b0df 1150 static CBlockIndex* pindexLastBest;
1151 if (pindexBest != pindexLastBest)
1152 {
1153 pindexLastBest = pindexBest;
1154 nLastUpdate = GetTime();
1155 }
1156 return (GetTime() - nLastUpdate < 10 &&
1157 pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
1158}
1159
64c7ee7e 1160void static InvalidChainFound(CBlockIndex* pindexNew)
0a61b0df 1161{
1162 if (pindexNew->bnChainWork > bnBestInvalidWork)
1163 {
1164 bnBestInvalidWork = pindexNew->bnChainWork;
d979e6e3 1165 pblocktree->WriteBestInvalidWork(bnBestInvalidWork);
ab1b288f 1166 uiInterface.NotifyBlocksChanged();
0a61b0df 1167 }
e69a7979
B
1168 printf("InvalidChainFound: invalid block=%s height=%d work=%s date=%s\n",
1169 pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight,
1170 pindexNew->bnChainWork.ToString().c_str(), DateTimeStrFormat("%x %H:%M:%S",
1171 pindexNew->GetBlockTime()).c_str());
1172 printf("InvalidChainFound: current best=%s height=%d work=%s date=%s\n",
1173 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str(),
1174 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
0a61b0df 1175 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
e6bc9c35 1176 printf("InvalidChainFound: Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.\n");
0a61b0df 1177}
1178
857c61df
PW
1179void static InvalidBlockFound(CBlockIndex *pindex) {
1180 pindex->nStatus |= BLOCK_FAILED_VALID;
d979e6e3 1181 pblocktree->WriteBlockIndex(CDiskBlockIndex(pindex));
857c61df
PW
1182 setBlockIndexValid.erase(pindex);
1183 InvalidChainFound(pindex);
1184 if (pindex->pnext)
1185 ConnectBestBlock(); // reorganise away from the failed block
1186}
1187
1188bool ConnectBestBlock() {
1189 do {
1190 CBlockIndex *pindexNewBest;
1191
1192 {
1193 std::set<CBlockIndex*,CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexValid.rbegin();
1194 if (it == setBlockIndexValid.rend())
1195 return true;
1196 pindexNewBest = *it;
1197 }
1198
1199 if (pindexNewBest == pindexBest)
1200 return true; // nothing to do
1201
1202 // check ancestry
1203 CBlockIndex *pindexTest = pindexNewBest;
1204 std::vector<CBlockIndex*> vAttach;
1205 do {
1206 if (pindexTest->nStatus & BLOCK_FAILED_MASK) {
1207 // mark descendants failed
857c61df
PW
1208 CBlockIndex *pindexFailed = pindexNewBest;
1209 while (pindexTest != pindexFailed) {
1210 pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
1211 setBlockIndexValid.erase(pindexFailed);
d979e6e3 1212 pblocktree->WriteBlockIndex(CDiskBlockIndex(pindexFailed));
857c61df
PW
1213 pindexFailed = pindexFailed->pprev;
1214 }
1215 InvalidChainFound(pindexNewBest);
1216 break;
1217 }
1218
1219 if (pindexBest == NULL || pindexTest->bnChainWork > pindexBest->bnChainWork)
1220 vAttach.push_back(pindexTest);
1221
1222 if (pindexTest->pprev == NULL || pindexTest->pnext != NULL) {
1223 reverse(vAttach.begin(), vAttach.end());
1224 BOOST_FOREACH(CBlockIndex *pindexSwitch, vAttach)
1225 if (!SetBestChain(pindexSwitch))
1226 return false;
1227 return true;
1228 }
1229 pindexTest = pindexTest->pprev;
1230 } while(true);
1231 } while(true);
1232}
1233
0f8cb5db
GA
1234void CBlock::UpdateTime(const CBlockIndex* pindexPrev)
1235{
1236 nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
1237
1238 // Updating time can change work required on testnet:
1239 if (fTestNet)
1240 nBits = GetNextWorkRequired(pindexPrev, this);
1241}
1242
0a61b0df 1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
13c51f20 1253const CTxOut &CTransaction::GetOutputFor(const CTxIn& input, CCoinsViewCache& view)
e679ec96 1254{
13c51f20
PW
1255 const CCoins &coins = view.GetCoins(input.prevout.hash);
1256 assert(coins.IsAvailable(input.prevout.n));
1257 return coins.vout[input.prevout.n];
8d7849b6
GA
1258}
1259
13c51f20 1260int64 CTransaction::GetValueIn(CCoinsViewCache& inputs) const
8d7849b6
GA
1261{
1262 if (IsCoinBase())
1263 return 0;
1264
1265 int64 nResult = 0;
c376ac35 1266 for (unsigned int i = 0; i < vin.size(); i++)
8d7849b6 1267 nResult += GetOutputFor(vin[i], inputs).nValue;
8d7849b6 1268
450cbb09 1269 return nResult;
8d7849b6
GA
1270}
1271
13c51f20 1272unsigned int CTransaction::GetP2SHSigOpCount(CCoinsViewCache& inputs) const
8d7849b6
GA
1273{
1274 if (IsCoinBase())
1275 return 0;
1276
7bd9c3a3 1277 unsigned int nSigOps = 0;
c376ac35 1278 for (unsigned int i = 0; i < vin.size(); i++)
8d7849b6 1279 {
13c51f20 1280 const CTxOut &prevout = GetOutputFor(vin[i], inputs);
137d0685
GA
1281 if (prevout.scriptPubKey.IsPayToScriptHash())
1282 nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig);
8d7849b6
GA
1283 }
1284 return nSigOps;
1285}
1286
13c51f20 1287bool CTransaction::UpdateCoins(CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight, const uint256 &txhash) const
450cbb09 1288{
450cbb09
PW
1289 // mark inputs spent
1290 if (!IsCoinBase()) {
1291 BOOST_FOREACH(const CTxIn &txin, vin) {
13c51f20 1292 CCoins &coins = inputs.GetCoins(txin.prevout.hash);
450cbb09
PW
1293 CTxInUndo undo;
1294 if (!coins.Spend(txin.prevout, undo))
1295 return error("UpdateCoins() : cannot spend input");
1296 txundo.vprevout.push_back(undo);
450cbb09
PW
1297 }
1298 }
1299
1300 // add outputs
64dd46fd 1301 if (!inputs.SetCoins(txhash, CCoins(*this, nHeight)))
450cbb09
PW
1302 return error("UpdateCoins() : cannot update output");
1303
1304 return true;
1305}
1306
13c51f20 1307bool CTransaction::HaveInputs(CCoinsViewCache &inputs) const
450cbb09 1308{
729b1806 1309 if (!IsCoinBase()) {
450cbb09
PW
1310 // first check whether information about the prevout hash is available
1311 for (unsigned int i = 0; i < vin.size(); i++) {
1312 const COutPoint &prevout = vin[i].prevout;
1313 if (!inputs.HaveCoins(prevout.hash))
1314 return false;
1315 }
1316
1317 // then check whether the actual outputs are available
1318 for (unsigned int i = 0; i < vin.size(); i++) {
1319 const COutPoint &prevout = vin[i].prevout;
13c51f20 1320 const CCoins &coins = inputs.GetCoins(prevout.hash);
450cbb09
PW
1321 if (!coins.IsAvailable(prevout.n))
1322 return false;
1323 }
1324 }
1325 return true;
1326}
1327
13c51f20 1328bool CTransaction::CheckInputs(CCoinsViewCache &inputs, enum CheckSig_mode csmode, bool fStrictPayToScriptHash, bool fStrictEncodings) const
0a61b0df 1329{
0a61b0df 1330 if (!IsCoinBase())
1331 {
13c51f20
PW
1332 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1333 // for an attacker to attempt to split the network.
1334 if (!HaveInputs(inputs))
1335 return error("CheckInputs() : %s inputs unavailable", GetHash().ToString().substr(0,10).c_str());
1336
56424040
PW
1337 // While checking, GetBestBlock() refers to the parent block.
1338 // This is also true for mempool checks.
1339 int nSpendHeight = inputs.GetBestBlock()->nHeight + 1;
bde280b9 1340 int64 nValueIn = 0;
8d7849b6 1341 int64 nFees = 0;
c376ac35 1342 for (unsigned int i = 0; i < vin.size(); i++)
0a61b0df 1343 {
450cbb09 1344 const COutPoint &prevout = vin[i].prevout;
13c51f20 1345 const CCoins &coins = inputs.GetCoins(prevout.hash);
0a61b0df 1346
1347 // If prev is coinbase, check that it's matured
450cbb09 1348 if (coins.IsCoinBase()) {
56424040
PW
1349 if (nSpendHeight - coins.nHeight < COINBASE_MATURITY)
1350 return error("CheckInputs() : tried to spend coinbase at depth %d", nSpendHeight - coins.nHeight);
450cbb09 1351 }
0a61b0df 1352
4add41a2 1353 // Check for negative or overflow input values
450cbb09
PW
1354 nValueIn += coins.vout[prevout.n].nValue;
1355 if (!MoneyRange(coins.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1356 return DoS(100, error("CheckInputs() : txin values out of range"));
4add41a2
GA
1357
1358 }
450cbb09
PW
1359
1360 if (nValueIn < GetValueOut())
1361 return DoS(100, error("ChecktInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
1362
1363 // Tally transaction fees
1364 int64 nTxFee = nValueIn - GetValueOut();
1365 if (nTxFee < 0)
1366 return DoS(100, error("CheckInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
1367 nFees += nTxFee;
1368 if (!MoneyRange(nFees))
1369 return DoS(100, error("CheckInputs() : nFees out of range"));
1370
4add41a2
GA
1371 // The first loop above does all the inexpensive checks.
1372 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1373 // Helps prevent CPU exhaustion attacks.
4add41a2 1374
450cbb09 1375 // Skip ECDSA signature verification when connecting blocks
729b1806 1376 // before the last block chain checkpoint. This is safe because block merkle hashes are
450cbb09 1377 // still computed and checked, and any change will be caught at the next checkpoint.
729b1806 1378 if (csmode == CS_ALWAYS ||
450cbb09
PW
1379 (csmode == CS_AFTER_CHECKPOINT && inputs.GetBestBlock()->nHeight >= Checkpoints::GetTotalBlocksEstimate())) {
1380 for (unsigned int i = 0; i < vin.size(); i++) {
1381 const COutPoint &prevout = vin[i].prevout;
13c51f20 1382 const CCoins &coins = inputs.GetCoins(prevout.hash);
8d7849b6 1383
b14bd4df 1384 // Verify signature
450cbb09 1385 if (!VerifySignature(coins, *this, i, fStrictPayToScriptHash, fStrictEncodings, 0)) {
db9f2e01
PW
1386 // only during transition phase for P2SH: do not invoke anti-DoS code for
1387 // potentially old clients relaying bad P2SH transactions
450cbb09
PW
1388 if (fStrictPayToScriptHash && VerifySignature(coins, *this, i, false, fStrictEncodings, 0))
1389 return error("CheckInputs() : %s P2SH VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
db9f2e01 1390
450cbb09 1391 return DoS(100,error("CheckInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
db9f2e01 1392 }
2a45a494 1393 }
0a61b0df 1394 }
0a61b0df 1395 }
1396
0a61b0df 1397 return true;
1398}
1399
1400
450cbb09 1401bool CTransaction::ClientCheckInputs() const
0a61b0df 1402{
1403 if (IsCoinBase())
1404 return false;
1405
1406 // Take over previous transactions' spent pointers
0a61b0df 1407 {
235507ae 1408 LOCK(mempool.cs);
bde280b9 1409 int64 nValueIn = 0;
c376ac35 1410 for (unsigned int i = 0; i < vin.size(); i++)
0a61b0df 1411 {
1412 // Get prev tx from single transactions in memory
1413 COutPoint prevout = vin[i].prevout;
ca4c4c53 1414 if (!mempool.exists(prevout.hash))
0a61b0df 1415 return false;
ca4c4c53 1416 CTransaction& txPrev = mempool.lookup(prevout.hash);
0a61b0df 1417
1418 if (prevout.n >= txPrev.vout.size())
1419 return false;
1420
1421 // Verify signature
450cbb09 1422 if (!VerifySignature(CCoins(txPrev, -1), *this, i, true, false, 0))
0a61b0df 1423 return error("ConnectInputs() : VerifySignature failed");
1424
235507ae
JG
1425 ///// this is redundant with the mempool.mapNextTx stuff,
1426 ///// not sure which I want to get rid of
0a61b0df 1427 ///// this has to go away now that posNext is gone
1428 // // Check for conflicts
1429 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1430 // return error("ConnectInputs() : prev tx already used");
1431 //
1432 // // Flag outpoints as used
1433 // txPrev.vout[prevout.n].posNext = posThisTx;
1434
1435 nValueIn += txPrev.vout[prevout.n].nValue;
f1e1fb4b 1436
1437 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1438 return error("ClientConnectInputs() : txin values out of range");
0a61b0df 1439 }
1440 if (GetValueOut() > nValueIn)
1441 return false;
1442 }
1443
1444 return true;
1445}
1446
1447
1448
1449
13c51f20 1450bool CBlock::DisconnectBlock(CBlockIndex *pindex, CCoinsViewCache &view)
0a61b0df 1451{
450cbb09 1452 assert(pindex == view.GetBestBlock());
0a61b0df 1453
450cbb09 1454 CBlockUndo blockUndo;
0a61b0df 1455 {
450cbb09
PW
1456 CDiskBlockPos pos = pindex->GetUndoPos();
1457 if (pos.IsNull())
1458 return error("DisconnectBlock() : no undo data available");
1459 FILE *file = OpenUndoFile(pos, true);
1460 if (file == NULL)
1461 return error("DisconnectBlock() : undo file not available");
1462 CAutoFile fileUndo(file, SER_DISK, CLIENT_VERSION);
1463 fileUndo >> blockUndo;
0a61b0df 1464 }
1465
450cbb09
PW
1466 assert(blockUndo.vtxundo.size() + 1 == vtx.size());
1467
1468 // undo transactions in reverse order
1469 for (int i = vtx.size() - 1; i >= 0; i--) {
1470 const CTransaction &tx = vtx[i];
1471 uint256 hash = tx.GetHash();
1472
1473 // check that all outputs are available
13c51f20 1474 if (!view.HaveCoins(hash))
450cbb09 1475 return error("DisconnectBlock() : outputs still spent? database corrupted");
13c51f20 1476 CCoins &outs = view.GetCoins(hash);
450cbb09
PW
1477
1478 CCoins outsBlock = CCoins(tx, pindex->nHeight);
1479 if (outs != outsBlock)
1480 return error("DisconnectBlock() : added transaction mismatch? database corrupted");
1481
1482 // remove outputs
13c51f20 1483 outs = CCoins();
450cbb09
PW
1484
1485 // restore inputs
1486 if (i > 0) { // not coinbases
1487 const CTxUndo &txundo = blockUndo.vtxundo[i-1];
1488 assert(txundo.vprevout.size() == tx.vin.size());
1489 for (unsigned int j = tx.vin.size(); j-- > 0;) {
1490 const COutPoint &out = tx.vin[j].prevout;
1491 const CTxInUndo &undo = txundo.vprevout[j];
1492 CCoins coins;
1493 view.GetCoins(out.hash, coins); // this can fail if the prevout was already entirely spent
1494 if (coins.IsPruned()) {
1495 if (undo.nHeight == 0)
1496 return error("DisconnectBlock() : undo data doesn't contain tx metadata? database corrupted");
1497 coins.fCoinBase = undo.fCoinBase;
1498 coins.nHeight = undo.nHeight;
1499 coins.nVersion = undo.nVersion;
1500 } else {
1501 if (undo.nHeight != 0)
1502 return error("DisconnectBlock() : undo data contains unneeded tx metadata? database corrupted");
1503 }
1504 if (coins.IsAvailable(out.n))
1505 return error("DisconnectBlock() : prevout output not spent? database corrupted");
1506 if (coins.vout.size() < out.n+1)
1507 coins.vout.resize(out.n+1);
1508 coins.vout[out.n] = undo.txout;
1509 if (!view.SetCoins(out.hash, coins))
1510 return error("DisconnectBlock() : cannot restore coin inputs");
1511 }
1512 }
1513 }
1514
1515 // move best block pointer to prevout block
1516 view.SetBestBlock(pindex->pprev);
1517
0a61b0df 1518 return true;
1519}
1520
44d40f26
PW
1521void static FlushBlockFile()
1522{
1523 LOCK(cs_LastBlockFile);
1524
1525 CDiskBlockPos posOld;
1526 posOld.nFile = nLastBlockFile;
1527 posOld.nPos = 0;
1528
1529 FILE *fileOld = OpenBlockFile(posOld);
1530 FileCommit(fileOld);
1531 fclose(fileOld);
1532
1533 fileOld = OpenUndoFile(posOld);
1534 FileCommit(fileOld);
1535 fclose(fileOld);
1536}
1537
d979e6e3 1538bool FindUndoPos(int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
5382bcf8 1539
13c51f20 1540bool CBlock::ConnectBlock(CBlockIndex* pindex, CCoinsViewCache &view, bool fJustCheck)
0a61b0df 1541{
1542 // Check it again in case a previous version let a bad block in
3cd01fdf 1543 if (!CheckBlock(!fJustCheck, !fJustCheck))
0a61b0df 1544 return false;
1545
450cbb09
PW
1546 // verify that the view's current state corresponds to the previous block
1547 assert(pindex->pprev == view.GetBestBlock());
1548
a206b0ea
PW
1549 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1550 // unless those are already completely spent.
1551 // If such overwrites are allowed, coinbases and transactions depending upon those
1552 // can be duplicated to remove the ability to spend the first instance -- even after
1553 // being sent to another address.
1554 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1555 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
b49f1398 1556 // already refuses previously-known transaction ids entirely.
ab91bf39
GM
1557 // This rule was originally applied all blocks whose timestamp was after March 15, 2012, 0:00 UTC.
1558 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1559 // two in the chain that violate it. This prevents exploiting the issue against nodes in their
1560 // initial block download.
1561 bool fEnforceBIP30 = !((pindex->nHeight==91842 && pindex->GetBlockHash() == uint256("0x00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")) ||
1562 (pindex->nHeight==91880 && pindex->GetBlockHash() == uint256("0x00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721")));
450cbb09 1563 if (fEnforceBIP30) {
64dd46fd
PW
1564 for (unsigned int i=0; i<vtx.size(); i++) {
1565 uint256 hash = GetTxHash(i);
13c51f20 1566 if (view.HaveCoins(hash) && !view.GetCoins(hash).IsPruned())
450cbb09
PW
1567 return error("ConnectBlock() : tried to overwrite transaction");
1568 }
1569 }
a206b0ea 1570
e6332751
GM
1571 // BIP16 didn't become active until Apr 1 2012
1572 int64 nBIP16SwitchTime = 1333238400;
8f188ece 1573 bool fStrictPayToScriptHash = (pindex->nTime >= nBIP16SwitchTime);
137d0685 1574
8adf48dc
PW
1575 CBlockUndo blockundo;
1576
bde280b9 1577 int64 nFees = 0;
7bd9c3a3 1578 unsigned int nSigOps = 0;
64dd46fd 1579 for (unsigned int i=0; i<vtx.size(); i++)
0a61b0df 1580 {
64dd46fd
PW
1581 const CTransaction &tx = vtx[i];
1582
137d0685
GA
1583 nSigOps += tx.GetLegacySigOpCount();
1584 if (nSigOps > MAX_BLOCK_SIGOPS)
1585 return DoS(100, error("ConnectBlock() : too many sigops"));
1586
8d7849b6
GA
1587 if (!tx.IsCoinBase())
1588 {
450cbb09
PW
1589 if (!tx.HaveInputs(view))
1590 return DoS(100, error("ConnectBlock() : inputs missing/spent"));
922e8e29 1591
137d0685
GA
1592 if (fStrictPayToScriptHash)
1593 {
1594 // Add in sigops done by pay-to-script-hash inputs;
1595 // this is to prevent a "rogue miner" from creating
1596 // an incredibly-expensive-to-validate block.
450cbb09 1597 nSigOps += tx.GetP2SHSigOpCount(view);
137d0685 1598 if (nSigOps > MAX_BLOCK_SIGOPS)
450cbb09 1599 return DoS(100, error("ConnectBlock() : too many sigops"));
137d0685 1600 }
922e8e29 1601
450cbb09 1602 nFees += tx.GetValueIn(view)-tx.GetValueOut();
8adf48dc 1603
450cbb09 1604 if (!tx.CheckInputs(view, CS_AFTER_CHECKPOINT, fStrictPayToScriptHash, false))
40634605 1605 return false;
8d7849b6
GA
1606 }
1607
450cbb09 1608 CTxUndo txundo;
64dd46fd 1609 if (!tx.UpdateCoins(view, txundo, pindex->nHeight, GetTxHash(i)))
450cbb09
PW
1610 return error("ConnectBlock() : UpdateInputs failed");
1611 if (!tx.IsCoinBase())
1612 blockundo.vtxundo.push_back(txundo);
0a61b0df 1613 }
e679ec96 1614
9e957fb3
PW
1615 if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))
1616 return false;
1617
3cd01fdf
LD
1618 if (fJustCheck)
1619 return true;
1620
5382bcf8 1621 // Write undo information to disk
857c61df 1622 if (pindex->GetUndoPos().IsNull() || (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS)
5382bcf8 1623 {
857c61df
PW
1624 if (pindex->GetUndoPos().IsNull()) {
1625 CDiskBlockPos pos;
d979e6e3 1626 if (!FindUndoPos(pindex->nFile, pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 8))
857c61df
PW
1627 return error("ConnectBlock() : FindUndoPos failed");
1628 if (!blockundo.WriteToDisk(pos))
1629 return error("ConnectBlock() : CBlockUndo::WriteToDisk failed");
1630
1631 // update nUndoPos in block index
1632 pindex->nUndoPos = pos.nPos;
1633 pindex->nStatus |= BLOCK_HAVE_UNDO;
1634 }
1635
1636 pindex->nStatus = (pindex->nStatus & ~BLOCK_VALID_MASK) | BLOCK_VALID_SCRIPTS;
1637
450cbb09 1638 CDiskBlockIndex blockindex(pindex);
d979e6e3 1639 if (!pblocktree->WriteBlockIndex(blockindex))
b22c8842 1640 return error("ConnectBlock() : WriteBlockIndex failed");
0a61b0df 1641 }
1642
729b1806 1643 // add this block to the view's block chain
450cbb09
PW
1644 if (!view.SetBestBlock(pindex))
1645 return false;
1646
0a61b0df 1647 // Watch for transactions paying to me
64dd46fd
PW
1648 for (unsigned int i=0; i<vtx.size(); i++)
1649 SyncWithWallets(GetTxHash(i), vtx[i], this, true);
0a61b0df 1650
1651 return true;
1652}
1653
857c61df 1654bool SetBestChain(CBlockIndex* pindexNew)
0a61b0df 1655{
ae8bfd12 1656 CCoinsViewCache &view = *pcoinsTip;
450cbb09
PW
1657
1658 // special case for attaching the genesis block
1659 // note that no ConnectBlock is called, so its coinbase output is non-spendable
1660 if (pindexGenesisBlock == NULL && pindexNew->GetBlockHash() == hashGenesisBlock)
1661 {
ae8bfd12
PW
1662 view.SetBestBlock(pindexNew);
1663 if (!view.Flush())
1664 return false;
450cbb09
PW
1665 pindexGenesisBlock = pindexNew;
1666 pindexBest = pindexNew;
1667 hashBestChain = pindexNew->GetBlockHash();
1668 nBestHeight = pindexBest->nHeight;
1669 bnBestChainWork = pindexNew->bnChainWork;
1670 return true;
1671 }
1672
450cbb09
PW
1673 // Find the fork (typically, there is none)
1674 CBlockIndex* pfork = view.GetBestBlock();
0a61b0df 1675 CBlockIndex* plonger = pindexNew;
1676 while (pfork != plonger)
1677 {
1678 while (plonger->nHeight > pfork->nHeight)
1679 if (!(plonger = plonger->pprev))
450cbb09 1680 return error("SetBestChain() : plonger->pprev is null");
0a61b0df 1681 if (pfork == plonger)
1682 break;
1683 if (!(pfork = pfork->pprev))
450cbb09 1684 return error("SetBestChain() : pfork->pprev is null");
0a61b0df 1685 }
1686
450cbb09 1687 // List of what to disconnect (typically nothing)
0a61b0df 1688 vector<CBlockIndex*> vDisconnect;
450cbb09 1689 for (CBlockIndex* pindex = view.GetBestBlock(); pindex != pfork; pindex = pindex->pprev)
0a61b0df 1690 vDisconnect.push_back(pindex);
1691
450cbb09 1692 // List of what to connect (typically only pindexNew)
0a61b0df 1693 vector<CBlockIndex*> vConnect;
1694 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1695 vConnect.push_back(pindex);
1696 reverse(vConnect.begin(), vConnect.end());
1697
450cbb09
PW
1698 if (vDisconnect.size() > 0) {
1699 printf("REORGANIZE: Disconnect %"PRIszu" blocks; %s..%s\n", vDisconnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexBest->GetBlockHash().ToString().substr(0,20).c_str());
1700 printf("REORGANIZE: Connect %"PRIszu" blocks; %s..%s\n", vConnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->GetBlockHash().ToString().substr(0,20).c_str());
1701 }
a1a0469f 1702
0a61b0df 1703 // Disconnect shorter branch
1704 vector<CTransaction> vResurrect;
450cbb09 1705 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect) {
0a61b0df 1706 CBlock block;
1707 if (!block.ReadFromDisk(pindex))
450cbb09 1708 return error("SetBestBlock() : ReadFromDisk for disconnect failed");
ae8bfd12
PW
1709 CCoinsViewCache viewTemp(view, true);
1710 if (!block.DisconnectBlock(pindex, viewTemp))
450cbb09 1711 return error("SetBestBlock() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
ae8bfd12
PW
1712 if (!viewTemp.Flush())
1713 return error("SetBestBlock() : Cache flush failed after disconnect");
0a61b0df 1714
1715 // Queue memory transactions to resurrect
223b6f1b 1716 BOOST_FOREACH(const CTransaction& tx, block.vtx)
0a61b0df 1717 if (!tx.IsCoinBase())
1718 vResurrect.push_back(tx);
1719 }
1720
1721 // Connect longer branch
1722 vector<CTransaction> vDelete;
450cbb09 1723 BOOST_FOREACH(CBlockIndex *pindex, vConnect) {
0a61b0df 1724 CBlock block;
857c61df
PW
1725 if (!block.ReadFromDisk(pindex))
1726 return error("SetBestBlock() : ReadFromDisk for connect failed");
ae8bfd12 1727 CCoinsViewCache viewTemp(view, true);
857c61df 1728 if (!block.ConnectBlock(pindex, viewTemp)) {
450cbb09 1729 InvalidChainFound(pindexNew);
857c61df 1730 InvalidBlockFound(pindex);
450cbb09 1731 return error("SetBestBlock() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
0a61b0df 1732 }
ae8bfd12
PW
1733 if (!viewTemp.Flush())
1734 return error("SetBestBlock() : Cache flush failed after connect");
0a61b0df 1735
1736 // Queue memory transactions to delete
857c61df 1737 BOOST_FOREACH(const CTransaction& tx, block.vtx)
0a61b0df 1738 vDelete.push_back(tx);
1739 }
0a61b0df 1740
b22c8842 1741 // Make sure it's successfully written to disk before changing memory structure
ae8bfd12 1742 bool fIsInitialDownload = IsInitialBlockDownload();
44d40f26
PW
1743 if (!fIsInitialDownload || view.GetCacheSize()>5000) {
1744 FlushBlockFile();
2d8a4829 1745 pblocktree->Sync();
ae8bfd12
PW
1746 if (!view.Flush())
1747 return false;
44d40f26 1748 }
450cbb09
PW
1749
1750 // At this point, all changes have been done to the database.
1751 // Proceed by updating the memory structures.
0a61b0df 1752
1753 // Disconnect shorter branch
223b6f1b 1754 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
0a61b0df 1755 if (pindex->pprev)
1756 pindex->pprev->pnext = NULL;
1757
1758 // Connect longer branch
223b6f1b 1759 BOOST_FOREACH(CBlockIndex* pindex, vConnect)
0a61b0df 1760 if (pindex->pprev)
1761 pindex->pprev->pnext = pindex;
1762
1763 // Resurrect memory transactions that were in the disconnected branch
223b6f1b 1764 BOOST_FOREACH(CTransaction& tx, vResurrect)
ae8bfd12 1765 tx.AcceptToMemoryPool(false);
0a61b0df 1766
1767 // Delete redundant memory transactions that are in the connected branch
223b6f1b 1768 BOOST_FOREACH(CTransaction& tx, vDelete)
8e45ed66 1769 mempool.remove(tx);
0a61b0df 1770
6a76c60e 1771 // Update best block in wallet (so we can detect restored wallets)
d237f62c 1772 if (!fIsInitialDownload)
6a76c60e 1773 {
6a76c60e 1774 const CBlockLocator locator(pindexNew);
64c7ee7e 1775 ::SetBestChain(locator);
6a76c60e
PW
1776 }
1777
0a61b0df 1778 // New best block
450cbb09 1779 hashBestChain = pindexNew->GetBlockHash();
0a61b0df 1780 pindexBest = pindexNew;
1be06419 1781 pblockindexFBBHLast = NULL;
0a61b0df 1782 nBestHeight = pindexBest->nHeight;
1783 bnBestChainWork = pindexNew->bnChainWork;
1784 nTimeBestReceived = GetTime();
1785 nTransactionsUpdated++;
857c61df
PW
1786 printf("SetBestChain: new best=%s height=%d work=%s tx=%lu date=%s\n",
1787 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str(), (unsigned long)pindexNew->nChainTx,
e69a7979 1788 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
0a61b0df 1789
2a919e39
GA
1790 // Check the version of the last 100 blocks to see if we need to upgrade:
1791 if (!fIsInitialDownload)
1792 {
1793 int nUpgraded = 0;
1794 const CBlockIndex* pindex = pindexBest;
1795 for (int i = 0; i < 100 && pindex != NULL; i++)
1796 {
1797 if (pindex->nVersion > CBlock::CURRENT_VERSION)
1798 ++nUpgraded;
1799 pindex = pindex->pprev;
1800 }
1801 if (nUpgraded > 0)
1802 printf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, CBlock::CURRENT_VERSION);
1803 if (nUpgraded > 100/2)
1804 // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
e6bc9c35 1805 strMiscWarning = _("Warning: This version is obsolete, upgrade required!");
2a919e39
GA
1806 }
1807
d237f62c
GA
1808 std::string strCmd = GetArg("-blocknotify", "");
1809
1810 if (!fIsInitialDownload && !strCmd.empty())
1811 {
1812 boost::replace_all(strCmd, "%s", hashBestChain.GetHex());
1813 boost::thread t(runCommand, strCmd); // thread runs free
1814 }
1815
0a61b0df 1816 return true;
1817}
1818
1819
630fd8dc 1820bool CBlock::AddToBlockIndex(const CDiskBlockPos &pos)
0a61b0df 1821{
1822 // Check for duplicate
1823 uint256 hash = GetHash();
1824 if (mapBlockIndex.count(hash))
1825 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
1826
1827 // Construct new block index object
630fd8dc 1828 CBlockIndex* pindexNew = new CBlockIndex(*this);
0a61b0df 1829 if (!pindexNew)
1830 return error("AddToBlockIndex() : new CBlockIndex failed");
1831 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
1832 pindexNew->phashBlock = &((*mi).first);
1833 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
1834 if (miPrev != mapBlockIndex.end())
1835 {
1836 pindexNew->pprev = (*miPrev).second;
1837 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
1838 }
857c61df 1839 pindexNew->nTx = vtx.size();
0a61b0df 1840 pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork();
857c61df
PW
1841 pindexNew->nChainTx = (pindexNew->pprev ? pindexNew->pprev->nChainTx : 0) + pindexNew->nTx;
1842 pindexNew->nFile = pos.nFile;
1843 pindexNew->nDataPos = pos.nPos;
5382bcf8 1844 pindexNew->nUndoPos = 0;
857c61df
PW
1845 pindexNew->nStatus = BLOCK_VALID_TRANSACTIONS | BLOCK_HAVE_DATA;
1846 setBlockIndexValid.insert(pindexNew);
0a61b0df 1847
d979e6e3 1848 pblocktree->WriteBlockIndex(CDiskBlockIndex(pindexNew));
0a61b0df 1849
857c61df
PW
1850 // New best?
1851 if (!ConnectBestBlock())
ae8bfd12 1852 return false;
0a61b0df 1853
1854 if (pindexNew == pindexBest)
1855 {
1856 // Notify UI to display prev block's coinbase if it was ours
1857 static uint256 hashPrevBestCoinBase;
64c7ee7e 1858 UpdatedTransaction(hashPrevBestCoinBase);
64dd46fd 1859 hashPrevBestCoinBase = GetTxHash(0);
0a61b0df 1860 }
1861
d979e6e3
PW
1862 pblocktree->Flush();
1863
ab1b288f 1864 uiInterface.NotifyBlocksChanged();
0a61b0df 1865 return true;
1866}
1867
1868
d979e6e3 1869bool FindBlockPos(CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64 nTime)
5382bcf8
PW
1870{
1871 bool fUpdatedLast = false;
1872
1873 LOCK(cs_LastBlockFile);
1874
1875 while (infoLastBlockFile.nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
1876 printf("Leaving block file %i: %s\n", nLastBlockFile, infoLastBlockFile.ToString().c_str());
44d40f26 1877 FlushBlockFile();
5382bcf8
PW
1878 nLastBlockFile++;
1879 infoLastBlockFile.SetNull();
d979e6e3 1880 pblocktree->ReadBlockFileInfo(nLastBlockFile, infoLastBlockFile); // check whether data for the new file somehow already exist; can fail just fine
5382bcf8
PW
1881 fUpdatedLast = true;
1882 }
1883
1884 pos.nFile = nLastBlockFile;
1885 pos.nPos = infoLastBlockFile.nSize;
1886 infoLastBlockFile.nSize += nAddSize;
1887 infoLastBlockFile.AddBlock(nHeight, nTime);
1888
bba89aa8
PW
1889 unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
1890 unsigned int nNewChunks = (infoLastBlockFile.nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
1891 if (nNewChunks > nOldChunks) {
1892 FILE *file = OpenBlockFile(pos);
1893 if (file) {
1894 printf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
1895 AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
1896 }
1897 fclose(file);
1898 }
1899
d979e6e3 1900 if (!pblocktree->WriteBlockFileInfo(nLastBlockFile, infoLastBlockFile))
5382bcf8
PW
1901 return error("FindBlockPos() : cannot write updated block info");
1902 if (fUpdatedLast)
d979e6e3 1903 pblocktree->WriteLastBlockFile(nLastBlockFile);
5382bcf8
PW
1904
1905 return true;
1906}
1907
d979e6e3 1908bool FindUndoPos(int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
5382bcf8
PW
1909{
1910 pos.nFile = nFile;
1911
1912 LOCK(cs_LastBlockFile);
1913
bba89aa8 1914 unsigned int nNewSize;
5382bcf8
PW
1915 if (nFile == nLastBlockFile) {
1916 pos.nPos = infoLastBlockFile.nUndoSize;
bba89aa8 1917 nNewSize = (infoLastBlockFile.nUndoSize += nAddSize);
d979e6e3 1918 if (!pblocktree->WriteBlockFileInfo(nLastBlockFile, infoLastBlockFile))
5382bcf8 1919 return error("FindUndoPos() : cannot write updated block info");
bba89aa8
PW
1920 } else {
1921 CBlockFileInfo info;
d979e6e3 1922 if (!pblocktree->ReadBlockFileInfo(nFile, info))
bba89aa8
PW
1923 return error("FindUndoPos() : cannot read block info");
1924 pos.nPos = info.nUndoSize;
1925 nNewSize = (info.nUndoSize += nAddSize);
d979e6e3 1926 if (!pblocktree->WriteBlockFileInfo(nFile, info))
bba89aa8
PW
1927 return error("FindUndoPos() : cannot write updated block info");
1928 }
1929
1930 unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
1931 unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
1932 if (nNewChunks > nOldChunks) {
1933 FILE *file = OpenUndoFile(pos);
1934 if (file) {
1935 printf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
1936 AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
1937 }
1938 fclose(file);
5382bcf8
PW
1939 }
1940
5382bcf8
PW
1941 return true;
1942}
1943
0a61b0df 1944
3cd01fdf 1945bool CBlock::CheckBlock(bool fCheckPOW, bool fCheckMerkleRoot) const
0a61b0df 1946{
1947 // These are checks that are independent of context
1948 // that can be verified before saving an orphan block.
1949
1950 // Size limits
6b6aaa16 1951 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
3e52aaf2 1952 return DoS(100, error("CheckBlock() : size limits failed"));
0a61b0df 1953
172f0060 1954 // Check proof of work matches claimed amount
3cd01fdf 1955 if (fCheckPOW && !CheckProofOfWork(GetHash(), nBits))
3e52aaf2 1956 return DoS(50, error("CheckBlock() : proof of work failed"));
172f0060 1957
0a61b0df 1958 // Check timestamp
1959 if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
1960 return error("CheckBlock() : block timestamp too far in the future");
1961
1962 // First transaction must be coinbase, the rest must not be
1963 if (vtx.empty() || !vtx[0].IsCoinBase())
3e52aaf2 1964 return DoS(100, error("CheckBlock() : first tx is not coinbase"));
c376ac35 1965 for (unsigned int i = 1; i < vtx.size(); i++)
0a61b0df 1966 if (vtx[i].IsCoinBase())
3e52aaf2 1967 return DoS(100, error("CheckBlock() : more than one coinbase"));
0a61b0df 1968
1969 // Check transactions
223b6f1b 1970 BOOST_FOREACH(const CTransaction& tx, vtx)
0a61b0df 1971 if (!tx.CheckTransaction())
3e52aaf2 1972 return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
0a61b0df 1973
c2ed184f
PW
1974 // Build the merkle tree already. We need it anyway later, and it makes the
1975 // block cache the transaction hashes, which means they don't need to be
1976 // recalculated many times during this block's validation.
1977 BuildMerkleTree();
1978
be8651dd
GA
1979 // Check for duplicate txids. This is caught by ConnectInputs(),
1980 // but catching it earlier avoids a potential DoS attack:
1981 set<uint256> uniqueTx;
64dd46fd
PW
1982 for (unsigned int i=0; i<vtx.size(); i++) {
1983 uniqueTx.insert(GetTxHash(i));
be8651dd
GA
1984 }
1985 if (uniqueTx.size() != vtx.size())
1986 return DoS(100, error("CheckBlock() : duplicate transaction"));
1987
7bd9c3a3 1988 unsigned int nSigOps = 0;
e679ec96
GA
1989 BOOST_FOREACH(const CTransaction& tx, vtx)
1990 {
922e8e29 1991 nSigOps += tx.GetLegacySigOpCount();
e679ec96
GA
1992 }
1993 if (nSigOps > MAX_BLOCK_SIGOPS)
3e52aaf2 1994 return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
0a61b0df 1995
814efd6f 1996 // Check merkle root
3cd01fdf 1997 if (fCheckMerkleRoot && hashMerkleRoot != BuildMerkleTree())
3e52aaf2 1998 return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
0a61b0df 1999
2000 return true;
2001}
2002
2003bool CBlock::AcceptBlock()
2004{
2005 // Check for duplicate
2006 uint256 hash = GetHash();
2007 if (mapBlockIndex.count(hash))
2008 return error("AcceptBlock() : block already in mapBlockIndex");
2009
2010 // Get prev block index
2011 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
2012 if (mi == mapBlockIndex.end())
3e52aaf2 2013 return DoS(10, error("AcceptBlock() : prev block not found"));
0a61b0df 2014 CBlockIndex* pindexPrev = (*mi).second;
f1e1fb4b 2015 int nHeight = pindexPrev->nHeight+1;
2016
172f0060 2017 // Check proof of work
c52296a7 2018 if (nBits != GetNextWorkRequired(pindexPrev, this))
3e52aaf2 2019 return DoS(100, error("AcceptBlock() : incorrect proof of work"));
0a61b0df 2020
2021 // Check timestamp against prev
2022 if (GetBlockTime() <= pindexPrev->GetMedianTimePast())
2023 return error("AcceptBlock() : block's timestamp is too early");
2024
2025 // Check that all transactions are finalized
223b6f1b 2026 BOOST_FOREACH(const CTransaction& tx, vtx)
f1e1fb4b 2027 if (!tx.IsFinal(nHeight, GetBlockTime()))
3e52aaf2 2028 return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
0a61b0df 2029
0a61b0df 2030 // Check that the block chain matches the known block chain up to a checkpoint
eb5fff9e 2031 if (!Checkpoints::CheckBlock(nHeight, hash))
814efd6f 2032 return DoS(100, error("AcceptBlock() : rejected by checkpoint lock-in at %d", nHeight));
0a61b0df 2033
d18f2fd9
GA
2034 // Reject block.nVersion=1 blocks when 95% (75% on testnet) of the network has upgraded:
2035 if (nVersion < 2)
2036 {
2037 if ((!fTestNet && CBlockIndex::IsSuperMajority(2, pindexPrev, 950, 1000)) ||
2038 (fTestNet && CBlockIndex::IsSuperMajority(2, pindexPrev, 75, 100)))
2039 {
2040 return error("AcceptBlock() : rejected nVersion=1 block");
2041 }
2042 }
de237cbf 2043 // Enforce block.nVersion=2 rule that the coinbase starts with serialized block height
d18f2fd9 2044 if (nVersion >= 2)
de237cbf
GA
2045 {
2046 // if 750 of the last 1,000 blocks are version 2 or greater (51/100 if testnet):
2047 if ((!fTestNet && CBlockIndex::IsSuperMajority(2, pindexPrev, 750, 1000)) ||
2048 (fTestNet && CBlockIndex::IsSuperMajority(2, pindexPrev, 51, 100)))
2049 {
2050 CScript expect = CScript() << nHeight;
2051 if (!std::equal(expect.begin(), expect.end(), vtx[0].vin[0].scriptSig.begin()))
2052 return DoS(100, error("AcceptBlock() : block height mismatch in coinbase"));
2053 }
2054 }
2055
0a61b0df 2056 // Write block to history file
5382bcf8 2057 unsigned int nBlockSize = ::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION);
6b6aaa16 2058 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION)))
0a61b0df 2059 return error("AcceptBlock() : out of disk space");
5382bcf8 2060 CDiskBlockPos blockPos;
d979e6e3
PW
2061 if (!FindBlockPos(blockPos, nBlockSize+8, nHeight, nTime))
2062 return error("AcceptBlock() : FindBlockPos failed");
630fd8dc 2063 if (!WriteToDisk(blockPos))
0a61b0df 2064 return error("AcceptBlock() : WriteToDisk failed");
630fd8dc 2065 if (!AddToBlockIndex(blockPos))
0a61b0df 2066 return error("AcceptBlock() : AddToBlockIndex failed");
2067
2068 // Relay inventory, but don't relay old inventory during initial block download
eae82d8e 2069 int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
0a61b0df 2070 if (hashBestChain == hash)
f8dcd5ca
PW
2071 {
2072 LOCK(cs_vNodes);
2073 BOOST_FOREACH(CNode* pnode, vNodes)
2074 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
2075 pnode->PushInventory(CInv(MSG_BLOCK, hash));
2076 }
0a61b0df 2077
2078 return true;
2079}
2080
de237cbf
GA
2081bool CBlockIndex::IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired, unsigned int nToCheck)
2082{
2083 unsigned int nFound = 0;
2084 for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++)
2085 {
2086 if (pstart->nVersion >= minVersion)
2087 ++nFound;
2088 pstart = pstart->pprev;
2089 }
2090 return (nFound >= nRequired);
2091}
2092
074d584a 2093bool ProcessBlock(CNode* pfrom, CBlock* pblock)
0a61b0df 2094{
2095 // Check for duplicate
2096 uint256 hash = pblock->GetHash();
2097 if (mapBlockIndex.count(hash))
2098 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
2099 if (mapOrphanBlocks.count(hash))
2100 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
2101
2102 // Preliminary checks
2103 if (!pblock->CheckBlock())
0a61b0df 2104 return error("ProcessBlock() : CheckBlock FAILED");
0a61b0df 2105
10fd7f66
GA
2106 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(mapBlockIndex);
2107 if (pcheckpoint && pblock->hashPrevBlock != hashBestChain)
2108 {
2109 // Extra checks to prevent "fill up memory by spamming with bogus blocks"
bde280b9 2110 int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
10fd7f66
GA
2111 if (deltaTime < 0)
2112 {
73aa0421
PW
2113 if (pfrom)
2114 pfrom->Misbehaving(100);
10fd7f66
GA
2115 return error("ProcessBlock() : block with timestamp before last checkpoint");
2116 }
2117 CBigNum bnNewBlock;
2118 bnNewBlock.SetCompact(pblock->nBits);
2119 CBigNum bnRequired;
2120 bnRequired.SetCompact(ComputeMinWork(pcheckpoint->nBits, deltaTime));
2121 if (bnNewBlock > bnRequired)
2122 {
73aa0421
PW
2123 if (pfrom)
2124 pfrom->Misbehaving(100);
10fd7f66
GA
2125 return error("ProcessBlock() : block with too little proof-of-work");
2126 }
2127 }
2128
2129
5c88e3c1 2130 // If we don't already have its previous block, shunt it off to holding area until we get it
0a61b0df 2131 if (!mapBlockIndex.count(pblock->hashPrevBlock))
2132 {
2133 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
0a61b0df 2134
5c88e3c1
PW
2135 // Accept orphans as long as there is a node to request its parents from
2136 if (pfrom) {
2137 CBlock* pblock2 = new CBlock(*pblock);
2138 mapOrphanBlocks.insert(make_pair(hash, pblock2));
2139 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
2140
2141 // Ask this guy to fill in what we're missing
776d0f34 2142 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
5c88e3c1 2143 }
0a61b0df 2144 return true;
2145 }
2146
2147 // Store to disk
2148 if (!pblock->AcceptBlock())
0a61b0df 2149 return error("ProcessBlock() : AcceptBlock FAILED");
0a61b0df 2150
2151 // Recursively process any orphan blocks that depended on this one
2152 vector<uint256> vWorkQueue;
2153 vWorkQueue.push_back(hash);
c376ac35 2154 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
0a61b0df 2155 {
2156 uint256 hashPrev = vWorkQueue[i];
2157 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
2158 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
2159 ++mi)
2160 {
2161 CBlock* pblockOrphan = (*mi).second;
2162 if (pblockOrphan->AcceptBlock())
2163 vWorkQueue.push_back(pblockOrphan->GetHash());
2164 mapOrphanBlocks.erase(pblockOrphan->GetHash());
2165 delete pblockOrphan;
2166 }
2167 mapOrphanBlocksByPrev.erase(hashPrev);
2168 }
2169
2170 printf("ProcessBlock: ACCEPTED\n");
2171 return true;
2172}
2173
2174
2175
2176
2177
2178
2179
2180
bde280b9 2181bool CheckDiskSpace(uint64 nAdditionalBytes)
0a61b0df 2182{
bde280b9 2183 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
0a61b0df 2184
966ae00f
PK
2185 // Check for nMinDiskSpace bytes (currently 50MB)
2186 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
0a61b0df 2187 {
2188 fShutdown = true;
e6bc9c35 2189 string strMessage = _("Warning: Disk space is low!");
0a61b0df 2190 strMiscWarning = strMessage;
2191 printf("*** %s\n", strMessage.c_str());
239c11d0 2192 uiInterface.ThreadSafeMessageBox(strMessage, "Bitcoin", CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
9247134e 2193 StartShutdown();
0a61b0df 2194 return false;
2195 }
2196 return true;
2197}
2198
5382bcf8
PW
2199CCriticalSection cs_LastBlockFile;
2200CBlockFileInfo infoLastBlockFile;
2201int nLastBlockFile = 0;
2202
2203FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
42613c97 2204{
450cbb09 2205 if (pos.IsNull())
0a61b0df 2206 return NULL;
5382bcf8
PW
2207 boost::filesystem::path path = GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
2208 boost::filesystem::create_directories(path.parent_path());
2209 FILE* file = fopen(path.string().c_str(), "rb+");
2210 if (!file && !fReadOnly)
2211 file = fopen(path.string().c_str(), "wb+");
450cbb09
PW
2212 if (!file) {
2213 printf("Unable to open file %s\n", path.string().c_str());
0a61b0df 2214 return NULL;
450cbb09 2215 }
5382bcf8
PW
2216 if (pos.nPos) {
2217 if (fseek(file, pos.nPos, SEEK_SET)) {
2218 printf("Unable to seek to position %u of %s\n", pos.nPos, path.string().c_str());
2219 fclose(file);
2220 return NULL;
2221 }
2222 }
0a61b0df 2223 return file;
2224}
2225
5382bcf8
PW
2226FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
2227 return OpenDiskFile(pos, "blk", fReadOnly);
2228}
2229
2230FILE *OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
2231 return OpenDiskFile(pos, "rev", fReadOnly);
2232}
2233
2d8a4829
PW
2234CBlockIndex * InsertBlockIndex(uint256 hash)
2235{
2236 if (hash == 0)
2237 return NULL;
2238
2239 // Return existing
2240 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
2241 if (mi != mapBlockIndex.end())
2242 return (*mi).second;
2243
2244 // Create new
2245 CBlockIndex* pindexNew = new CBlockIndex();
2246 if (!pindexNew)
2247 throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
2248 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2249 pindexNew->phashBlock = &((*mi).first);
2250
2251 return pindexNew;
2252}
2253
2254bool static LoadBlockIndexDB()
2255{
2256 if (!pblocktree->LoadBlockIndexGuts())
2257 return false;
2258
2259 if (fRequestShutdown)
2260 return true;
2261
2262 // Calculate bnChainWork
2263 vector<pair<int, CBlockIndex*> > vSortedByHeight;
2264 vSortedByHeight.reserve(mapBlockIndex.size());
2265 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
2266 {
2267 CBlockIndex* pindex = item.second;
2268 vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
2269 }
2270 sort(vSortedByHeight.begin(), vSortedByHeight.end());
2271 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
2272 {
2273 CBlockIndex* pindex = item.second;
2274 pindex->bnChainWork = (pindex->pprev ? pindex->pprev->bnChainWork : 0) + pindex->GetBlockWork();
2275 pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
2276 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS && !(pindex->nStatus & BLOCK_FAILED_MASK))
2277 setBlockIndexValid.insert(pindex);
2278 }
2279
2280 // Load block file info
2281 pblocktree->ReadLastBlockFile(nLastBlockFile);
2282 printf("LoadBlockIndex(): last block file = %i\n", nLastBlockFile);
2283 if (pblocktree->ReadBlockFileInfo(nLastBlockFile, infoLastBlockFile))
2284 printf("LoadBlockIndex(): last block file: %s\n", infoLastBlockFile.ToString().c_str());
729b1806 2285
2d8a4829
PW
2286 // Load hashBestChain pointer to end of best chain
2287 pindexBest = pcoinsTip->GetBestBlock();
2288 if (pindexBest == NULL)
2289 {
2290 if (pindexGenesisBlock == NULL)
2291 return true;
2292 }
2293 hashBestChain = pindexBest->GetBlockHash();
2294 nBestHeight = pindexBest->nHeight;
2295 bnBestChainWork = pindexBest->bnChainWork;
2296
2297 // set 'next' pointers in best chain
2298 CBlockIndex *pindex = pindexBest;
2299 while(pindex != NULL && pindex->pprev != NULL) {
2300 CBlockIndex *pindexPrev = pindex->pprev;
2301 pindexPrev->pnext = pindex;
2302 pindex = pindexPrev;
2303 }
2304 printf("LoadBlockIndex(): hashBestChain=%s height=%d date=%s\n",
2305 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight,
2306 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
2307
2308 // Load bnBestInvalidWork, OK if it doesn't exist
2309 pblocktree->ReadBestInvalidWork(bnBestInvalidWork);
2310
2311 // Verify blocks in the best chain
2312 int nCheckLevel = GetArg("-checklevel", 1);
2313 int nCheckDepth = GetArg( "-checkblocks", 2500);
2314 if (nCheckDepth == 0)
2315 nCheckDepth = 1000000000; // suffices until the year 19000
2316 if (nCheckDepth > nBestHeight)
2317 nCheckDepth = nBestHeight;
2318 printf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
2319 CBlockIndex* pindexFork = NULL;
2320 for (CBlockIndex* pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev)
2321 {
2322 if (fRequestShutdown || pindex->nHeight < nBestHeight-nCheckDepth)
2323 break;
2324 CBlock block;
2325 if (!block.ReadFromDisk(pindex))
2326 return error("LoadBlockIndex() : block.ReadFromDisk failed");
2327 // check level 1: verify block validity
2328 if (nCheckLevel>0 && !block.CheckBlock())
2329 {
2330 printf("LoadBlockIndex() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
2331 pindexFork = pindex->pprev;
2332 }
2333 // TODO: stronger verifications
2334 }
2335 if (pindexFork && !fRequestShutdown)
2336 {
2337 // TODO: reorg back
2338 return error("LoadBlockIndex(): chain database corrupted");
2339 }
2340
2341 return true;
2342}
2343
0a61b0df 2344bool LoadBlockIndex(bool fAllowNew)
2345{
5cbf7532 2346 if (fTestNet)
2347 {
a9d811a9
GM
2348 pchMessageStart[0] = 0x0b;
2349 pchMessageStart[1] = 0x11;
2350 pchMessageStart[2] = 0x09;
2351 pchMessageStart[3] = 0x07;
feeb761b 2352 hashGenesisBlock = uint256("000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943");
5cbf7532 2353 }
2354
0a61b0df 2355 //
d979e6e3 2356 // Load block index from databases
0a61b0df 2357 //
d979e6e3 2358 if (!LoadBlockIndexDB())
0a61b0df 2359 return false;
0a61b0df 2360
2361 //
2362 // Init with genesis block
2363 //
2364 if (mapBlockIndex.empty())
2365 {
2366 if (!fAllowNew)
2367 return false;
2368
2369 // Genesis Block:
2370 // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
2371 // CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2372 // CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
2373 // CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
2374 // vMerkleTree: 4a5e1e
2375
2376 // Genesis block
2377 const char* pszTimestamp = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks";
2378 CTransaction txNew;
2379 txNew.vin.resize(1);
2380 txNew.vout.resize(1);
2381 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
2382 txNew.vout[0].nValue = 50 * COIN;
2383 txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG;
2384 CBlock block;
2385 block.vtx.push_back(txNew);
2386 block.hashPrevBlock = 0;
2387 block.hashMerkleRoot = block.BuildMerkleTree();
2388 block.nVersion = 1;
2389 block.nTime = 1231006505;
2390 block.nBits = 0x1d00ffff;
2391 block.nNonce = 2083236893;
2392
5cbf7532 2393 if (fTestNet)
2394 {
98ba262a 2395 block.nTime = 1296688602;
feeb761b 2396 block.nNonce = 414098458;
5cbf7532 2397 }
0a61b0df 2398
5cbf7532 2399 //// debug print
630fd8dc
PW
2400 uint256 hash = block.GetHash();
2401 printf("%s\n", hash.ToString().c_str());
5cbf7532 2402 printf("%s\n", hashGenesisBlock.ToString().c_str());
2403 printf("%s\n", block.hashMerkleRoot.ToString().c_str());
2404 assert(block.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));
2405 block.print();
630fd8dc 2406 assert(hash == hashGenesisBlock);
0a61b0df 2407
2408 // Start new block file
5382bcf8
PW
2409 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
2410 CDiskBlockPos blockPos;
d979e6e3
PW
2411 if (!FindBlockPos(blockPos, nBlockSize+8, 0, block.nTime))
2412 return error("AcceptBlock() : FindBlockPos failed");
630fd8dc 2413 if (!block.WriteToDisk(blockPos))
0a61b0df 2414 return error("LoadBlockIndex() : writing genesis block to disk failed");
630fd8dc 2415 if (!block.AddToBlockIndex(blockPos))
0a61b0df 2416 return error("LoadBlockIndex() : genesis block not accepted");
2417 }
2418
2419 return true;
2420}
2421
2422
2423
2424void PrintBlockTree()
2425{
814efd6f 2426 // pre-compute tree structure
0a61b0df 2427 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
2428 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
2429 {
2430 CBlockIndex* pindex = (*mi).second;
2431 mapNext[pindex->pprev].push_back(pindex);
2432 // test
2433 //while (rand() % 3 == 0)
2434 // mapNext[pindex->pprev].push_back(pindex);
2435 }
2436
2437 vector<pair<int, CBlockIndex*> > vStack;
2438 vStack.push_back(make_pair(0, pindexGenesisBlock));
2439
2440 int nPrevCol = 0;
2441 while (!vStack.empty())
2442 {
2443 int nCol = vStack.back().first;
2444 CBlockIndex* pindex = vStack.back().second;
2445 vStack.pop_back();
2446
2447 // print split or gap
2448 if (nCol > nPrevCol)
2449 {
2450 for (int i = 0; i < nCol-1; i++)
2451 printf("| ");
2452 printf("|\\\n");
2453 }
2454 else if (nCol < nPrevCol)
2455 {
2456 for (int i = 0; i < nCol; i++)
2457 printf("| ");
2458 printf("|\n");
64c7ee7e 2459 }
0a61b0df 2460 nPrevCol = nCol;
2461
2462 // print columns
2463 for (int i = 0; i < nCol; i++)
2464 printf("| ");
2465
2466 // print item
2467 CBlock block;
2468 block.ReadFromDisk(pindex);
450cbb09 2469 printf("%d (blk%05u.dat:0x%x) %s tx %"PRIszu"",
0a61b0df 2470 pindex->nHeight,
5382bcf8 2471 pindex->GetBlockPos().nFile, pindex->GetBlockPos().nPos,
0a61b0df 2472 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
2473 block.vtx.size());
2474
64c7ee7e 2475 PrintWallets(block);
0a61b0df 2476
814efd6f 2477 // put the main time-chain first
0a61b0df 2478 vector<CBlockIndex*>& vNext = mapNext[pindex];
c376ac35 2479 for (unsigned int i = 0; i < vNext.size(); i++)
0a61b0df 2480 {
2481 if (vNext[i]->pnext)
2482 {
2483 swap(vNext[0], vNext[i]);
2484 break;
2485 }
2486 }
2487
2488 // iterate children
c376ac35 2489 for (unsigned int i = 0; i < vNext.size(); i++)
0a61b0df 2490 vStack.push_back(make_pair(nCol+i, vNext[i]));
2491 }
2492}
2493
1d740055
PW
2494bool LoadExternalBlockFile(FILE* fileIn)
2495{
746f502a
PK
2496 int64 nStart = GetTimeMillis();
2497
1d740055
PW
2498 int nLoaded = 0;
2499 {
1d740055
PW
2500 try {
2501 CAutoFile blkdat(fileIn, SER_DISK, CLIENT_VERSION);
2502 unsigned int nPos = 0;
f621326c 2503 while (nPos != (unsigned int)-1 && blkdat.good() && !fRequestShutdown)
1d740055
PW
2504 {
2505 unsigned char pchData[65536];
2506 do {
2507 fseek(blkdat, nPos, SEEK_SET);
2508 int nRead = fread(pchData, 1, sizeof(pchData), blkdat);
2509 if (nRead <= 8)
2510 {
f621326c 2511 nPos = (unsigned int)-1;
1d740055
PW
2512 break;
2513 }
2514 void* nFind = memchr(pchData, pchMessageStart[0], nRead+1-sizeof(pchMessageStart));
2515 if (nFind)
2516 {
2517 if (memcmp(nFind, pchMessageStart, sizeof(pchMessageStart))==0)
2518 {
2519 nPos += ((unsigned char*)nFind - pchData) + sizeof(pchMessageStart);
2520 break;
2521 }
2522 nPos += ((unsigned char*)nFind - pchData) + 1;
2523 }
2524 else
2525 nPos += sizeof(pchData) - sizeof(pchMessageStart) + 1;
2526 } while(!fRequestShutdown);
f621326c 2527 if (nPos == (unsigned int)-1)
1d740055
PW
2528 break;
2529 fseek(blkdat, nPos, SEEK_SET);
2530 unsigned int nSize;
2531 blkdat >> nSize;
2532 if (nSize > 0 && nSize <= MAX_BLOCK_SIZE)
2533 {
2534 CBlock block;
2535 blkdat >> block;
66b02c93 2536 LOCK(cs_main);
1d740055
PW
2537 if (ProcessBlock(NULL,&block))
2538 {
2539 nLoaded++;
2540 nPos += 4 + nSize;
2541 }
2542 }
2543 }
2544 }
8fe791e4
JG
2545 catch (std::exception &e) {
2546 printf("%s() : Deserialize or I/O error caught during load\n",
2547 __PRETTY_FUNCTION__);
1d740055
PW
2548 }
2549 }
746f502a 2550 printf("Loaded %i blocks from external file in %"PRI64d"ms\n", nLoaded, GetTimeMillis() - nStart);
1d740055
PW
2551 return nLoaded > 0;
2552}
0a61b0df 2553
66b02c93
PW
2554struct CImportingNow
2555{
2556 CImportingNow() {
2557 assert(fImporting == false);
2558 fImporting = true;
2559 }
2560
2561 ~CImportingNow() {
2562 assert(fImporting == true);
2563 fImporting = false;
2564 }
2565};
2566
2567void ThreadImport(void *data) {
2568 std::vector<boost::filesystem::path> *vFiles = reinterpret_cast<std::vector<boost::filesystem::path>*>(data);
2569
2570 RenameThread("bitcoin-loadblk");
2571
2572 CImportingNow imp;
2573 vnThreadsRunning[THREAD_IMPORT]++;
2574
2575 // -loadblock=
66b02c93
PW
2576 BOOST_FOREACH(boost::filesystem::path &path, *vFiles) {
2577 FILE *file = fopen(path.string().c_str(), "rb");
2578 if (file)
2579 LoadExternalBlockFile(file);
2580 }
2581
2582 // hardcoded $DATADIR/bootstrap.dat
2583 filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat";
2584 if (filesystem::exists(pathBootstrap)) {
66b02c93
PW
2585 FILE *file = fopen(pathBootstrap.string().c_str(), "rb");
2586 if (file) {
2587 filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
2588 LoadExternalBlockFile(file);
2589 RenameOver(pathBootstrap, pathBootstrapOld);
2590 }
2591 }
2592
2593 delete vFiles;
2594
2595 vnThreadsRunning[THREAD_IMPORT]--;
2596}
2597
2598
0a61b0df 2599
2600
2601
2602
2603
2604
2605
2606
2607//////////////////////////////////////////////////////////////////////////////
2608//
2609// CAlert
2610//
2611
f35c6c4f
GA
2612extern map<uint256, CAlert> mapAlerts;
2613extern CCriticalSection cs_mapAlerts;
0a61b0df 2614
2615string GetWarnings(string strFor)
2616{
2617 int nPriority = 0;
2618 string strStatusBar;
2619 string strRPC;
bdde31d7 2620 if (GetBoolArg("-testsafemode"))
0a61b0df 2621 strRPC = "test";
2622
2623 // Misc warnings like out of disk space and clock is wrong
2624 if (strMiscWarning != "")
2625 {
2626 nPriority = 1000;
2627 strStatusBar = strMiscWarning;
2628 }
2629
2630 // Longer invalid proof-of-work chain
2631 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
2632 {
2633 nPriority = 2000;
e6bc9c35 2634 strStatusBar = strRPC = _("Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.");
0a61b0df 2635 }
2636
2637 // Alerts
0a61b0df 2638 {
f8dcd5ca 2639 LOCK(cs_mapAlerts);
223b6f1b 2640 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
0a61b0df 2641 {
2642 const CAlert& alert = item.second;
2643 if (alert.AppliesToMe() && alert.nPriority > nPriority)
2644 {
2645 nPriority = alert.nPriority;
2646 strStatusBar = alert.strStatusBar;
0a61b0df 2647 }
2648 }
2649 }
2650
2651 if (strFor == "statusbar")
2652 return strStatusBar;
2653 else if (strFor == "rpc")
2654 return strRPC;
ecf1c79a 2655 assert(!"GetWarnings() : invalid parameter");
0a61b0df 2656 return "error";
2657}
2658
0a61b0df 2659
2660
2661
2662
2663
2664
2665
2666//////////////////////////////////////////////////////////////////////////////
2667//
2668// Messages
2669//
2670
2671
ae8bfd12 2672bool static AlreadyHave(const CInv& inv)
0a61b0df 2673{
2674 switch (inv.type)
2675 {
8deb9822
JG
2676 case MSG_TX:
2677 {
450cbb09 2678 bool txInMap = false;
ce8c9349 2679 {
450cbb09
PW
2680 LOCK(mempool.cs);
2681 txInMap = mempool.exists(inv.hash);
ce8c9349 2682 }
450cbb09 2683 return txInMap || mapOrphanTransactions.count(inv.hash) ||
ae8bfd12 2684 pcoinsTip->HaveCoins(inv.hash);
8deb9822 2685 }
8deb9822
JG
2686 case MSG_BLOCK:
2687 return mapBlockIndex.count(inv.hash) ||
2688 mapOrphanBlocks.count(inv.hash);
0a61b0df 2689 }
2690 // Don't know what it is, just say we already got one
2691 return true;
2692}
2693
2694
2695
2696
5cbf7532 2697// The message start string is designed to be unlikely to occur in normal data.
814efd6f 2698// The characters are rarely used upper ASCII, not valid as UTF-8, and produce
5cbf7532 2699// a large 4-byte int at any alignment.
25133bd7 2700unsigned char pchMessageStart[4] = { 0xf9, 0xbe, 0xb4, 0xd9 };
0a61b0df 2701
2702
64c7ee7e 2703bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
0a61b0df 2704{
fd61d6f5 2705 static map<CService, CPubKey> mapReuseKey;
0a61b0df 2706 RandAddSeedPerfmon();
0985816b 2707 if (fDebug)
d210f4f5 2708 printf("received: %s (%"PRIszu" bytes)\n", strCommand.c_str(), vRecv.size());
0a61b0df 2709 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
2710 {
2711 printf("dropmessagestest DROPPING RECV MESSAGE\n");
2712 return true;
2713 }
2714
2715
2716
2717
2718
2719 if (strCommand == "version")
2720 {
2721 // Each connection can only send one version message
2722 if (pfrom->nVersion != 0)
806704c2
GA
2723 {
2724 pfrom->Misbehaving(1);
0a61b0df 2725 return false;
806704c2 2726 }
0a61b0df 2727
bde280b9 2728 int64 nTime;
0a61b0df 2729 CAddress addrMe;
2730 CAddress addrFrom;
bde280b9 2731 uint64 nNonce = 1;
0a61b0df 2732 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
8b09cd3a 2733 if (pfrom->nVersion < MIN_PROTO_VERSION)
18c0fa97 2734 {
27adfb2e 2735 // Since February 20, 2012, the protocol is initiated at version 209,
18c0fa97
PW
2736 // and earlier versions are no longer supported
2737 printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
2738 pfrom->fDisconnect = true;
2739 return false;
2740 }
2741
0a61b0df 2742 if (pfrom->nVersion == 10300)
2743 pfrom->nVersion = 300;
18c0fa97 2744 if (!vRecv.empty())
0a61b0df 2745 vRecv >> addrFrom >> nNonce;
18c0fa97 2746 if (!vRecv.empty())
0a61b0df 2747 vRecv >> pfrom->strSubVer;
18c0fa97 2748 if (!vRecv.empty())
0a61b0df 2749 vRecv >> pfrom->nStartingHeight;
2750
39857190
PW
2751 if (pfrom->fInbound && addrMe.IsRoutable())
2752 {
2753 pfrom->addrLocal = addrMe;
2754 SeenLocal(addrMe);
2755 }
2756
0a61b0df 2757 // Disconnect if we connected to ourself
2758 if (nNonce == nLocalHostNonce && nNonce > 1)
2759 {
b22c8842 2760 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
0a61b0df 2761 pfrom->fDisconnect = true;
2762 return true;
2763 }
2764
cbc920d4
GA
2765 // Be shy and don't send version until we hear
2766 if (pfrom->fInbound)
2767 pfrom->PushVersion();
2768
0a61b0df 2769 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
0a61b0df 2770
67a42f92 2771 AddTimeData(pfrom->addr, nTime);
0a61b0df 2772
2773 // Change version
18c0fa97 2774 pfrom->PushMessage("verack");
f8ded588 2775 pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
0a61b0df 2776
c891967b 2777 if (!pfrom->fInbound)
2778 {
2779 // Advertise our address
587f929c 2780 if (!fNoListen && !IsInitialBlockDownload())
c891967b 2781 {
39857190
PW
2782 CAddress addr = GetLocalAddress(&pfrom->addr);
2783 if (addr.IsRoutable())
2784 pfrom->PushAddress(addr);
c891967b 2785 }
2786
2787 // Get recent addresses
478b01d9 2788 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
c891967b 2789 {
2790 pfrom->PushMessage("getaddr");
2791 pfrom->fGetAddr = true;
2792 }
5fee401f
PW
2793 addrman.Good(pfrom->addr);
2794 } else {
2795 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
2796 {
2797 addrman.Add(addrFrom, addrFrom);
2798 addrman.Good(addrFrom);
2799 }
c891967b 2800 }
2801
0a61b0df 2802 // Ask the first connected node for block updates
9ef7fa34 2803 static int nAskedForBlocks = 0;
66b02c93 2804 if (!pfrom->fClient && !pfrom->fOneShot && !fImporting &&
93dd68e9 2805 (pfrom->nStartingHeight > (nBestHeight - 144)) &&
8b09cd3a 2806 (pfrom->nVersion < NOBLKS_VERSION_START ||
ce8c9349 2807 pfrom->nVersion >= NOBLKS_VERSION_END) &&
ec74e8a4 2808 (nAskedForBlocks < 1 || vNodes.size() <= 1))
0a61b0df 2809 {
2810 nAskedForBlocks++;
2811 pfrom->PushGetBlocks(pindexBest, uint256(0));
2812 }
2813
2814 // Relay alerts
f8dcd5ca
PW
2815 {
2816 LOCK(cs_mapAlerts);
223b6f1b 2817 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
0a61b0df 2818 item.second.RelayTo(pfrom);
f8dcd5ca 2819 }
0a61b0df 2820
2821 pfrom->fSuccessfullyConnected = true;
2822
863e995b 2823 printf("receive version message: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", pfrom->nVersion, pfrom->nStartingHeight, addrMe.ToString().c_str(), addrFrom.ToString().c_str(), pfrom->addr.ToString().c_str());
a8b95ce6
WL
2824
2825 cPeerBlockCounts.input(pfrom->nStartingHeight);
0a61b0df 2826 }
2827
2828
2829 else if (pfrom->nVersion == 0)
2830 {
2831 // Must have a version message before anything else
806704c2 2832 pfrom->Misbehaving(1);
0a61b0df 2833 return false;
2834 }
2835
2836
2837 else if (strCommand == "verack")
2838 {
f8ded588 2839 pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
0a61b0df 2840 }
2841
2842
2843 else if (strCommand == "addr")
2844 {
2845 vector<CAddress> vAddr;
2846 vRecv >> vAddr;
c891967b 2847
2848 // Don't want addr from older versions unless seeding
8b09cd3a 2849 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
0a61b0df 2850 return true;
2851 if (vAddr.size() > 1000)
806704c2
GA
2852 {
2853 pfrom->Misbehaving(20);
d210f4f5 2854 return error("message addr size() = %"PRIszu"", vAddr.size());
806704c2 2855 }
0a61b0df 2856
2857 // Store the new addresses
090e5b40 2858 vector<CAddress> vAddrOk;
bde280b9
WL
2859 int64 nNow = GetAdjustedTime();
2860 int64 nSince = nNow - 10 * 60;
223b6f1b 2861 BOOST_FOREACH(CAddress& addr, vAddr)
0a61b0df 2862 {
2863 if (fShutdown)
2864 return true;
c891967b 2865 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
2866 addr.nTime = nNow - 5 * 24 * 60 * 60;
0a61b0df 2867 pfrom->AddAddressKnown(addr);
090e5b40 2868 bool fReachable = IsReachable(addr);
c891967b 2869 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
0a61b0df 2870 {
2871 // Relay to a limited number of other nodes
0a61b0df 2872 {
f8dcd5ca 2873 LOCK(cs_vNodes);
5cbf7532 2874 // Use deterministic randomness to send to the same nodes for 24 hours
2875 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
0a61b0df 2876 static uint256 hashSalt;
2877 if (hashSalt == 0)
f718aedd 2878 hashSalt = GetRandHash();
4843b55f 2879 uint64 hashAddr = addr.GetHash();
67a42f92 2880 uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60));
5cbf7532 2881 hashRand = Hash(BEGIN(hashRand), END(hashRand));
0a61b0df 2882 multimap<uint256, CNode*> mapMix;
223b6f1b 2883 BOOST_FOREACH(CNode* pnode, vNodes)
5cbf7532 2884 {
8b09cd3a 2885 if (pnode->nVersion < CADDR_TIME_VERSION)
c891967b 2886 continue;
5cbf7532 2887 unsigned int nPointer;
2888 memcpy(&nPointer, &pnode, sizeof(nPointer));
2889 uint256 hashKey = hashRand ^ nPointer;
2890 hashKey = Hash(BEGIN(hashKey), END(hashKey));
2891 mapMix.insert(make_pair(hashKey, pnode));
2892 }
090e5b40 2893 int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
0a61b0df 2894 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
2895 ((*mi).second)->PushAddress(addr);
2896 }
2897 }
090e5b40
PW
2898 // Do not store addresses outside our network
2899 if (fReachable)
2900 vAddrOk.push_back(addr);
0a61b0df 2901 }
090e5b40 2902 addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
0a61b0df 2903 if (vAddr.size() < 1000)
2904 pfrom->fGetAddr = false;
478b01d9
PW
2905 if (pfrom->fOneShot)
2906 pfrom->fDisconnect = true;
0a61b0df 2907 }
2908
2909
2910 else if (strCommand == "inv")
2911 {
2912 vector<CInv> vInv;
2913 vRecv >> vInv;
05a85b2b 2914 if (vInv.size() > MAX_INV_SZ)
806704c2
GA
2915 {
2916 pfrom->Misbehaving(20);
d210f4f5 2917 return error("message inv size() = %"PRIszu"", vInv.size());
806704c2 2918 }
0a61b0df 2919
68601333
PW
2920 // find last block in inv vector
2921 unsigned int nLastBlock = (unsigned int)(-1);
2922 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) {
385f730f 2923 if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) {
68601333 2924 nLastBlock = vInv.size() - 1 - nInv;
385f730f
PW
2925 break;
2926 }
68601333 2927 }
c376ac35 2928 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
0a61b0df 2929 {
0aa89c08
PW
2930 const CInv &inv = vInv[nInv];
2931
0a61b0df 2932 if (fShutdown)
2933 return true;
2934 pfrom->AddInventoryKnown(inv);
2935
ae8bfd12 2936 bool fAlreadyHave = AlreadyHave(inv);
59090133
NS
2937 if (fDebug)
2938 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
0a61b0df 2939
66b02c93
PW
2940 if (!fAlreadyHave) {
2941 if (!fImporting)
2942 pfrom->AskFor(inv);
2943 } else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) {
0a61b0df 2944 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
385f730f
PW
2945 } else if (nInv == nLastBlock) {
2946 // In case we are on a very long side-chain, it is possible that we already have
2947 // the last block in an inv bundle sent in response to getblocks. Try to detect
2948 // this situation and push another getblocks to continue.
385f730f
PW
2949 pfrom->PushGetBlocks(mapBlockIndex[inv.hash], uint256(0));
2950 if (fDebug)
2951 printf("force request: %s\n", inv.ToString().c_str());
2952 }
0a61b0df 2953
2954 // Track requests for our stuff
64c7ee7e 2955 Inventory(inv.hash);
0a61b0df 2956 }
2957 }
2958
2959
2960 else if (strCommand == "getdata")
2961 {
2962 vector<CInv> vInv;
2963 vRecv >> vInv;
05a85b2b 2964 if (vInv.size() > MAX_INV_SZ)
806704c2
GA
2965 {
2966 pfrom->Misbehaving(20);
d210f4f5 2967 return error("message getdata size() = %"PRIszu"", vInv.size());
806704c2 2968 }
0a61b0df 2969
983e4bde 2970 if (fDebugNet || (vInv.size() != 1))
d210f4f5 2971 printf("received getdata (%"PRIszu" invsz)\n", vInv.size());
983e4bde 2972
223b6f1b 2973 BOOST_FOREACH(const CInv& inv, vInv)
0a61b0df 2974 {
2975 if (fShutdown)
2976 return true;
983e4bde
JG
2977 if (fDebugNet || (vInv.size() == 1))
2978 printf("received getdata for: %s\n", inv.ToString().c_str());
0a61b0df 2979
2980 if (inv.type == MSG_BLOCK)
2981 {
2982 // Send block from disk
2983 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
2984 if (mi != mapBlockIndex.end())
2985 {
0a61b0df 2986 CBlock block;
f03304a9 2987 block.ReadFromDisk((*mi).second);
0a61b0df 2988 pfrom->PushMessage("block", block);
2989
2990 // Trigger them to send a getblocks request for the next batch of inventory
2991 if (inv.hash == pfrom->hashContinue)
2992 {
2993 // Bypass PushInventory, this must send even if redundant,
2994 // and we want it right after the last block so they don't
2995 // wait for other stuff first.
2996 vector<CInv> vInv;
2997 vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
2998 pfrom->PushMessage("inv", vInv);
2999 pfrom->hashContinue = 0;
3000 }
3001 }
3002 }
3003 else if (inv.IsKnownType())
3004 {
3005 // Send stream from relay memory
05a85b2b 3006 bool pushed = false;
0a61b0df 3007 {
f8dcd5ca 3008 LOCK(cs_mapRelay);
0a61b0df 3009 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
05a85b2b 3010 if (mi != mapRelay.end()) {
0a61b0df 3011 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
05a85b2b
JG
3012 pushed = true;
3013 }
3014 }
3015 if (!pushed && inv.type == MSG_TX) {
3016 LOCK(mempool.cs);
3017 if (mempool.exists(inv.hash)) {
3018 CTransaction tx = mempool.lookup(inv.hash);
3019 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
3020 ss.reserve(1000);
3021 ss << tx;
3022 pfrom->PushMessage("tx", ss);
3023 }
0a61b0df 3024 }
3025 }
3026
3027 // Track requests for our stuff
64c7ee7e 3028 Inventory(inv.hash);
0a61b0df 3029 }
3030 }
3031
3032
3033 else if (strCommand == "getblocks")
3034 {
3035 CBlockLocator locator;
3036 uint256 hashStop;
3037 vRecv >> locator >> hashStop;
3038
f03304a9 3039 // Find the last block the caller has in the main chain
0a61b0df 3040 CBlockIndex* pindex = locator.GetBlockIndex();
3041
3042 // Send the rest of the chain
3043 if (pindex)
3044 pindex = pindex->pnext;
9d6cd04b 3045 int nLimit = 500;
0a61b0df 3046 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
3047 for (; pindex; pindex = pindex->pnext)
3048 {
3049 if (pindex->GetBlockHash() == hashStop)
3050 {
9d6cd04b 3051 printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
0a61b0df 3052 break;
3053 }
3054 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
9d6cd04b 3055 if (--nLimit <= 0)
0a61b0df 3056 {
3057 // When this block is requested, we'll send an inv that'll make them
3058 // getblocks the next batch of inventory.
9d6cd04b 3059 printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
0a61b0df 3060 pfrom->hashContinue = pindex->GetBlockHash();
3061 break;
3062 }
3063 }
3064 }
3065
3066
f03304a9 3067 else if (strCommand == "getheaders")
3068 {
3069 CBlockLocator locator;
3070 uint256 hashStop;
3071 vRecv >> locator >> hashStop;
3072
3073 CBlockIndex* pindex = NULL;
3074 if (locator.IsNull())
3075 {
3076 // If locator is null, return the hashStop block
3077 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
3078 if (mi == mapBlockIndex.end())
3079 return true;
3080 pindex = (*mi).second;
3081 }
3082 else
3083 {
3084 // Find the last block the caller has in the main chain
3085 pindex = locator.GetBlockIndex();
3086 if (pindex)
3087 pindex = pindex->pnext;
3088 }
3089
3090 vector<CBlock> vHeaders;
ecf07f27
MC
3091 int nLimit = 2000;
3092 printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str());
f03304a9 3093 for (; pindex; pindex = pindex->pnext)
3094 {
3095 vHeaders.push_back(pindex->GetBlockHeader());
3096 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
3097 break;
3098 }
3099 pfrom->PushMessage("headers", vHeaders);
3100 }
3101
3102
0a61b0df 3103 else if (strCommand == "tx")
3104 {
3105 vector<uint256> vWorkQueue;
7a15109c 3106 vector<uint256> vEraseQueue;
0a61b0df 3107 CDataStream vMsg(vRecv);
3108 CTransaction tx;
3109 vRecv >> tx;
3110
3111 CInv inv(MSG_TX, tx.GetHash());
3112 pfrom->AddInventoryKnown(inv);
3113
3114 bool fMissingInputs = false;
ae8bfd12 3115 if (tx.AcceptToMemoryPool(true, &fMissingInputs))
0a61b0df 3116 {
64dd46fd 3117 SyncWithWallets(inv.hash, tx, NULL, true);
0a61b0df 3118 RelayMessage(inv, vMsg);
3119 mapAlreadyAskedFor.erase(inv);
3120 vWorkQueue.push_back(inv.hash);
7a15109c 3121 vEraseQueue.push_back(inv.hash);
0a61b0df 3122
3123 // Recursively process any orphan transactions that depended on this one
c376ac35 3124 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
0a61b0df 3125 {
3126 uint256 hashPrev = vWorkQueue[i];
77b99cf7
GA
3127 for (map<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin();
3128 mi != mapOrphanTransactionsByPrev[hashPrev].end();
0a61b0df 3129 ++mi)
3130 {
3131 const CDataStream& vMsg = *((*mi).second);
3132 CTransaction tx;
3133 CDataStream(vMsg) >> tx;
3134 CInv inv(MSG_TX, tx.GetHash());
7a15109c 3135 bool fMissingInputs2 = false;
0a61b0df 3136
ae8bfd12 3137 if (tx.AcceptToMemoryPool(true, &fMissingInputs2))
0a61b0df 3138 {
b22c8842 3139 printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
64dd46fd 3140 SyncWithWallets(inv.hash, tx, NULL, true);
0a61b0df 3141 RelayMessage(inv, vMsg);
3142 mapAlreadyAskedFor.erase(inv);
3143 vWorkQueue.push_back(inv.hash);
7a15109c
GA
3144 vEraseQueue.push_back(inv.hash);
3145 }
3146 else if (!fMissingInputs2)
3147 {
3148 // invalid orphan
3149 vEraseQueue.push_back(inv.hash);
3150 printf(" removed invalid orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
0a61b0df 3151 }
3152 }
3153 }
3154
7a15109c 3155 BOOST_FOREACH(uint256 hash, vEraseQueue)
0a61b0df 3156 EraseOrphanTx(hash);
3157 }
3158 else if (fMissingInputs)
3159 {
0a61b0df 3160 AddOrphanTx(vMsg);
142e6041
GA
3161
3162 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
7bd9c3a3 3163 unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
142e6041 3164 if (nEvicted > 0)
7bd9c3a3 3165 printf("mapOrphan overflow, removed %u tx\n", nEvicted);
0a61b0df 3166 }
3e52aaf2 3167 if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
0a61b0df 3168 }
3169
3170
3171 else if (strCommand == "block")
3172 {
f03304a9 3173 CBlock block;
3174 vRecv >> block;
0a61b0df 3175
f03304a9 3176 printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str());
3177 // block.print();
0a61b0df 3178
f03304a9 3179 CInv inv(MSG_BLOCK, block.GetHash());
0a61b0df 3180 pfrom->AddInventoryKnown(inv);
3181
f03304a9 3182 if (ProcessBlock(pfrom, &block))
0a61b0df 3183 mapAlreadyAskedFor.erase(inv);
3e52aaf2 3184 if (block.nDoS) pfrom->Misbehaving(block.nDoS);
0a61b0df 3185 }
3186
3187
3188 else if (strCommand == "getaddr")
3189 {
0a61b0df 3190 pfrom->vAddrToSend.clear();
5fee401f
PW
3191 vector<CAddress> vAddr = addrman.GetAddr();
3192 BOOST_FOREACH(const CAddress &addr, vAddr)
3193 pfrom->PushAddress(addr);
0a61b0df 3194 }
3195
3196
05a85b2b
JG
3197 else if (strCommand == "mempool")
3198 {
3199 std::vector<uint256> vtxid;
3200 mempool.queryHashes(vtxid);
3201 vector<CInv> vInv;
3202 for (unsigned int i = 0; i < vtxid.size(); i++) {
3203 CInv inv(MSG_TX, vtxid[i]);
3204 vInv.push_back(inv);
3205 if (i == (MAX_INV_SZ - 1))
3206 break;
3207 }
3208 if (vInv.size() > 0)
3209 pfrom->PushMessage("inv", vInv);
3210 }
3211
3212
0a61b0df 3213 else if (strCommand == "checkorder")
3214 {
3215 uint256 hashReply;
a206a239 3216 vRecv >> hashReply;
0a61b0df 3217
a206a239 3218 if (!GetBoolArg("-allowreceivebyip"))
172f0060 3219 {
3220 pfrom->PushMessage("reply", hashReply, (int)2, string(""));
3221 return true;
3222 }
3223
a206a239 3224 CWalletTx order;
3225 vRecv >> order;
3226
0a61b0df 3227 /// we have a chance to check the order here
3228
3229 // Keep giving the same key to the same ip until they use it
67a42f92
PW
3230 if (!mapReuseKey.count(pfrom->addr))
3231 pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true);
0a61b0df 3232
3233 // Send back approval of order and pubkey to use
3234 CScript scriptPubKey;
67a42f92 3235 scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG;
0a61b0df 3236 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
3237 }
3238
3239
0a61b0df 3240 else if (strCommand == "reply")
3241 {
3242 uint256 hashReply;
3243 vRecv >> hashReply;
3244
3245 CRequestTracker tracker;
0a61b0df 3246 {
f8dcd5ca 3247 LOCK(pfrom->cs_mapRequests);
0a61b0df 3248 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
3249 if (mi != pfrom->mapRequests.end())
3250 {
3251 tracker = (*mi).second;
3252 pfrom->mapRequests.erase(mi);
3253 }
3254 }
3255 if (!tracker.IsNull())
3256 tracker.fn(tracker.param1, vRecv);
3257 }
3258
3259
3260 else if (strCommand == "ping")
3261 {
93e447b6
JG
3262 if (pfrom->nVersion > BIP0031_VERSION)
3263 {
3264 uint64 nonce = 0;
3265 vRecv >> nonce;
3266 // Echo the message back with the nonce. This allows for two useful features:
3267 //
3268 // 1) A remote node can quickly check if the connection is operational
3269 // 2) Remote nodes can measure the latency of the network thread. If this node
3270 // is overloaded it won't respond to pings quickly and the remote node can
3271 // avoid sending us more work, like chain download requests.
3272 //
3273 // The nonce stops the remote getting confused between different pings: without
3274 // it, if the remote node sends a ping once per second and this node takes 5
3275 // seconds to respond to each, the 5th ping the remote sends would appear to
3276 // return very quickly.
3277 pfrom->PushMessage("pong", nonce);
3278 }
0a61b0df 3279 }
3280
3281
3282 else if (strCommand == "alert")
3283 {
3284 CAlert alert;
3285 vRecv >> alert;
3286
d5a52d9b
GA
3287 uint256 alertHash = alert.GetHash();
3288 if (pfrom->setKnown.count(alertHash) == 0)
0a61b0df 3289 {
d5a52d9b 3290 if (alert.ProcessAlert())
f8dcd5ca 3291 {
d5a52d9b
GA
3292 // Relay
3293 pfrom->setKnown.insert(alertHash);
3294 {
3295 LOCK(cs_vNodes);
3296 BOOST_FOREACH(CNode* pnode, vNodes)
3297 alert.RelayTo(pnode);
3298 }
3299 }
3300 else {
3301 // Small DoS penalty so peers that send us lots of
3302 // duplicate/expired/invalid-signature/whatever alerts
3303 // eventually get banned.
3304 // This isn't a Misbehaving(100) (immediate ban) because the
3305 // peer might be an older or different implementation with
3306 // a different signature key, etc.
3307 pfrom->Misbehaving(10);
f8dcd5ca 3308 }
0a61b0df 3309 }
3310 }
3311
3312
3313 else
3314 {
3315 // Ignore unknown commands for extensibility
3316 }
3317
3318
3319 // Update the last seen time for this node's address
3320 if (pfrom->fNetworkNode)
3321 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
3322 AddressCurrentlyConnected(pfrom->addr);
3323
3324
3325 return true;
3326}
3327
e89b9f6a
PW
3328bool ProcessMessages(CNode* pfrom)
3329{
3330 CDataStream& vRecv = pfrom->vRecv;
3331 if (vRecv.empty())
3332 return true;
3333 //if (fDebug)
3334 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
0a61b0df 3335
e89b9f6a
PW
3336 //
3337 // Message format
3338 // (4) message start
3339 // (12) command
3340 // (4) size
3341 // (4) checksum
3342 // (x) data
3343 //
0a61b0df 3344
e89b9f6a
PW
3345 loop
3346 {
9d6cd04b
MC
3347 // Don't bother if send buffer is too full to respond anyway
3348 if (pfrom->vSend.size() >= SendBufferSize())
3349 break;
3350
e89b9f6a
PW
3351 // Scan for message start
3352 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
3353 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
3354 if (vRecv.end() - pstart < nHeaderSize)
3355 {
1d8c7a95 3356 if ((int)vRecv.size() > nHeaderSize)
e89b9f6a
PW
3357 {
3358 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
3359 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
3360 }
3361 break;
3362 }
3363 if (pstart - vRecv.begin() > 0)
d210f4f5 3364 printf("\n\nPROCESSMESSAGE SKIPPED %"PRIpdd" BYTES\n\n", pstart - vRecv.begin());
e89b9f6a 3365 vRecv.erase(vRecv.begin(), pstart);
0a61b0df 3366
e89b9f6a
PW
3367 // Read header
3368 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
3369 CMessageHeader hdr;
3370 vRecv >> hdr;
3371 if (!hdr.IsValid())
3372 {
3373 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
3374 continue;
3375 }
3376 string strCommand = hdr.GetCommand();
3377
3378 // Message size
3379 unsigned int nMessageSize = hdr.nMessageSize;
3380 if (nMessageSize > MAX_SIZE)
3381 {
ea591ead 3382 printf("ProcessMessages(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
e89b9f6a
PW
3383 continue;
3384 }
3385 if (nMessageSize > vRecv.size())
3386 {
3387 // Rewind and wait for rest of message
3388 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
3389 break;
3390 }
3391
3392 // Checksum
18c0fa97
PW
3393 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
3394 unsigned int nChecksum = 0;
3395 memcpy(&nChecksum, &hash, sizeof(nChecksum));
3396 if (nChecksum != hdr.nChecksum)
e89b9f6a 3397 {
ea591ead 3398 printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
18c0fa97
PW
3399 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
3400 continue;
e89b9f6a
PW
3401 }
3402
3403 // Copy message to its own buffer
3404 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
3405 vRecv.ignore(nMessageSize);
3406
3407 // Process message
3408 bool fRet = false;
3409 try
3410 {
f8dcd5ca
PW
3411 {
3412 LOCK(cs_main);
e89b9f6a 3413 fRet = ProcessMessage(pfrom, strCommand, vMsg);
f8dcd5ca 3414 }
e89b9f6a
PW
3415 if (fShutdown)
3416 return true;
3417 }
3418 catch (std::ios_base::failure& e)
3419 {
3420 if (strstr(e.what(), "end of data"))
3421 {
814efd6f 3422 // Allow exceptions from under-length message on vRecv
ea591ead 3423 printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught, normally caused by a message being shorter than its stated length\n", strCommand.c_str(), nMessageSize, e.what());
e89b9f6a
PW
3424 }
3425 else if (strstr(e.what(), "size too large"))
3426 {
814efd6f 3427 // Allow exceptions from over-long size
ea591ead 3428 printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
e89b9f6a
PW
3429 }
3430 else
3431 {
ea591ead 3432 PrintExceptionContinue(&e, "ProcessMessages()");
e89b9f6a
PW
3433 }
3434 }
3435 catch (std::exception& e) {
ea591ead 3436 PrintExceptionContinue(&e, "ProcessMessages()");
e89b9f6a 3437 } catch (...) {
ea591ead 3438 PrintExceptionContinue(NULL, "ProcessMessages()");
e89b9f6a
PW
3439 }
3440
3441 if (!fRet)
3442 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
3443 }
3444
3445 vRecv.Compact();
3446 return true;
3447}
0a61b0df 3448
3449
0a61b0df 3450bool SendMessages(CNode* pto, bool fSendTrickle)
3451{
c581cc16
PW
3452 TRY_LOCK(cs_main, lockMain);
3453 if (lockMain) {
0a61b0df 3454 // Don't send anything until we get their version message
3455 if (pto->nVersion == 0)
3456 return true;
3457
6d64a0bf 3458 // Keep-alive ping. We send a nonce of zero because we don't use it anywhere
93e447b6
JG
3459 // right now.
3460 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty()) {
c971112d 3461 uint64 nonce = 0;
93e447b6 3462 if (pto->nVersion > BIP0031_VERSION)
c971112d 3463 pto->PushMessage("ping", nonce);
93e447b6
JG
3464 else
3465 pto->PushMessage("ping");
3466 }
0a61b0df 3467
c891967b 3468 // Resend wallet transactions that haven't gotten in a block yet
3469 ResendWalletTransactions();
3470
0a61b0df 3471 // Address refresh broadcast
bde280b9 3472 static int64 nLastRebroadcast;
5d1b8f17 3473 if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
0a61b0df 3474 {
0a61b0df 3475 {
f8dcd5ca 3476 LOCK(cs_vNodes);
223b6f1b 3477 BOOST_FOREACH(CNode* pnode, vNodes)
0a61b0df 3478 {
3479 // Periodically clear setAddrKnown to allow refresh broadcasts
5d1b8f17
GM
3480 if (nLastRebroadcast)
3481 pnode->setAddrKnown.clear();
0a61b0df 3482
3483 // Rebroadcast our address
587f929c 3484 if (!fNoListen)
c891967b 3485 {
39857190
PW
3486 CAddress addr = GetLocalAddress(&pnode->addr);
3487 if (addr.IsRoutable())
3488 pnode->PushAddress(addr);
c891967b 3489 }
0a61b0df 3490 }
3491 }
5d1b8f17 3492 nLastRebroadcast = GetTime();
0a61b0df 3493 }
3494
0a61b0df 3495 //
3496 // Message: addr
3497 //
3498 if (fSendTrickle)
3499 {
3500 vector<CAddress> vAddr;
3501 vAddr.reserve(pto->vAddrToSend.size());
223b6f1b 3502 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
0a61b0df 3503 {
3504 // returns true if wasn't already contained in the set
3505 if (pto->setAddrKnown.insert(addr).second)
3506 {
3507 vAddr.push_back(addr);
3508 // receiver rejects addr messages larger than 1000
3509 if (vAddr.size() >= 1000)
3510 {
3511 pto->PushMessage("addr", vAddr);
3512 vAddr.clear();
3513 }
3514 }
3515 }
3516 pto->vAddrToSend.clear();
3517 if (!vAddr.empty())
3518 pto->PushMessage("addr", vAddr);
3519 }
3520
3521
3522 //
3523 // Message: inventory
3524 //
3525 vector<CInv> vInv;
3526 vector<CInv> vInvWait;
0a61b0df 3527 {
f8dcd5ca 3528 LOCK(pto->cs_inventory);
0a61b0df 3529 vInv.reserve(pto->vInventoryToSend.size());
3530 vInvWait.reserve(pto->vInventoryToSend.size());
223b6f1b 3531 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
0a61b0df 3532 {
3533 if (pto->setInventoryKnown.count(inv))
3534 continue;
3535
3536 // trickle out tx inv to protect privacy
3537 if (inv.type == MSG_TX && !fSendTrickle)
3538 {
3539 // 1/4 of tx invs blast to all immediately
3540 static uint256 hashSalt;
3541 if (hashSalt == 0)
f718aedd 3542 hashSalt = GetRandHash();
0a61b0df 3543 uint256 hashRand = inv.hash ^ hashSalt;
3544 hashRand = Hash(BEGIN(hashRand), END(hashRand));
3545 bool fTrickleWait = ((hashRand & 3) != 0);
3546
3547 // always trickle our own transactions
3548 if (!fTrickleWait)
3549 {
64c7ee7e
PW
3550 CWalletTx wtx;
3551 if (GetTransaction(inv.hash, wtx))
3552 if (wtx.fFromMe)
3553 fTrickleWait = true;
0a61b0df 3554 }
3555
3556 if (fTrickleWait)
3557 {
3558 vInvWait.push_back(inv);
3559 continue;
3560 }
3561 }
3562
3563 // returns true if wasn't already contained in the set
3564 if (pto->setInventoryKnown.insert(inv).second)
3565 {
3566 vInv.push_back(inv);
3567 if (vInv.size() >= 1000)
3568 {
3569 pto->PushMessage("inv", vInv);
3570 vInv.clear();
3571 }
3572 }
3573 }
3574 pto->vInventoryToSend = vInvWait;
3575 }
3576 if (!vInv.empty())
3577 pto->PushMessage("inv", vInv);
3578
3579
3580 //
3581 // Message: getdata
3582 //
3583 vector<CInv> vGetData;
bde280b9 3584 int64 nNow = GetTime() * 1000000;
0a61b0df 3585 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
3586 {
3587 const CInv& inv = (*pto->mapAskFor.begin()).second;
ae8bfd12 3588 if (!AlreadyHave(inv))
0a61b0df 3589 {
d07eaba1
JG
3590 if (fDebugNet)
3591 printf("sending getdata: %s\n", inv.ToString().c_str());
0a61b0df 3592 vGetData.push_back(inv);
3593 if (vGetData.size() >= 1000)
3594 {
3595 pto->PushMessage("getdata", vGetData);
3596 vGetData.clear();
3597 }
757cec9d 3598 mapAlreadyAskedFor[inv] = nNow;
0a61b0df 3599 }
3600 pto->mapAskFor.erase(pto->mapAskFor.begin());
3601 }
3602 if (!vGetData.empty())
3603 pto->PushMessage("getdata", vGetData);
3604
3605 }
3606 return true;
3607}
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622//////////////////////////////////////////////////////////////////////////////
3623//
3624// BitcoinMiner
3625//
3626
64c7ee7e 3627int static FormatHashBlocks(void* pbuffer, unsigned int len)
3df62878 3628{
3629 unsigned char* pdata = (unsigned char*)pbuffer;
3630 unsigned int blocks = 1 + ((len + 8) / 64);
3631 unsigned char* pend = pdata + 64 * blocks;
3632 memset(pdata + len, 0, 64 * blocks - len);
3633 pdata[len] = 0x80;
3634 unsigned int bits = len * 8;
3635 pend[-1] = (bits >> 0) & 0xff;
3636 pend[-2] = (bits >> 8) & 0xff;
3637 pend[-3] = (bits >> 16) & 0xff;
3638 pend[-4] = (bits >> 24) & 0xff;
3639 return blocks;
3640}
3641
3df62878 3642static const unsigned int pSHA256InitState[8] =
3643{0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
3644
6ccff2cb 3645void SHA256Transform(void* pstate, void* pinput, const void* pinit)
3df62878 3646{
6ccff2cb
NS
3647 SHA256_CTX ctx;
3648 unsigned char data[64];
3649
3650 SHA256_Init(&ctx);
3651
3652 for (int i = 0; i < 16; i++)
3653 ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);
3654
3655 for (int i = 0; i < 8; i++)
3656 ctx.h[i] = ((uint32_t*)pinit)[i];
3657
3658 SHA256_Update(&ctx, data, sizeof(data));
6d64a0bf 3659 for (int i = 0; i < 8; i++)
6ccff2cb 3660 ((uint32_t*)pstate)[i] = ctx.h[i];
3df62878 3661}
3662
3663//
3664// ScanHash scans nonces looking for a hash with at least some zero bits.
3665// It operates on big endian data. Caller does the byte reversing.
3666// All input buffers are 16-byte aligned. nNonce is usually preserved
776d0f34 3667// between calls, but periodically or if nNonce is 0xffff0000 or above,
3df62878 3668// the block is rebuilt and nNonce starts over at zero.
3669//
64c7ee7e 3670unsigned int static ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)
3df62878 3671{
776d0f34 3672 unsigned int& nNonce = *(unsigned int*)(pdata + 12);
3df62878 3673 for (;;)
3674 {
814efd6f 3675 // Crypto++ SHA256
776d0f34 3676 // Hash pdata using pmidstate as the starting state into
814efd6f 3677 // pre-formatted buffer phash1, then hash phash1 into phash
3df62878 3678 nNonce++;
776d0f34 3679 SHA256Transform(phash1, pdata, pmidstate);
3df62878 3680 SHA256Transform(phash, phash1, pSHA256InitState);
3681
3682 // Return the nonce if the hash has at least some zero bits,
3683 // caller will check if it has enough to reach the target
3684 if (((unsigned short*)phash)[14] == 0)
3685 return nNonce;
3686
3687 // If nothing found after trying for a while, return -1
3688 if ((nNonce & 0xffff) == 0)
3689 {
3690 nHashesDone = 0xffff+1;
1d8c7a95 3691 return (unsigned int) -1;
3df62878 3692 }
3693 }
3694}
3695
d0d9486f 3696// Some explaining would be appreciated
683bcb91 3697class COrphan
3698{
3699public:
3700 CTransaction* ptx;
3701 set<uint256> setDependsOn;
3702 double dPriority;
c555400c 3703 double dFeePerKb;
683bcb91 3704
3705 COrphan(CTransaction* ptxIn)
3706 {
3707 ptx = ptxIn;
c555400c 3708 dPriority = dFeePerKb = 0;
683bcb91 3709 }
3710
3711 void print() const
3712 {
c555400c
GA
3713 printf("COrphan(hash=%s, dPriority=%.1f, dFeePerKb=%.1f)\n",
3714 ptx->GetHash().ToString().substr(0,10).c_str(), dPriority, dFeePerKb);
223b6f1b 3715 BOOST_FOREACH(uint256 hash, setDependsOn)
683bcb91 3716 printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
3717 }
3718};
3719
3720
340f0876
LD
3721uint64 nLastBlockTx = 0;
3722uint64 nLastBlockSize = 0;
3723
c555400c
GA
3724// We want to sort transactions by priority and fee, so:
3725typedef boost::tuple<double, double, CTransaction*> TxPriority;
3726class TxPriorityCompare
3727{
3728 bool byFee;
3729public:
3730 TxPriorityCompare(bool _byFee) : byFee(_byFee) { }
3731 bool operator()(const TxPriority& a, const TxPriority& b)
3732 {
3733 if (byFee)
3734 {
3735 if (a.get<1>() == b.get<1>())
3736 return a.get<0>() < b.get<0>();
3737 return a.get<1>() < b.get<1>();
3738 }
3739 else
3740 {
3741 if (a.get<0>() == b.get<0>())
3742 return a.get<1>() < b.get<1>();
3743 return a.get<0>() < b.get<0>();
3744 }
3745 }
3746};
3747
3cd01fdf
LD
3748const char* pszDummy = "\0\0";
3749CScript scriptDummy(std::vector<unsigned char>(pszDummy, pszDummy + sizeof(pszDummy)));
3750
776d0f34 3751CBlock* CreateNewBlock(CReserveKey& reservekey)
3752{
3753 CBlockIndex* pindexPrev = pindexBest;
3754
3755 // Create new block
3756 auto_ptr<CBlock> pblock(new CBlock());
3757 if (!pblock.get())
3758 return NULL;
3759
3760 // Create coinbase tx
3761 CTransaction txNew;
3762 txNew.vin.resize(1);
3763 txNew.vin[0].prevout.SetNull();
3764 txNew.vout.resize(1);
3765 txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
3766
3767 // Add our coinbase tx as first transaction
3768 pblock->vtx.push_back(txNew);
3769
c555400c
GA
3770 // Largest block you're willing to create:
3771 unsigned int nBlockMaxSize = GetArg("-blockmaxsize", MAX_BLOCK_SIZE_GEN/2);
3772 // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity:
3773 nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize));
3774
3775 // How much of the block should be dedicated to high-priority transactions,
3776 // included regardless of the fees they pay
3777 unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", 27000);
3778 nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
3779
3780 // Minimum block size you want to create; block will be filled with free transactions
3781 // until there are no more or the block reaches this size:
3782 unsigned int nBlockMinSize = GetArg("-blockminsize", 0);
3783 nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);
3784
3785 // Fee-per-kilobyte amount considered the same as "free"
3786 // Be careful setting this: if you set it to zero then
3787 // a transaction spammer can cheaply fill blocks using
3788 // 1-satoshi-fee transactions. It should be set above the real
3789 // cost to you of processing a transaction.
3790 int64 nMinTxFee = MIN_TX_FEE;
3791 if (mapArgs.count("-mintxfee"))
3792 ParseMoney(mapArgs["-mintxfee"], nMinTxFee);
3793
776d0f34 3794 // Collect memory pool transactions into the block
bde280b9 3795 int64 nFees = 0;
776d0f34 3796 {
235507ae 3797 LOCK2(cs_main, mempool.cs);
ae8bfd12 3798 CCoinsViewCache view(*pcoinsTip, true);
776d0f34 3799
3800 // Priority order to process transactions
3801 list<COrphan> vOrphan; // list memory doesn't move
3802 map<uint256, vector<COrphan*> > mapDependers;
c555400c
GA
3803
3804 // This vector will be sorted into a priority queue:
3805 vector<TxPriority> vecPriority;
3806 vecPriority.reserve(mempool.mapTx.size());
235507ae 3807 for (map<uint256, CTransaction>::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi)
776d0f34 3808 {
3809 CTransaction& tx = (*mi).second;
3810 if (tx.IsCoinBase() || !tx.IsFinal())
3811 continue;
3812
3813 COrphan* porphan = NULL;
3814 double dPriority = 0;
c555400c 3815 int64 nTotalIn = 0;
e0e54740 3816 bool fMissingInputs = false;
223b6f1b 3817 BOOST_FOREACH(const CTxIn& txin, tx.vin)
776d0f34 3818 {
3819 // Read prev transaction
450cbb09
PW
3820 CCoins coins;
3821 if (!view.GetCoins(txin.prevout.hash, coins))
776d0f34 3822 {
e0e54740
GA
3823 // This should never happen; all transactions in the memory
3824 // pool should connect to either transactions in the chain
3825 // or other transactions in the memory pool.
3826 if (!mempool.mapTx.count(txin.prevout.hash))
3827 {
3828 printf("ERROR: mempool transaction missing input\n");
3829 if (fDebug) assert("mempool transaction missing input" == 0);
3830 fMissingInputs = true;
3831 if (porphan)
3832 vOrphan.pop_back();
3833 break;
3834 }
3835
776d0f34 3836 // Has to wait for dependencies
3837 if (!porphan)
3838 {
3839 // Use list for automatic deletion
3840 vOrphan.push_back(COrphan(&tx));
3841 porphan = &vOrphan.back();
3842 }
3843 mapDependers[txin.prevout.hash].push_back(porphan);
3844 porphan->setDependsOn.insert(txin.prevout.hash);
c555400c 3845 nTotalIn += mempool.mapTx[txin.prevout.hash].vout[txin.prevout.n].nValue;
776d0f34 3846 continue;
3847 }
450cbb09
PW
3848
3849 int64 nValueIn = coins.vout[txin.prevout.n].nValue;
c555400c 3850 nTotalIn += nValueIn;
776d0f34 3851
1e64c2d5 3852 int nConf = pindexPrev->nHeight - coins.nHeight + 1;
450cbb09 3853
776d0f34 3854 dPriority += (double)nValueIn * nConf;
776d0f34 3855 }
e0e54740 3856 if (fMissingInputs) continue;
776d0f34 3857
3858 // Priority is sum(valuein * age) / txsize
c555400c
GA
3859 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
3860 dPriority /= nTxSize;
776d0f34 3861
c555400c
GA
3862 // This is a more accurate fee-per-kilobyte than is used by the client code, because the
3863 // client code rounds up the size to the nearest 1K. That's good, because it gives an
3864 // incentive to create smaller transactions.
3865 double dFeePerKb = double(nTotalIn-tx.GetValueOut()) / (double(nTxSize)/1000.0);
776d0f34 3866
c555400c 3867 if (porphan)
776d0f34 3868 {
c555400c
GA
3869 porphan->dPriority = dPriority;
3870 porphan->dFeePerKb = dFeePerKb;
776d0f34 3871 }
c555400c
GA
3872 else
3873 vecPriority.push_back(TxPriority(dPriority, dFeePerKb, &(*mi).second));
776d0f34 3874 }
3875
3876 // Collect transactions into block
bde280b9 3877 uint64 nBlockSize = 1000;
340f0876 3878 uint64 nBlockTx = 0;
137d0685 3879 int nBlockSigOps = 100;
c555400c
GA
3880 bool fSortedByFee = (nBlockPrioritySize <= 0);
3881
3882 TxPriorityCompare comparer(fSortedByFee);
3883 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
3884
3885 while (!vecPriority.empty())
776d0f34 3886 {
c555400c
GA
3887 // Take highest priority transaction off the priority queue:
3888 double dPriority = vecPriority.front().get<0>();
3889 double dFeePerKb = vecPriority.front().get<1>();
3890 CTransaction& tx = *(vecPriority.front().get<2>());
3891
3892 std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
3893 vecPriority.pop_back();
776d0f34 3894
450cbb09
PW
3895 // second layer cached modifications just for this transaction
3896 CCoinsViewCache viewTemp(view, true);
3897
776d0f34 3898 // Size limits
6b6aaa16 3899 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
c555400c 3900 if (nBlockSize + nTxSize >= nBlockMaxSize)
776d0f34 3901 continue;
776d0f34 3902
922e8e29 3903 // Legacy limits on sigOps:
7bd9c3a3 3904 unsigned int nTxSigOps = tx.GetLegacySigOpCount();
137d0685 3905 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
922e8e29
GA
3906 continue;
3907
c555400c
GA
3908 // Skip free transactions if we're past the minimum block size:
3909 if (fSortedByFee && (dFeePerKb < nMinTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))
3910 continue;
3911
3912 // Prioritize by fee once past the priority size or we run out of high-priority
3913 // transactions:
3914 if (!fSortedByFee &&
3915 ((nBlockSize + nTxSize >= nBlockPrioritySize) || (dPriority < COIN * 144 / 250)))
3916 {
3917 fSortedByFee = true;
3918 comparer = TxPriorityCompare(fSortedByFee);
3919 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
3920 }
776d0f34 3921
13c51f20 3922 if (!tx.HaveInputs(viewTemp))
e679ec96 3923 continue;
922e8e29 3924
450cbb09 3925 int64 nTxFees = tx.GetValueIn(viewTemp)-tx.GetValueOut();
8d7849b6 3926
450cbb09 3927 nTxSigOps += tx.GetP2SHSigOpCount(viewTemp);
137d0685 3928 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
776d0f34 3929 continue;
8d7849b6 3930
13c51f20
PW
3931 if (!tx.CheckInputs(viewTemp, CS_ALWAYS, true, false))
3932 continue;
3933
450cbb09 3934 CTxUndo txundo;
64dd46fd
PW
3935 uint256 hash = tx.GetHash();
3936 if (!tx.UpdateCoins(viewTemp, txundo, pindexPrev->nHeight+1, hash))
8d7849b6 3937 continue;
450cbb09
PW
3938
3939 // push changes from the second layer cache to the first one
3940 viewTemp.Flush();
776d0f34 3941
3942 // Added
3943 pblock->vtx.push_back(tx);
3944 nBlockSize += nTxSize;
340f0876 3945 ++nBlockTx;
137d0685 3946 nBlockSigOps += nTxSigOps;
68649bef 3947 nFees += nTxFees;
776d0f34 3948
c555400c
GA
3949 if (fDebug && GetBoolArg("-printpriority"))
3950 {
3951 printf("priority %.1f feeperkb %.1f txid %s\n",
3952 dPriority, dFeePerKb, tx.GetHash().ToString().c_str());
3953 }
3954
776d0f34 3955 // Add transactions that depend on this one to the priority queue
776d0f34 3956 if (mapDependers.count(hash))
3957 {
223b6f1b 3958 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
776d0f34 3959 {
3960 if (!porphan->setDependsOn.empty())
3961 {
3962 porphan->setDependsOn.erase(hash);
3963 if (porphan->setDependsOn.empty())
c555400c
GA
3964 {
3965 vecPriority.push_back(TxPriority(porphan->dPriority, porphan->dFeePerKb, porphan->ptx));
3966 std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
3967 }
776d0f34 3968 }
3969 }
3970 }
3971 }
340f0876
LD
3972
3973 nLastBlockTx = nBlockTx;
3974 nLastBlockSize = nBlockSize;
d210f4f5 3975 printf("CreateNewBlock(): total size %"PRI64u"\n", nBlockSize);
340f0876 3976
450cbb09 3977 pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);
776d0f34 3978
450cbb09
PW
3979 // Fill in header
3980 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
3981 pblock->UpdateTime(pindexPrev);
3982 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock.get());
3983 pblock->nNonce = 0;
3cd01fdf 3984 pblock->vtx[0].vin[0].scriptSig = scriptDummy;
450cbb09 3985
630fd8dc 3986 CBlockIndex indexDummy(*pblock);
3cd01fdf
LD
3987 indexDummy.pprev = pindexPrev;
3988 indexDummy.nHeight = pindexPrev->nHeight + 1;
ae8bfd12 3989 CCoinsViewCache viewNew(*pcoinsTip, true);
450cbb09 3990 if (!pblock->ConnectBlock(&indexDummy, viewNew, true))
3cd01fdf
LD
3991 throw std::runtime_error("CreateNewBlock() : ConnectBlock failed");
3992 }
3993
776d0f34 3994 return pblock.release();
3995}
3996
3997
83f4cd15 3998void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
776d0f34 3999{
4000 // Update nExtraNonce
02d87b3a
LD
4001 static uint256 hashPrevBlock;
4002 if (hashPrevBlock != pblock->hashPrevBlock)
776d0f34 4003 {
02d87b3a
LD
4004 nExtraNonce = 0;
4005 hashPrevBlock = pblock->hashPrevBlock;
776d0f34 4006 }
02d87b3a 4007 ++nExtraNonce;
de237cbf
GA
4008 unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
4009 pblock->vtx[0].vin[0].scriptSig = (CScript() << nHeight << CBigNum(nExtraNonce)) + COINBASE_FLAGS;
d7062ef1
GA
4010 assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100);
4011
776d0f34 4012 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
4013}
4014
4015
4016void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
4017{
4018 //
814efd6f 4019 // Pre-build hash buffers
776d0f34 4020 //
4021 struct
4022 {
4023 struct unnamed2
4024 {
4025 int nVersion;
4026 uint256 hashPrevBlock;
4027 uint256 hashMerkleRoot;
4028 unsigned int nTime;
4029 unsigned int nBits;
4030 unsigned int nNonce;
4031 }
4032 block;
4033 unsigned char pchPadding0[64];
4034 uint256 hash1;
4035 unsigned char pchPadding1[64];
4036 }
4037 tmp;
4038 memset(&tmp, 0, sizeof(tmp));
4039
4040 tmp.block.nVersion = pblock->nVersion;
4041 tmp.block.hashPrevBlock = pblock->hashPrevBlock;
4042 tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
4043 tmp.block.nTime = pblock->nTime;
4044 tmp.block.nBits = pblock->nBits;
4045 tmp.block.nNonce = pblock->nNonce;
4046
4047 FormatHashBlocks(&tmp.block, sizeof(tmp.block));
4048 FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
4049
4050 // Byte swap all the input buffer
c376ac35 4051 for (unsigned int i = 0; i < sizeof(tmp)/4; i++)
776d0f34 4052 ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
4053
4054 // Precalc the first half of the first hash, which stays constant
4055 SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
4056
4057 memcpy(pdata, &tmp.block, 128);
4058 memcpy(phash1, &tmp.hash1, 64);
4059}
4060
4061
64c7ee7e 4062bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
776d0f34 4063{
4064 uint256 hash = pblock->GetHash();
4065 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
4066
4067 if (hash > hashTarget)
4068 return false;
4069
4070 //// debug print
4071 printf("BitcoinMiner:\n");
4072 printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
4073 pblock->print();
776d0f34 4074 printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
4075
4076 // Found a solution
776d0f34 4077 {
f8dcd5ca 4078 LOCK(cs_main);
776d0f34 4079 if (pblock->hashPrevBlock != hashBestChain)
4080 return error("BitcoinMiner : generated block is stale");
4081
4082 // Remove key from key pool
4083 reservekey.KeepKey();
4084
4085 // Track how many getdata requests this block gets
f8dcd5ca
PW
4086 {
4087 LOCK(wallet.cs_wallet);
64c7ee7e 4088 wallet.mapRequestCount[pblock->GetHash()] = 0;
f8dcd5ca 4089 }
776d0f34 4090
4091 // Process this block the same as if we had received it from another node
4092 if (!ProcessBlock(NULL, pblock))
4093 return error("BitcoinMiner : ProcessBlock, block not accepted");
4094 }
4095
776d0f34 4096 return true;
4097}
4098
64c7ee7e
PW
4099void static ThreadBitcoinMiner(void* parg);
4100
972060ce
GA
4101static bool fGenerateBitcoins = false;
4102static bool fLimitProcessors = false;
4103static int nLimitProcessors = -1;
4104
64c7ee7e 4105void static BitcoinMiner(CWallet *pwallet)
0a61b0df 4106{
4107 printf("BitcoinMiner started\n");
4108 SetThreadPriority(THREAD_PRIORITY_LOWEST);
4109
96931d6f 4110 // Make this thread recognisable as the mining thread
9f46ab62 4111 RenameThread("bitcoin-miner");
96931d6f 4112
776d0f34 4113 // Each thread has its own key and counter
64c7ee7e 4114 CReserveKey reservekey(pwallet);
5cbf7532 4115 unsigned int nExtraNonce = 0;
776d0f34 4116
0a61b0df 4117 while (fGenerateBitcoins)
4118 {
0a61b0df 4119 if (fShutdown)
4120 return;
4121 while (vNodes.empty() || IsInitialBlockDownload())
4122 {
4123 Sleep(1000);
4124 if (fShutdown)
4125 return;
4126 if (!fGenerateBitcoins)
4127 return;
4128 }
4129
0a61b0df 4130
4131 //
4132 // Create new block
4133 //
776d0f34 4134 unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
4135 CBlockIndex* pindexPrev = pindexBest;
4136
4137 auto_ptr<CBlock> pblock(CreateNewBlock(reservekey));
0a61b0df 4138 if (!pblock.get())
4139 return;
83f4cd15 4140 IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce);
0a61b0df 4141
d210f4f5 4142 printf("Running BitcoinMiner with %"PRIszu" transactions in block (%u bytes)\n", pblock->vtx.size(),
c555400c 4143 ::GetSerializeSize(*pblock, SER_NETWORK, PROTOCOL_VERSION));
0a61b0df 4144
4145
4146 //
814efd6f 4147 // Pre-build hash buffers
0a61b0df 4148 //
776d0f34 4149 char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
4150 char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf);
4151 char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf);
4152
4153 FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1);
4154
4155 unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
0f8cb5db 4156 unsigned int& nBlockBits = *(unsigned int*)(pdata + 64 + 8);
776d0f34 4157 unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
0a61b0df 4158
4159
4160 //
4161 // Search
4162 //
bde280b9 4163 int64 nStart = GetTime();
0a61b0df 4164 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
4165 uint256 hashbuf[2];
4166 uint256& hash = *alignup<16>(hashbuf);
4167 loop
4168 {
3df62878 4169 unsigned int nHashesDone = 0;
4170 unsigned int nNonceFound;
4171
814efd6f 4172 // Crypto++ SHA256
b26141e2
JG
4173 nNonceFound = ScanHash_CryptoPP(pmidstate, pdata + 64, phash1,
4174 (char*)&hash, nHashesDone);
0a61b0df 4175
3df62878 4176 // Check if something found
1d8c7a95 4177 if (nNonceFound != (unsigned int) -1)
0a61b0df 4178 {
c376ac35 4179 for (unsigned int i = 0; i < sizeof(hash)/4; i++)
0a61b0df 4180 ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
4181
4182 if (hash <= hashTarget)
4183 {
3df62878 4184 // Found a solution
4185 pblock->nNonce = ByteReverse(nNonceFound);
0a61b0df 4186 assert(hash == pblock->GetHash());
4187
0a61b0df 4188 SetThreadPriority(THREAD_PRIORITY_NORMAL);
64c7ee7e 4189 CheckWork(pblock.get(), *pwalletMain, reservekey);
0a61b0df 4190 SetThreadPriority(THREAD_PRIORITY_LOWEST);
0a61b0df 4191 break;
4192 }
4193 }
4194
3df62878 4195 // Meter hashes/sec
bde280b9 4196 static int64 nHashCounter;
3df62878 4197 if (nHPSTimerStart == 0)
0a61b0df 4198 {
3df62878 4199 nHPSTimerStart = GetTimeMillis();
4200 nHashCounter = 0;
4201 }
4202 else
4203 nHashCounter += nHashesDone;
4204 if (GetTimeMillis() - nHPSTimerStart > 4000)
4205 {
4206 static CCriticalSection cs;
0a61b0df 4207 {
f8dcd5ca 4208 LOCK(cs);
3df62878 4209 if (GetTimeMillis() - nHPSTimerStart > 4000)
0a61b0df 4210 {
3df62878 4211 dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
4212 nHPSTimerStart = GetTimeMillis();
4213 nHashCounter = 0;
bde280b9 4214 static int64 nLogTime;
3df62878 4215 if (GetTime() - nLogTime > 30 * 60)
0a61b0df 4216 {
3df62878 4217 nLogTime = GetTime();
c59881ea 4218 printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[THREAD_MINER], dHashesPerSec/1000.0);
0a61b0df 4219 }
4220 }
4221 }
3df62878 4222 }
0a61b0df 4223
3df62878 4224 // Check for stop or if block needs to be rebuilt
4225 if (fShutdown)
4226 return;
4227 if (!fGenerateBitcoins)
4228 return;
c59881ea 4229 if (fLimitProcessors && vnThreadsRunning[THREAD_MINER] > nLimitProcessors)
3df62878 4230 return;
4231 if (vNodes.empty())
4232 break;
776d0f34 4233 if (nBlockNonce >= 0xffff0000)
3df62878 4234 break;
4235 if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
4236 break;
4237 if (pindexPrev != pindexBest)
4238 break;
0a61b0df 4239
3df62878 4240 // Update nTime every few seconds
0f8cb5db 4241 pblock->UpdateTime(pindexPrev);
776d0f34 4242 nBlockTime = ByteReverse(pblock->nTime);
0f8cb5db
GA
4243 if (fTestNet)
4244 {
4245 // Changing pblock->nTime can change work required on testnet:
4246 nBlockBits = ByteReverse(pblock->nBits);
4247 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
4248 }
0a61b0df 4249 }
4250 }
4251}
4252
64c7ee7e 4253void static ThreadBitcoinMiner(void* parg)
0a61b0df 4254{
64c7ee7e 4255 CWallet* pwallet = (CWallet*)parg;
e89b9f6a 4256 try
0a61b0df 4257 {
c59881ea 4258 vnThreadsRunning[THREAD_MINER]++;
64c7ee7e 4259 BitcoinMiner(pwallet);
c59881ea 4260 vnThreadsRunning[THREAD_MINER]--;
aca3f961 4261 }
e89b9f6a 4262 catch (std::exception& e) {
c59881ea 4263 vnThreadsRunning[THREAD_MINER]--;
e89b9f6a
PW
4264 PrintException(&e, "ThreadBitcoinMiner()");
4265 } catch (...) {
c59881ea 4266 vnThreadsRunning[THREAD_MINER]--;
e89b9f6a 4267 PrintException(NULL, "ThreadBitcoinMiner()");
0a61b0df 4268 }
e89b9f6a 4269 nHPSTimerStart = 0;
c59881ea 4270 if (vnThreadsRunning[THREAD_MINER] == 0)
e89b9f6a 4271 dHashesPerSec = 0;
c59881ea 4272 printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[THREAD_MINER]);
e2a186af 4273}
4274
0a61b0df 4275
64c7ee7e 4276void GenerateBitcoins(bool fGenerate, CWallet* pwallet)
0a61b0df 4277{
972060ce
GA
4278 fGenerateBitcoins = fGenerate;
4279 nLimitProcessors = GetArg("-genproclimit", -1);
4280 if (nLimitProcessors == 0)
4281 fGenerateBitcoins = false;
4282 fLimitProcessors = (nLimitProcessors != -1);
4283
4284 if (fGenerate)
0a61b0df 4285 {
e89b9f6a
PW
4286 int nProcessors = boost::thread::hardware_concurrency();
4287 printf("%d processors\n", nProcessors);
4288 if (nProcessors < 1)
4289 nProcessors = 1;
4290 if (fLimitProcessors && nProcessors > nLimitProcessors)
4291 nProcessors = nLimitProcessors;
c59881ea 4292 int nAddThreads = nProcessors - vnThreadsRunning[THREAD_MINER];
e89b9f6a
PW
4293 printf("Starting %d BitcoinMiner threads\n", nAddThreads);
4294 for (int i = 0; i < nAddThreads; i++)
0a61b0df 4295 {
4d1d94c5
WL
4296 if (!NewThread(ThreadBitcoinMiner, pwallet))
4297 printf("Error: NewThread(ThreadBitcoinMiner) failed\n");
e89b9f6a 4298 Sleep(10);
0a61b0df 4299 }
f5f1878b 4300 }
0a61b0df 4301}
0fa593d0
PW
4302
4303// Amount compression:
4304// * If the amount is 0, output 0
4305// * first, divide the amount (in base units) by the largest power of 10 possible; call the exponent e (e is max 9)
4306// * if e<9, the last digit of the resulting number cannot be 0; store it as d, and drop it (divide by 10)
4307// * call the result n
4308// * output 1 + 10*(9*n + d - 1) + e
4309// * if e==9, we only know the resulting number is not zero, so output 1 + 10*(n - 1) + 9
4310// (this is decodable, as d is in [1-9] and e is in [0-9])
4311
4312uint64 CTxOutCompressor::CompressAmount(uint64 n)
4313{
4314 if (n == 0)
4315 return 0;
4316 int e = 0;
4317 while (((n % 10) == 0) && e < 9) {
4318 n /= 10;
4319 e++;
4320 }
4321 if (e < 9) {
4322 int d = (n % 10);
4323 assert(d >= 1 && d <= 9);
4324 n /= 10;
4325 return 1 + (n*9 + d - 1)*10 + e;
4326 } else {
4327 return 1 + (n - 1)*10 + 9;
4328 }
4329}
4330
4331uint64 CTxOutCompressor::DecompressAmount(uint64 x)
4332{
4333 // x = 0 OR x = 1+10*(9*n + d - 1) + e OR x = 1+10*(n - 1) + 9
4334 if (x == 0)
4335 return 0;
4336 x--;
4337 // x = 10*(9*n + d - 1) + e
4338 int e = x % 10;
4339 x /= 10;
4340 uint64 n = 0;
4341 if (e < 9) {
4342 // x = 9*n + d - 1
4343 int d = (x % 9) + 1;
4344 x /= 9;
4345 // x = n
4346 n = x*10 + d;
4347 } else {
4348 n = x+1;
4349 }
4350 while (e) {
4351 n *= 10;
4352 e--;
4353 }
4354 return n;
4355}
This page took 0.868039 seconds and 4 git commands to generate.