main.cpp 161 KB
Newer Older
s_nakamoto's avatar
s_nakamoto committed
1
// Copyright (c) 2009-2010 Satoshi Nakamoto
Gavin Andresen's avatar
Gavin Andresen committed
2
// Copyright (c) 2009-2012 The Bitcoin developers
s_nakamoto's avatar
s_nakamoto committed
3
// Distributed under the MIT/X11 software license, see the accompanying
Fordy's avatar
Fordy committed
4
5
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

6
#include "alert.h"
7
#include "checkpoints.h"
8
#include "db.h"
9
#include "txdb.h"
10
#include "net.h"
11
#include "init.h"
Pieter Wuille's avatar
Pieter Wuille committed
12
#include "ui_interface.h"
13
#include "checkqueue.h"
14
#include <boost/algorithm/string/replace.hpp>
15
#include <boost/filesystem.hpp>
16
#include <boost/filesystem/fstream.hpp>
s_nakamoto's avatar
s_nakamoto committed
17

18
19
using namespace std;
using namespace boost;
s_nakamoto's avatar
s_nakamoto committed
20
21
22
23
24

//
// Global state
//

Pieter Wuille's avatar
Pieter Wuille committed
25
26
27
CCriticalSection cs_setpwalletRegistered;
set<CWallet*> setpwalletRegistered;

s_nakamoto's avatar
s_nakamoto committed
28
29
CCriticalSection cs_main;

30
CTxMemPool mempool;
s_nakamoto's avatar
s_nakamoto committed
31
32
33
unsigned int nTransactionsUpdated = 0;

map<uint256, CBlockIndex*> mapBlockIndex;
34
uint256 hashGenesisBlock("0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f");
35
static CBigNum bnProofOfWorkLimit(~uint256(0) >> 32);
s_nakamoto's avatar
s_nakamoto committed
36
37
38
39
40
41
CBlockIndex* pindexGenesisBlock = NULL;
int nBestHeight = -1;
CBigNum bnBestChainWork = 0;
CBigNum bnBestInvalidWork = 0;
uint256 hashBestChain = 0;
CBlockIndex* pindexBest = NULL;
42
set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexValid; // may contain all CBlockIndex*'s that have validness >=BLOCK_VALID_TRANSACTIONS, and must contain those who aren't failed
43
int64 nTimeBestReceived = 0;
44
int nScriptCheckThreads = 0;
45
bool fImporting = false;
46
bool fReindex = false;
47
bool fBenchmark = false;
48
bool fTxIndex = false;
Pieter Wuille's avatar
Pieter Wuille committed
49
unsigned int nCoinCacheSize = 5000;
s_nakamoto's avatar
s_nakamoto committed
50

51
CMedianFilter<int> cPeerBlockCounts(8, 0); // Amount of blocks that other nodes claim to have
52

s_nakamoto's avatar
s_nakamoto committed
53
54
55
56
map<uint256, CBlock*> mapOrphanBlocks;
multimap<uint256, CBlock*> mapOrphanBlocksByPrev;

map<uint256, CDataStream*> mapOrphanTransactions;
57
map<uint256, map<uint256, CDataStream*> > mapOrphanTransactionsByPrev;
s_nakamoto's avatar
s_nakamoto committed
58

59
60
// Constant stuff for coinbase transactions we create:
CScript COINBASE_FLAGS;
s_nakamoto's avatar
s_nakamoto committed
61

62
63
const string strMessageMagic = "Bitcoin Signed Message:\n";

s_nakamoto's avatar
s_nakamoto committed
64
double dHashesPerSec;
65
int64 nHPSTimerStart;
s_nakamoto's avatar
s_nakamoto committed
66
67

// Settings
68
int64 nTransactionFee = 0;
69

70

s_nakamoto's avatar
s_nakamoto committed
71

Pieter Wuille's avatar
Pieter Wuille committed
72
73
74
75
76
//////////////////////////////////////////////////////////////////////////////
//
// dispatching functions
//

Pieter Wuille's avatar
Pieter Wuille committed
77
78
79
// These functions dispatch to one or all registered wallets


Pieter Wuille's avatar
Pieter Wuille committed
80
81
82
void RegisterWallet(CWallet* pwalletIn)
{
    {
83
        LOCK(cs_setpwalletRegistered);
Pieter Wuille's avatar
Pieter Wuille committed
84
85
86
87
88
89
90
        setpwalletRegistered.insert(pwalletIn);
    }
}

void UnregisterWallet(CWallet* pwalletIn)
{
    {
91
        LOCK(cs_setpwalletRegistered);
Pieter Wuille's avatar
Pieter Wuille committed
92
93
94
95
        setpwalletRegistered.erase(pwalletIn);
    }
}

Pieter Wuille's avatar
Pieter Wuille committed
96
// get the wallet transaction with the given hash (if it exists)
Pieter Wuille's avatar
Pieter Wuille committed
97
98
99
100
101
102
103
104
bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
{
    BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
        if (pwallet->GetTransaction(hashTx,wtx))
            return true;
    return false;
}

Pieter Wuille's avatar
Pieter Wuille committed
105
// erases transaction with the given hash from all wallets
Pieter Wuille's avatar
Pieter Wuille committed
106
107
108
109
110
111
void static EraseFromWallets(uint256 hash)
{
    BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
        pwallet->EraseFromWallet(hash);
}

Pieter Wuille's avatar
Pieter Wuille committed
112
// make sure all wallets know about the given transaction, in the given block
Pieter Wuille's avatar
Pieter Wuille committed
113
void SyncWithWallets(const uint256 &hash, const CTransaction& tx, const CBlock* pblock, bool fUpdate)
Pieter Wuille's avatar
Pieter Wuille committed
114
115
{
    BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
Pieter Wuille's avatar
Pieter Wuille committed
116
        pwallet->AddToWalletIfInvolvingMe(hash, tx, pblock, fUpdate);
Pieter Wuille's avatar
Pieter Wuille committed
117
118
}

Pieter Wuille's avatar
Pieter Wuille committed
119
// notify wallets about a new best chain
Pieter Wuille's avatar
Pieter Wuille committed
120
121
122
123
124
125
void static SetBestChain(const CBlockLocator& loc)
{
    BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
        pwallet->SetBestChain(loc);
}

Pieter Wuille's avatar
Pieter Wuille committed
126
// notify wallets about an updated transaction
Pieter Wuille's avatar
Pieter Wuille committed
127
128
129
130
131
132
void static UpdatedTransaction(const uint256& hashTx)
{
    BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
        pwallet->UpdatedTransaction(hashTx);
}

Pieter Wuille's avatar
Pieter Wuille committed
133
// dump all wallets
Pieter Wuille's avatar
Pieter Wuille committed
134
135
136
137
138
139
void static PrintWallets(const CBlock& block)
{
    BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
        pwallet->PrintWallet(block);
}

Pieter Wuille's avatar
Pieter Wuille committed
140
// notify wallets about an incoming inventory (for request counts)
Pieter Wuille's avatar
Pieter Wuille committed
141
142
143
144
145
146
void static Inventory(const uint256& hash)
{
    BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
        pwallet->Inventory(hash);
}

Pieter Wuille's avatar
Pieter Wuille committed
147
// ask wallets to resend their transactions
Pieter Wuille's avatar
Pieter Wuille committed
148
149
150
151
152
153
154
155
156
157
158
159
void static ResendWalletTransactions()
{
    BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
        pwallet->ResendWalletTransactions();
}







Pieter Wuille's avatar
Pieter Wuille committed
160
161
162
163
164
165
166
167
168
169
//////////////////////////////////////////////////////////////////////////////
//
// CCoinsView implementations
//

bool CCoinsView::GetCoins(uint256 txid, CCoins &coins) { return false; }
bool CCoinsView::SetCoins(uint256 txid, const CCoins &coins) { return false; }
bool CCoinsView::HaveCoins(uint256 txid) { return false; }
CBlockIndex *CCoinsView::GetBestBlock() { return NULL; }
bool CCoinsView::SetBestBlock(CBlockIndex *pindex) { return false; }
170
bool CCoinsView::BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex) { return false; }
171
bool CCoinsView::GetStats(CCoinsStats &stats) { return false; }
Pieter Wuille's avatar
Pieter Wuille committed
172

Pieter Wuille's avatar
Pieter Wuille committed
173

Pieter Wuille's avatar
Pieter Wuille committed
174
175
176
177
178
179
180
CCoinsViewBacked::CCoinsViewBacked(CCoinsView &viewIn) : base(&viewIn) { }
bool CCoinsViewBacked::GetCoins(uint256 txid, CCoins &coins) { return base->GetCoins(txid, coins); }
bool CCoinsViewBacked::SetCoins(uint256 txid, const CCoins &coins) { return base->SetCoins(txid, coins); }
bool CCoinsViewBacked::HaveCoins(uint256 txid) { return base->HaveCoins(txid); }
CBlockIndex *CCoinsViewBacked::GetBestBlock() { return base->GetBestBlock(); }
bool CCoinsViewBacked::SetBestBlock(CBlockIndex *pindex) { return base->SetBestBlock(pindex); }
void CCoinsViewBacked::SetBackend(CCoinsView &viewIn) { base = &viewIn; }
181
bool CCoinsViewBacked::BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex) { return base->BatchWrite(mapCoins, pindex); }
182
bool CCoinsViewBacked::GetStats(CCoinsStats &stats) { return base->GetStats(stats); }
Pieter Wuille's avatar
Pieter Wuille committed
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197

CCoinsViewCache::CCoinsViewCache(CCoinsView &baseIn, bool fDummy) : CCoinsViewBacked(baseIn), pindexTip(NULL) { }

bool CCoinsViewCache::GetCoins(uint256 txid, CCoins &coins) {
    if (cacheCoins.count(txid)) {
        coins = cacheCoins[txid];
        return true;
    }
    if (base->GetCoins(txid, coins)) {
        cacheCoins[txid] = coins;
        return true;
    }
    return false;
}

Pieter Wuille's avatar
Pieter Wuille committed
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
std::map<uint256,CCoins>::iterator CCoinsViewCache::FetchCoins(uint256 txid) {
    std::map<uint256,CCoins>::iterator it = cacheCoins.find(txid);
    if (it != cacheCoins.end())
        return it;
    CCoins tmp;
    if (!base->GetCoins(txid,tmp))
        return it;
    std::pair<std::map<uint256,CCoins>::iterator,bool> ret = cacheCoins.insert(std::make_pair(txid, tmp));
    return ret.first;
}

CCoins &CCoinsViewCache::GetCoins(uint256 txid) {
    std::map<uint256,CCoins>::iterator it = FetchCoins(txid);
    assert(it != cacheCoins.end());
    return it->second;
}

Pieter Wuille's avatar
Pieter Wuille committed
215
216
217
218
219
220
bool CCoinsViewCache::SetCoins(uint256 txid, const CCoins &coins) {
    cacheCoins[txid] = coins;
    return true;
}

bool CCoinsViewCache::HaveCoins(uint256 txid) {
Pieter Wuille's avatar
Pieter Wuille committed
221
    return FetchCoins(txid) != cacheCoins.end();
Pieter Wuille's avatar
Pieter Wuille committed
222
223
224
225
226
227
228
229
230
231
232
233
234
}

CBlockIndex *CCoinsViewCache::GetBestBlock() {
    if (pindexTip == NULL)
        pindexTip = base->GetBestBlock();
    return pindexTip;
}

bool CCoinsViewCache::SetBestBlock(CBlockIndex *pindex) {
    pindexTip = pindex;
    return true;
}

235
236
237
238
bool CCoinsViewCache::BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex) {
    for (std::map<uint256, CCoins>::const_iterator it = mapCoins.begin(); it != mapCoins.end(); it++)
        cacheCoins[it->first] = it->second;
    pindexTip = pindex;
Pieter Wuille's avatar
Pieter Wuille committed
239
240
241
    return true;
}

242
243
244
245
246
247
248
249
250
251
252
bool CCoinsViewCache::Flush() {
    bool fOk = base->BatchWrite(cacheCoins, pindexTip);
    if (fOk)
        cacheCoins.clear();
    return fOk;
}

unsigned int CCoinsViewCache::GetCacheSize() {
    return cacheCoins.size();
}

Pieter Wuille's avatar
Pieter Wuille committed
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
/** CCoinsView that brings transactions from a memorypool into view.
    It does not check for spendings by memory pool transactions. */
CCoinsViewMemPool::CCoinsViewMemPool(CCoinsView &baseIn, CTxMemPool &mempoolIn) : CCoinsViewBacked(baseIn), mempool(mempoolIn) { }

bool CCoinsViewMemPool::GetCoins(uint256 txid, CCoins &coins) {
    if (base->GetCoins(txid, coins))
        return true;
    if (mempool.exists(txid)) {
        const CTransaction &tx = mempool.lookup(txid);
        coins = CCoins(tx, MEMPOOL_HEIGHT);
        return true;
    }
    return false;
}

bool CCoinsViewMemPool::HaveCoins(uint256 txid) {
    return mempool.exists(txid) || base->HaveCoins(txid);
}

272
CCoinsViewCache *pcoinsTip = NULL;
273
CBlockTreeDB *pblocktree = NULL;
Pieter Wuille's avatar
Pieter Wuille committed
274

s_nakamoto's avatar
s_nakamoto committed
275
276
277
278
279
//////////////////////////////////////////////////////////////////////////////
//
// mapOrphanTransactions
//

280
bool AddOrphanTx(const CDataStream& vMsg)
s_nakamoto's avatar
s_nakamoto committed
281
282
283
284
285
{
    CTransaction tx;
    CDataStream(vMsg) >> tx;
    uint256 hash = tx.GetHash();
    if (mapOrphanTransactions.count(hash))
286
287
288
        return false;

    CDataStream* pvMsg = new CDataStream(vMsg);
289

290
291
292
293
294
295
296
297
298
    // Ignore big transactions, to avoid a
    // send-big-orphans memory exhaustion attack. If a peer has a legitimate
    // large transaction with a missing parent then we assume
    // it will rebroadcast it later, after the parent transaction(s)
    // have been mined or received.
    // 10,000 orphans, each of which is at most 5,000 bytes big is
    // at most 500 megabytes of orphans:
    if (pvMsg->size() > 5000)
    {
299
        printf("ignoring large orphan tx (size: %"PRIszu", hash: %s)\n", pvMsg->size(), hash.ToString().substr(0,10).c_str());
300
        delete pvMsg;
301
302
        return false;
    }
303

304
    mapOrphanTransactions[hash] = pvMsg;
305
    BOOST_FOREACH(const CTxIn& txin, tx.vin)
306
307
        mapOrphanTransactionsByPrev[txin.prevout.hash].insert(make_pair(hash, pvMsg));

308
    printf("stored orphan tx %s (mapsz %"PRIszu")\n", hash.ToString().substr(0,10).c_str(),
309
310
        mapOrphanTransactions.size());
    return true;
s_nakamoto's avatar
s_nakamoto committed
311
312
}

Pieter Wuille's avatar
Pieter Wuille committed
313
void static EraseOrphanTx(uint256 hash)
s_nakamoto's avatar
s_nakamoto committed
314
315
316
317
318
319
{
    if (!mapOrphanTransactions.count(hash))
        return;
    const CDataStream* pvMsg = mapOrphanTransactions[hash];
    CTransaction tx;
    CDataStream(*pvMsg) >> tx;
320
    BOOST_FOREACH(const CTxIn& txin, tx.vin)
s_nakamoto's avatar
s_nakamoto committed
321
    {
322
323
324
        mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash);
        if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty())
            mapOrphanTransactionsByPrev.erase(txin.prevout.hash);
s_nakamoto's avatar
s_nakamoto committed
325
326
327
328
329
    }
    delete pvMsg;
    mapOrphanTransactions.erase(hash);
}

330
unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
331
{
332
    unsigned int nEvicted = 0;
333
334
335
    while (mapOrphanTransactions.size() > nMaxOrphans)
    {
        // Evict a random orphan:
336
        uint256 randomhash = GetRandHash();
337
338
339
340
341
342
343
344
        map<uint256, CDataStream*>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
        if (it == mapOrphanTransactions.end())
            it = mapOrphanTransactions.begin();
        EraseOrphanTx(it->first);
        ++nEvicted;
    }
    return nEvicted;
}
s_nakamoto's avatar
s_nakamoto committed
345
346
347
348
349
350
351
352
353







//////////////////////////////////////////////////////////////////////////////
//
Pieter Wuille's avatar
Pieter Wuille committed
354
// CTransaction
s_nakamoto's avatar
s_nakamoto committed
355
356
//

Gavin Andresen's avatar
Gavin Andresen committed
357
358
bool CTransaction::IsStandard() const
{
359
360
361
    if (nVersion > CTransaction::CURRENT_VERSION)
        return false;

362
363
364
    if (!IsFinal())
        return false;

Gavin Andresen's avatar
Gavin Andresen committed
365
366
    BOOST_FOREACH(const CTxIn& txin, vin)
    {
367
        // Biggest 'standard' txin is a 3-signature 3-of-3 CHECKMULTISIG
368
        // pay-to-script-hash, which is 3 ~80-byte signatures, 3
Gavin Andresen's avatar
Gavin Andresen committed
369
        // ~65-byte public keys, plus a few script ops.
370
        if (txin.scriptSig.size() > 500)
371
            return false;
Gavin Andresen's avatar
Gavin Andresen committed
372
        if (!txin.scriptSig.IsPushOnly())
373
            return false;
Gavin Andresen's avatar
Gavin Andresen committed
374
    }
375
    BOOST_FOREACH(const CTxOut& txout, vout) {
Gavin Andresen's avatar
Gavin Andresen committed
376
        if (!::IsStandard(txout.scriptPubKey))
377
            return false;
378
379
380
        if (txout.nValue == 0)
            return false;
    }
Gavin Andresen's avatar
Gavin Andresen committed
381
382
383
384
385
    return true;
}

//
// Check transaction inputs, and make sure any
386
// pay-to-script-hash transactions are evaluating IsStandard scripts
Gavin Andresen's avatar
Gavin Andresen committed
387
388
//
// Why bother? To avoid denial-of-service attacks; an attacker
389
390
391
// can submit a standard HASH... OP_EQUAL transaction,
// which will get accepted into blocks. The redemption
// script can be anything; an attacker could use a very
Gavin Andresen's avatar
Gavin Andresen committed
392
393
394
// expensive-to-check-upon-redemption script like:
//   DUP CHECKSIG DROP ... repeated 100 times... OP_1
//
Pieter Wuille's avatar
Pieter Wuille committed
395
bool CTransaction::AreInputsStandard(CCoinsViewCache& mapInputs) const
Gavin Andresen's avatar
Gavin Andresen committed
396
{
397
    if (IsCoinBase())
398
        return true; // Coinbases don't use vin normally
399

400
    for (unsigned int i = 0; i < vin.size(); i++)
Gavin Andresen's avatar
Gavin Andresen committed
401
    {
402
        const CTxOut& prev = GetOutputFor(vin[i], mapInputs);
Gavin Andresen's avatar
Gavin Andresen committed
403
404

        vector<vector<unsigned char> > vSolutions;
405
406
        txnouttype whichType;
        // get the scriptPubKey corresponding to this input:
407
        const CScript& prevScript = prev.scriptPubKey;
408
        if (!Solver(prevScript, whichType, vSolutions))
409
            return false;
410
        int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
411
412
        if (nArgsExpected < 0)
            return false;
413
414
415
416
417
418
419

        // Transactions with extra stuff in their scriptSigs are
        // non-standard. Note that this EvalScript() call will
        // be quick, because if there are any operations
        // beside "push data" in the scriptSig the
        // IsStandard() call returns false
        vector<vector<unsigned char> > stack;
420
        if (!EvalScript(stack, vin[i].scriptSig, *this, i, false, 0))
421
422
            return false;

Gavin Andresen's avatar
Gavin Andresen committed
423
424
        if (whichType == TX_SCRIPTHASH)
        {
425
            if (stack.empty())
Gavin Andresen's avatar
Gavin Andresen committed
426
                return false;
427
            CScript subscript(stack.back().begin(), stack.back().end());
428
429
430
            vector<vector<unsigned char> > vSolutions2;
            txnouttype whichType2;
            if (!Solver(subscript, whichType2, vSolutions2))
431
                return false;
432
433
            if (whichType2 == TX_SCRIPTHASH)
                return false;
434
435
436
437
438
439

            int tmpExpected;
            tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
            if (tmpExpected < 0)
                return false;
            nArgsExpected += tmpExpected;
Gavin Andresen's avatar
Gavin Andresen committed
440
        }
441

442
        if (stack.size() != (unsigned int)nArgsExpected)
443
            return false;
Gavin Andresen's avatar
Gavin Andresen committed
444
445
446
447
448
    }

    return true;
}

449
unsigned int
450
451
CTransaction::GetLegacySigOpCount() const
{
452
    unsigned int nSigOps = 0;
453
454
455
456
457
458
459
460
461
462
    BOOST_FOREACH(const CTxIn& txin, vin)
    {
        nSigOps += txin.scriptSig.GetSigOpCount(false);
    }
    BOOST_FOREACH(const CTxOut& txout, vout)
    {
        nSigOps += txout.scriptPubKey.GetSigOpCount(false);
    }
    return nSigOps;
}
s_nakamoto's avatar
s_nakamoto committed
463
464
465
466


int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
{
Pieter Wuille's avatar
Pieter Wuille committed
467
468
469
470
471
472
473
474
475
476
    CBlock blockTmp;

    if (pblock == NULL) {
        CCoins coins;
        if (pcoinsTip->GetCoins(GetHash(), coins)) {
            CBlockIndex *pindex = FindBlockByHeight(coins.nHeight);
            if (pindex) {
                if (!blockTmp.ReadFromDisk(pindex))
                    return 0;
                pblock = &blockTmp;
Pieter Wuille's avatar
Pieter Wuille committed
477
            }
s_nakamoto's avatar
s_nakamoto committed
478
        }
Pieter Wuille's avatar
Pieter Wuille committed
479
    }
s_nakamoto's avatar
s_nakamoto committed
480

Pieter Wuille's avatar
Pieter Wuille committed
481
    if (pblock) {
s_nakamoto's avatar
s_nakamoto committed
482
483
484
485
        // Update the tx's hashBlock
        hashBlock = pblock->GetHash();

        // Locate the transaction
486
        for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++)
s_nakamoto's avatar
s_nakamoto committed
487
488
            if (pblock->vtx[nIndex] == *(CTransaction*)this)
                break;
489
        if (nIndex == (int)pblock->vtx.size())
s_nakamoto's avatar
s_nakamoto committed
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
        {
            vMerkleBranch.clear();
            nIndex = -1;
            printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
            return 0;
        }

        // Fill in merkle branch
        vMerkleBranch = pblock->GetMerkleBranch(nIndex);
    }

    // Is the tx in a block that's in the main chain
    map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
    if (mi == mapBlockIndex.end())
        return 0;
    CBlockIndex* pindex = (*mi).second;
    if (!pindex || !pindex->IsInMainChain())
        return 0;

    return pindexBest->nHeight - pindex->nHeight + 1;
}







Pieter Wuille's avatar
Pieter Wuille committed
518
bool CTransaction::CheckTransaction(CValidationState &state) const
519
520
{
    // Basic checks that don't depend on any context
521
    if (vin.empty())
Pieter Wuille's avatar
Pieter Wuille committed
522
        return state.DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
523
    if (vout.empty())
Pieter Wuille's avatar
Pieter Wuille committed
524
        return state.DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
525
    // Size limits
526
    if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
Pieter Wuille's avatar
Pieter Wuille committed
527
        return state.DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
528
529

    // Check for negative or overflow output values
530
    int64 nValueOut = 0;
531
    BOOST_FOREACH(const CTxOut& txout, vout)
532
533
    {
        if (txout.nValue < 0)
Pieter Wuille's avatar
Pieter Wuille committed
534
            return state.DoS(100, error("CTransaction::CheckTransaction() : txout.nValue negative"));
535
        if (txout.nValue > MAX_MONEY)
Pieter Wuille's avatar
Pieter Wuille committed
536
            return state.DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
537
538
        nValueOut += txout.nValue;
        if (!MoneyRange(nValueOut))
Pieter Wuille's avatar
Pieter Wuille committed
539
            return state.DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
540
541
    }

542
543
544
545
546
    // Check for duplicate inputs
    set<COutPoint> vInOutPoints;
    BOOST_FOREACH(const CTxIn& txin, vin)
    {
        if (vInOutPoints.count(txin.prevout))
Pieter Wuille's avatar
Pieter Wuille committed
547
            return state.DoS(100, error("CTransaction::CheckTransaction() : duplicate inputs"));
548
549
550
        vInOutPoints.insert(txin.prevout);
    }

551
552
553
    if (IsCoinBase())
    {
        if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
Pieter Wuille's avatar
Pieter Wuille committed
554
            return state.DoS(100, error("CTransaction::CheckTransaction() : coinbase script size"));
555
556
557
    }
    else
    {
558
        BOOST_FOREACH(const CTxIn& txin, vin)
559
            if (txin.prevout.IsNull())
Pieter Wuille's avatar
Pieter Wuille committed
560
                return state.DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
561
562
563
564
565
    }

    return true;
}

566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
int64 CTransaction::GetMinFee(unsigned int nBlockSize, bool fAllowFree,
                              enum GetMinFee_mode mode) const
{
    // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
    int64 nBaseFee = (mode == GMF_RELAY) ? MIN_RELAY_TX_FEE : MIN_TX_FEE;

    unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION);
    unsigned int nNewBlockSize = nBlockSize + nBytes;
    int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;

    if (fAllowFree)
    {
        if (nBlockSize == 1)
        {
            // Transactions under 10K are free
            // (about 4500 BTC if made of 50 BTC inputs)
            if (nBytes < 10000)
                nMinFee = 0;
        }
        else
        {
            // Free transaction area
            if (nNewBlockSize < 27000)
                nMinFee = 0;
        }
    }

    // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
    if (nMinFee < nBaseFee)
    {
        BOOST_FOREACH(const CTxOut& txout, vout)
            if (txout.nValue < CENT)
                nMinFee = nBaseFee;
    }

    // Raise the price as the block approaches full
    if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
    {
        if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
            return MAX_MONEY;
        nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
    }

    if (!MoneyRange(nMinFee))
        nMinFee = MAX_MONEY;
    return nMinFee;
}

Pieter Wuille's avatar
Pieter Wuille committed
614
615
616
617
618
619
620
621
622
623
624
625
void CTxMemPool::pruneSpent(const uint256 &hashTx, CCoins &coins)
{
    LOCK(cs);

    std::map<COutPoint, CInPoint>::iterator it = mapNextTx.lower_bound(COutPoint(hashTx, 0));

    // iterate over all COutPoints in mapNextTx whose hash equals the provided hashTx
    while (it != mapNextTx.end() && it->first.hash == hashTx) {
        coins.Spend(it->first.n); // and remove those outputs from coins
        it++;
    }
}
626

Pieter Wuille's avatar
Pieter Wuille committed
627
bool CTxMemPool::accept(CValidationState &state, CTransaction &tx, bool fCheckInputs, bool fLimitFree,
628
                        bool* pfMissingInputs)
s_nakamoto's avatar
s_nakamoto committed
629
630
631
632
{
    if (pfMissingInputs)
        *pfMissingInputs = false;

Pieter Wuille's avatar
Pieter Wuille committed
633
    if (!tx.CheckTransaction(state))
634
        return error("CTxMemPool::accept() : CheckTransaction failed");
635

s_nakamoto's avatar
s_nakamoto committed
636
    // Coinbase is only valid in a block, not as a loose transaction
637
    if (tx.IsCoinBase())
Pieter Wuille's avatar
Pieter Wuille committed
638
        return state.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx"));
s_nakamoto's avatar
s_nakamoto committed
639
640

    // To help v0.1.5 clients who would see it as a negative number
641
642
    if ((int64)tx.nLockTime > std::numeric_limits<int>::max())
        return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet");
s_nakamoto's avatar
s_nakamoto committed
643

644
    // Rather not work on nonstandard transactions (unless -testnet)
645
646
    if (!fTestNet && !tx.IsStandard())
        return error("CTxMemPool::accept() : nonstandard transaction type");
647

Pieter Wuille's avatar
Pieter Wuille committed
648
    // is it already in the memory pool?
649
    uint256 hash = tx.GetHash();
650
    {
651
652
        LOCK(cs);
        if (mapTx.count(hash))
s_nakamoto's avatar
s_nakamoto committed
653
            return false;
654
    }
s_nakamoto's avatar
s_nakamoto committed
655
656
657

    // Check for conflicts with in-memory transactions
    CTransaction* ptxOld = NULL;
658
    for (unsigned int i = 0; i < tx.vin.size(); i++)
s_nakamoto's avatar
s_nakamoto committed
659
    {
660
        COutPoint outpoint = tx.vin[i].prevout;
s_nakamoto's avatar
s_nakamoto committed
661
662
663
664
665
666
667
668
669
        if (mapNextTx.count(outpoint))
        {
            // Disable replacement feature for now
            return false;

            // Allow replacing with a newer version of the same transaction
            if (i != 0)
                return false;
            ptxOld = mapNextTx[outpoint].ptx;
670
671
            if (ptxOld->IsFinal())
                return false;
672
            if (!tx.IsNewerThan(*ptxOld))
s_nakamoto's avatar
s_nakamoto committed
673
                return false;
674
            for (unsigned int i = 0; i < tx.vin.size(); i++)
s_nakamoto's avatar
s_nakamoto committed
675
            {
676
                COutPoint outpoint = tx.vin[i].prevout;
s_nakamoto's avatar
s_nakamoto committed
677
678
679
680
681
682
683
                if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
                    return false;
            }
            break;
        }
    }

684
    if (fCheckInputs)
s_nakamoto's avatar
s_nakamoto committed
685
    {
686
687
688
689
690
691
692
        CCoinsView dummy;
        CCoinsViewCache view(dummy);

        {
        LOCK(cs);
        CCoinsViewMemPool viewMemPool(*pcoinsTip, *this);
        view.SetBackend(viewMemPool);
Pieter Wuille's avatar
Pieter Wuille committed
693
694
695

        // do we already have it?
        if (view.HaveCoins(hash))
696
            return false;
Pieter Wuille's avatar
Pieter Wuille committed
697
698

        // do all inputs exist?
Pieter Wuille's avatar
Pieter Wuille committed
699
700
        // Note that this does not check for the presence of actual outputs (see the next check for that),
        // only helps filling in pfMissingInputs (to determine missing vs spent).
Pieter Wuille's avatar
Pieter Wuille committed
701
702
703
704
705
706
        BOOST_FOREACH(const CTxIn txin, tx.vin) {
            if (!view.HaveCoins(txin.prevout.hash)) {
                if (pfMissingInputs)
                    *pfMissingInputs = true;
                return false;
            }
Gavin Andresen's avatar
Gavin Andresen committed
707
708
        }

Pieter Wuille's avatar
Pieter Wuille committed
709
        // are the actual inputs available?
Pieter Wuille's avatar
Pieter Wuille committed
710
        if (!tx.HaveInputs(view))
Pieter Wuille's avatar
Pieter Wuille committed
711
            return state.Invalid(error("CTxMemPool::accept() : inputs already spent"));
712

713
714
715
716
717
718
        // Bring the best block into scope
        view.GetBestBlock();

        // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
        view.SetBackend(dummy);
        }
Pieter Wuille's avatar
Pieter Wuille committed
719

720
        // Check for non-standard pay-to-script-hash in inputs
Pieter Wuille's avatar
Pieter Wuille committed
721
        if (!tx.AreInputsStandard(view) && !fTestNet)
722
            return error("CTxMemPool::accept() : nonstandard transaction input");
Gavin Andresen's avatar
Gavin Andresen committed
723

724
725
726
727
        // Note: if you modify this code to accept non-standard transactions, then
        // you should add code here to check that the transaction does a
        // reasonable number of ECDSA signature verifications.

Pieter Wuille's avatar
Pieter Wuille committed
728
        int64 nFees = tx.GetValueIn(view)-tx.GetValueOut();
729
        unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
730
731

        // Don't accept it if it can't get into a block
732
        int64 txMinFee = tx.GetMinFee(1000, true, GMF_RELAY);
733
        if (fLimitFree && nFees < txMinFee)
734
            return error("CTxMemPool::accept() : not enough fees %s, %"PRI64d" < %"PRI64d,
735
                         hash.ToString().c_str(),
736
                         nFees, txMinFee);
737

738
        // Continuously rate-limit free transactions
739
        // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
740
        // be annoying or make others' transactions take longer to confirm.
741
        if (fLimitFree && nFees < MIN_RELAY_TX_FEE)
742
        {
743
            static double dFreeCount;
744
745
            static int64 nLastTime;
            int64 nNow = GetTime();
746

747
748
749
750
751
752
753
            LOCK(cs);

            // Use an exponentially decaying ~10-minute window:
            dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
            nLastTime = nNow;
            // -limitfreerelay unit is thousand-bytes-per-minute
            // At default rate it would take over a month to fill 1GB
754
            if (dFreeCount >= GetArg("-limitfreerelay", 15)*10*1000)
755
756
757
758
                return error("CTxMemPool::accept() : free transaction rejected by rate limiter");
            if (fDebug)
                printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
            dFreeCount += nSize;
759
        }
760
761
762

        // Check against previous transactions
        // This is done last to help prevent CPU exhaustion denial-of-service attacks.
Pieter Wuille's avatar
Pieter Wuille committed
763
        if (!tx.CheckInputs(state, view, true, SCRIPT_VERIFY_P2SH))
764
        {
765
            return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
766
        }
s_nakamoto's avatar
s_nakamoto committed
767
768
769
770
    }

    // Store transaction in memory
    {
771
        LOCK(cs);
s_nakamoto's avatar
s_nakamoto committed
772
773
        if (ptxOld)
        {
774
775
            printf("CTxMemPool::accept() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
            remove(*ptxOld);
s_nakamoto's avatar
s_nakamoto committed
776
        }
777
        addUnchecked(hash, tx);
s_nakamoto's avatar
s_nakamoto committed
778
779
780
781
782
    }

    ///// are we sure this is ok when loading transactions or restoring block txes
    // If updated, erase old tx from wallet
    if (ptxOld)
Pieter Wuille's avatar
Pieter Wuille committed
783
        EraseFromWallets(ptxOld->GetHash());
784
    SyncWithWallets(hash, tx, NULL, true);
s_nakamoto's avatar
s_nakamoto committed
785

786
    printf("CTxMemPool::accept() : accepted %s (poolsz %"PRIszu")\n",
787
788
           hash.ToString().substr(0,10).c_str(),
           mapTx.size());
s_nakamoto's avatar
s_nakamoto committed
789
790
791
    return true;
}

Pieter Wuille's avatar
Pieter Wuille committed
792
bool CTransaction::AcceptToMemoryPool(CValidationState &state, bool fCheckInputs, bool fLimitFree, bool* pfMissingInputs)
793
{
Pieter Wuille's avatar
Pieter Wuille committed
794
795
796
797
798
    try {
        return mempool.accept(state, *this, fCheckInputs, fLimitFree, pfMissingInputs);
    } catch(std::runtime_error &e) {
        return state.Abort(_("System error: ") + e.what());
    }
799
}
800

801
bool CTxMemPool::addUnchecked(const uint256& hash, CTransaction &tx)
s_nakamoto's avatar
s_nakamoto committed
802
803
{
    // Add to memory pool without checking anything.  Don't call this directly,
804
    // call CTxMemPool::accept to properly check the transaction first.
s_nakamoto's avatar
s_nakamoto committed
805
    {
806
        mapTx[hash] = tx;
807
        for (unsigned int i = 0; i < tx.vin.size(); i++)
808
            mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i);
s_nakamoto's avatar
s_nakamoto committed
809
810
811
812
813
814
        nTransactionsUpdated++;
    }
    return true;
}


815
bool CTxMemPool::remove(const CTransaction &tx, bool fRecursive)
s_nakamoto's avatar
s_nakamoto committed
816
817
818
{
    // Remove transaction from memory pool
    {
819
820
821
        LOCK(cs);
        uint256 hash = tx.GetHash();
        if (mapTx.count(hash))
822
        {
823
824
825
826
827
828
829
            if (fRecursive) {
                for (unsigned int i = 0; i < tx.vout.size(); i++) {
                    std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(COutPoint(hash, i));
                    if (it != mapNextTx.end())
                        remove(*it->second.ptx, true);
                }
            }
830
            BOOST_FOREACH(const CTxIn& txin, tx.vin)
831
                mapNextTx.erase(txin.prevout);
832
            mapTx.erase(hash);
833
834
            nTransactionsUpdated++;
        }
s_nakamoto's avatar
s_nakamoto committed
835
836
837
838
    }
    return true;
}

839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
bool CTxMemPool::removeConflicts(const CTransaction &tx)
{
    // Remove transactions which depend on inputs of tx, recursively
    LOCK(cs);
    BOOST_FOREACH(const CTxIn &txin, tx.vin) {
        std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(txin.prevout);
        if (it != mapNextTx.end()) {
            const CTransaction &txConflict = *it->second.ptx;
            if (txConflict != tx)
                remove(txConflict, true);
        }
    }
    return true;
}

854
void CTxMemPool::clear()
Luke Dashjr's avatar
Luke Dashjr committed
855
856
857
858
859
860
861
{
    LOCK(cs);
    mapTx.clear();
    mapNextTx.clear();
    ++nTransactionsUpdated;
}

862
863
864
void CTxMemPool::queryHashes(std::vector<uint256>& vtxid)
{
    vtxid.clear();
s_nakamoto's avatar
s_nakamoto committed
865

866
867
868
869
870
    LOCK(cs);
    vtxid.reserve(mapTx.size());
    for (map<uint256, CTransaction>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
        vtxid.push_back((*mi).first);
}
s_nakamoto's avatar
s_nakamoto committed
871
872
873
874




875
int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
s_nakamoto's avatar
s_nakamoto committed
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
{
    if (hashBlock == 0 || nIndex == -1)
        return 0;

    // Find the block it claims to be in
    map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
    if (mi == mapBlockIndex.end())
        return 0;
    CBlockIndex* pindex = (*mi).second;
    if (!pindex || !pindex->IsInMainChain())
        return 0;

    // Make sure the merkle branch connects to this block
    if (!fMerkleVerified)
    {
        if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
            return 0;
        fMerkleVerified = true;
    }

896
    pindexRet = pindex;
s_nakamoto's avatar
s_nakamoto committed
897
898
899
900
901
902
903
904
905
906
907
908
    return pindexBest->nHeight - pindex->nHeight + 1;
}


int CMerkleTx::GetBlocksToMaturity() const
{
    if (!IsCoinBase())
        return 0;
    return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
}


909
bool CMerkleTx::AcceptToMemoryPool(bool fCheckInputs, bool fLimitFree)
s_nakamoto's avatar
s_nakamoto committed
910
{
Pieter Wuille's avatar
Pieter Wuille committed
911
912
    CValidationState state;
    return CTransaction::AcceptToMemoryPool(state, fCheckInputs, fLimitFree);
s_nakamoto's avatar
s_nakamoto committed
913
914
915
916
}



917
bool CWalletTx::AcceptWalletTransaction(bool fCheckInputs)
s_nakamoto's avatar
s_nakamoto committed
918
919
{
    {
920
        LOCK(mempool.cs);
s_nakamoto's avatar
s_nakamoto committed
921
        // Add previous supporting transactions first
922
        BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
s_nakamoto's avatar
s_nakamoto committed
923
924
925
926
        {
            if (!tx.IsCoinBase())
            {
                uint256 hash = tx.GetHash();
927
                if (!mempool.exists(hash) && pcoinsTip->HaveCoins(hash))
928
                    tx.AcceptToMemoryPool(fCheckInputs, false);
s_nakamoto's avatar
s_nakamoto committed
929
930
            }
        }
931
        return AcceptToMemoryPool(fCheckInputs, false);
s_nakamoto's avatar
s_nakamoto committed
932
    }
s_nakamoto's avatar
s_nakamoto committed
933
    return false;
s_nakamoto's avatar
s_nakamoto committed
934
935
}

936

937
// Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock
Pieter Wuille's avatar
Pieter Wuille committed
938
bool GetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock, bool fAllowSlow)
939
{
Pieter Wuille's avatar
Pieter Wuille committed
940
    CBlockIndex *pindexSlow = NULL;
941
942
943
944
945
946
    {
        LOCK(cs_main);
        {
            LOCK(mempool.cs);
            if (mempool.exists(hash))
            {
Pieter Wuille's avatar
Pieter Wuille committed
947
                txOut = mempool.lookup(hash);
948
949
950
                return true;
            }
        }
Pieter Wuille's avatar
Pieter Wuille committed
951

952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
        if (fTxIndex) {
            CDiskTxPos postx;
            if (pblocktree->ReadTxIndex(hash, postx)) {
                CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);
                CBlockHeader header;
                try {
                    file >> header;
                    fseek(file, postx.nTxOffset, SEEK_CUR);
                    file >> txOut;
                } catch (std::exception &e) {
                    return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
                }
                hashBlock = header.GetHash();
                if (txOut.GetHash() != hash)
                    return error("%s() : txid mismatch", __PRETTY_FUNCTION__);
                return true;
            }
        }

Pieter Wuille's avatar
Pieter Wuille committed
971
972
973
        if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
            int nHeight = -1;
            {
974
                CCoinsViewCache &view = *pcoinsTip;
Pieter Wuille's avatar
Pieter Wuille committed
975
976
977
978
979
980
                CCoins coins;
                if (view.GetCoins(hash, coins))
                    nHeight = coins.nHeight;
            }
            if (nHeight > 0)
                pindexSlow = FindBlockByHeight(nHeight);
981
982
        }
    }
s_nakamoto's avatar
s_nakamoto committed
983

Pieter Wuille's avatar
Pieter Wuille committed
984
985
986
987
988
989
990
991
992
993
994
995
    if (pindexSlow) {
        CBlock block;
        if (block.ReadFromDisk(pindexSlow)) {
            BOOST_FOREACH(const CTransaction &tx, block.vtx) {
                if (tx.GetHash() == hash) {
                    txOut = tx;
                    hashBlock = pindexSlow->GetBlockHash();
                    return true;
                }
            }
        }
    }
s_nakamoto's avatar
s_nakamoto committed
996

Pieter Wuille's avatar
Pieter Wuille committed
997
998
    return false;
}
s_nakamoto's avatar
s_nakamoto committed
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009






//////////////////////////////////////////////////////////////////////////////
//
// CBlock and CBlockIndex
//

Luke Dashjr's avatar
Luke Dashjr committed
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
static CBlockIndex* pblockindexFBBHLast;
CBlockIndex* FindBlockByHeight(int nHeight)
{
    CBlockIndex *pblockindex;
    if (nHeight < nBestHeight / 2)
        pblockindex = pindexGenesisBlock;
    else
        pblockindex = pindexBest;
    if (pblockindexFBBHLast && abs(nHeight - pblockindex->nHeight) > abs(nHeight - pblockindexFBBHLast->nHeight))
        pblockindex = pblockindexFBBHLast;
    while (pblockindex->nHeight > nHeight)
        pblockindex = pblockindex->pprev;
    while (pblockindex->nHeight < nHeight)
        pblockindex = pblockindex->pnext;
    pblockindexFBBHLast = pblockindex;
    return pblockindex;
}

1028
bool CBlock::ReadFromDisk(const CBlockIndex* pindex)
s_nakamoto's avatar
s_nakamoto committed
1029
{
1030
    if (!ReadFromDisk(pindex->GetBlockPos()))
s_nakamoto's avatar
s_nakamoto committed
1031
1032
1033
1034
1035
1036
        return false;
    if (GetHash() != pindex->GetBlockHash())
        return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
    return true;
}

1037
uint256 static GetOrphanRoot(const CBlockHeader* pblock)
s_nakamoto's avatar
s_nakamoto committed
1038
1039
1040
1041
1042
1043
1044
{
    // Work back to the first block in the orphan chain
    while (mapOrphanBlocks.count(pblock->hashPrevBlock))
        pblock = mapOrphanBlocks[pblock->hashPrevBlock];
    return pblock->GetHash();
}

1045
int64 static GetBlockValue(int nHeight, int64 nFees)
s_nakamoto's avatar
s_nakamoto committed
1046
{
1047
    int64 nSubsidy = 50 * COIN;
s_nakamoto's avatar
s_nakamoto committed
1048

1049
    // Subsidy is cut in half every 210000 blocks, which will occur approximately every 4 years
s_nakamoto's avatar
s_nakamoto committed
1050
1051
1052
1053
1054
    nSubsidy >>= (nHeight / 210000);

    return nSubsidy + nFees;
}

1055
1056
1057
static const int64 nTargetTimespan = 14 * 24 * 60 * 60; // two weeks
static const int64 nTargetSpacing = 10 * 60;
static const int64 nInterval = nTargetTimespan / nTargetSpacing;
1058
1059
1060
1061
1062

//
// minimum amount of work that could possibly be required nTime after
// minimum work required was nBase
//
1063
unsigned int ComputeMinWork(unsigned int nBase, int64 nTime)
1064
{
1065
1066
1067
1068
1069
    // Testnet has min-difficulty blocks
    // after nTargetSpacing*2 time between blocks:
    if (fTestNet && nTime > nTargetSpacing*2)
        return bnProofOfWorkLimit.GetCompact();

1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
    CBigNum bnResult;
    bnResult.SetCompact(nBase);
    while (nTime > 0 && bnResult < bnProofOfWorkLimit)
    {
        // Maximum 400% adjustment...
        bnResult *= 4;
        // ... in best-case exactly 4-times-normal target time
        nTime -= nTargetTimespan*4;
    }
    if (bnResult > bnProofOfWorkLimit)
        bnResult = bnProofOfWorkLimit;
    return bnResult.GetCompact();
}

1084
unsigned int static GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock)
s_nakamoto's avatar
s_nakamoto committed
1085
{
1086
    unsigned int nProofOfWorkLimit = bnProofOfWorkLimit.GetCompact();
s_nakamoto's avatar
s_nakamoto committed
1087
1088
1089

    // Genesis block
    if (pindexLast == NULL)
1090
        return nProofOfWorkLimit;
s_nakamoto's avatar
s_nakamoto committed
1091
1092
1093

    // Only change once per interval
    if ((pindexLast->nHeight+1) % nInterval != 0)
1094
    {
1095
1096
        // Special difficulty rule for testnet:
        if (fTestNet)
1097
1098
1099
        {
            // If the new block's timestamp is more than 2* 10 minutes
            // then allow mining of a min-difficulty block.
1100
            if (pblock->nTime > pindexLast->nTime + nTargetSpacing*2)
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
                return nProofOfWorkLimit;
            else
            {
                // Return the last non-special-min-difficulty-rules-block
                const CBlockIndex* pindex = pindexLast;
                while (pindex->pprev && pindex->nHeight % nInterval != 0 && pindex->nBits == nProofOfWorkLimit)
                    pindex = pindex->pprev;
                return pindex->nBits;
            }
        }

s_nakamoto's avatar
s_nakamoto committed
1112
        return pindexLast->nBits;
1113
    }
s_nakamoto's avatar
s_nakamoto committed
1114
1115
1116
1117
1118
1119
1120
1121

    // Go back by what we want to be 14 days worth of blocks
    const CBlockIndex* pindexFirst = pindexLast;
    for (int i = 0; pindexFirst && i < nInterval-1; i++)
        pindexFirst = pindexFirst->pprev;
    assert(pindexFirst);

    // Limit adjustment step
1122
    int64 nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();
s_nakamoto's avatar
s_nakamoto committed
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
    printf("  nActualTimespan = %"PRI64d"  before bounds\n", nActualTimespan);
    if (nActualTimespan < nTargetTimespan/4)
        nActualTimespan = nTargetTimespan/4;
    if (nActualTimespan > nTargetTimespan*4)
        nActualTimespan = nTargetTimespan*4;

    // Retarget
    CBigNum bnNew;
    bnNew.SetCompact(pindexLast->nBits);
    bnNew *= nActualTimespan;
    bnNew /= nTargetTimespan;

    if (bnNew > bnProofOfWorkLimit)
        bnNew = bnProofOfWorkLimit;

    /// debug print
    printf("GetNextWorkRequired RETARGET\n");
    printf("nTargetTimespan = %"PRI64d"    nActualTimespan = %"PRI64d"\n", nTargetTimespan, nActualTimespan);
    printf("Before: %08x  %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());
    printf("After:  %08x  %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());

    return bnNew.GetCompact();
}

bool CheckProofOfWork(uint256 hash, unsigned int nBits)
{
    CBigNum bnTarget;
    bnTarget.SetCompact(nBits);

    // Check range
    if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
        return error("CheckProofOfWork() : nBits below minimum work");

    // Check proof of work matches claimed amount
    if (hash > bnTarget.getuint256())
        return error("CheckProofOfWork() : hash doesn't match nBits");

    return true;
}

1163
// Return maximum amount of blocks that other nodes claim to have
1164
int GetNumBlocksOfPeers()
1165
{
1166
    return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
1167
1168
}

s_nakamoto's avatar
s_nakamoto committed
1169
1170
bool IsInitialBlockDownload()
{
1171
    if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate() || fReindex || fImporting)
s_nakamoto's avatar
s_nakamoto committed
1172
        return true;
1173
    static int64 nLastUpdate;
s_nakamoto's avatar
s_nakamoto committed
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
    static CBlockIndex* pindexLastBest;
    if (pindexBest != pindexLastBest)
    {
        pindexLastBest = pindexBest;
        nLastUpdate = GetTime();
    }
    return (GetTime() - nLastUpdate < 10 &&
            pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
}

Pieter Wuille's avatar
Pieter Wuille committed
1184
void static InvalidChainFound(CBlockIndex* pindexNew)
s_nakamoto's avatar
s_nakamoto committed
1185
1186
1187
1188
{
    if (pindexNew->bnChainWork > bnBestInvalidWork)
    {
        bnBestInvalidWork = pindexNew->bnChainWork;
1189
        pblocktree->WriteBestInvalidWork(bnBestInvalidWork);
1190
        uiInterface.NotifyBlocksChanged();
s_nakamoto's avatar
s_nakamoto committed
1191
    }
1192
    printf("InvalidChainFound: invalid block=%s  height=%d  work=%s  date=%s\n",
1193
      BlockHashStr(pindexNew->GetBlockHash()).c_str(), pindexNew->nHeight,
1194
      pindexNew->bnChainWork.ToString().c_str(), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
1195
1196
      pindexNew->GetBlockTime()).c_str());
    printf("InvalidChainFound:  current best=%s  height=%d  work=%s  date=%s\n",
1197
      BlockHashStr(hashBestChain).c_str(), nBestHeight, bnBestChainWork.ToString().c_str(),
1198
      DateTimeStrFormat("%Y-%m-%d %H:%M:%S", pindexBest->GetBlockTime()).c_str());
s_nakamoto's avatar
s_nakamoto committed
1199
    if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
1200
        printf("InvalidChainFound: Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.\n");
s_nakamoto's avatar
s_nakamoto committed
1201
1202
}

1203
1204
void static InvalidBlockFound(CBlockIndex *pindex) {
    pindex->nStatus |= BLOCK_FAILED_VALID;
1205
    pblocktree->WriteBlockIndex(CDiskBlockIndex(pindex));
1206
1207
    setBlockIndexValid.erase(pindex);
    InvalidChainFound(pindex);
Pieter Wuille's avatar
Pieter Wuille committed
1208
1209
1210
1211
    if (pindex->pnext) {
        CValidationState stateDummy;
        ConnectBestBlock(stateDummy); // reorganise away from the failed block
    }
1212
1213
}

Pieter Wuille's avatar
Pieter Wuille committed
1214
bool ConnectBestBlock(CValidationState &state) {
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
    do {
        CBlockIndex *pindexNewBest;

        {
            std::set<CBlockIndex*,CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexValid.rbegin();
            if (it == setBlockIndexValid.rend())
                return true;
            pindexNewBest = *it;
        }

1225
        if (pindexNewBest == pindexBest || (pindexBest && pindexNewBest->bnChainWork == pindexBest->bnChainWork))
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
            return true; // nothing to do

        // check ancestry
        CBlockIndex *pindexTest = pindexNewBest;
        std::vector<CBlockIndex*> vAttach;
        do {
            if (pindexTest->nStatus & BLOCK_FAILED_MASK) {
                // mark descendants failed
                CBlockIndex *pindexFailed = pindexNewBest;
                while (pindexTest != pindexFailed) {
                    pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
                    setBlockIndexValid.erase(pindexFailed);
1238
                    pblocktree->WriteBlockIndex(CDiskBlockIndex(pindexFailed));
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
                    pindexFailed = pindexFailed->pprev;
                }
                InvalidChainFound(pindexNewBest);
                break;
            }

            if (pindexBest == NULL || pindexTest->bnChainWork > pindexBest->bnChainWork)
                vAttach.push_back(pindexTest);

            if (pindexTest->pprev == NULL || pindexTest->pnext != NULL) {
                reverse(vAttach.begin(), vAttach.end());
1250
1251
1252
                BOOST_FOREACH(CBlockIndex *pindexSwitch, vAttach) {
                    if (fRequestShutdown)
                        break;
Pieter Wuille's avatar
Pieter Wuille committed
1253
                    CValidationState state;
Pieter Wuille's avatar
Pieter Wuille committed
1254
1255
1256
1257
1258
1259
                    try {
                        if (!SetBestChain(state, pindexSwitch))
                            return false;
                    } catch(std::runtime_error &e) {
                        return state.Abort(_("System error: ") + e.what());
                    }
1260
                }
1261
1262
1263
1264
1265
1266
1267
                return true;
            }
            pindexTest = pindexTest->pprev;
        } while(true);
    } while(true);
}

1268
void CBlockHeader::UpdateTime(const CBlockIndex* pindexPrev)
1269
1270
1271
1272
1273
1274
1275
1276
{
    nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());

    // Updating time can change work required on testnet:
    if (fTestNet)
        nBits = GetNextWorkRequired(pindexPrev, this);
}

s_nakamoto's avatar
s_nakamoto committed
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286










Pieter Wuille's avatar
Pieter Wuille committed
1287
const CTxOut &CTransaction::GetOutputFor(const CTxIn& input, CCoinsViewCache& view)
Gavin Andresen's avatar
Gavin Andresen committed
1288
{
Pieter Wuille's avatar
Pieter Wuille committed
1289
1290
1291
    const CCoins &coins = view.GetCoins(input.prevout.hash);
    assert(coins.IsAvailable(input.prevout.n));
    return coins.vout[input.prevout.n];
1292
1293
}

Pieter Wuille's avatar
Pieter Wuille committed
1294
int64 CTransaction::GetValueIn(CCoinsViewCache& inputs) const
1295
1296
1297
1298
1299
{
    if (IsCoinBase())
        return 0;

    int64 nResult = 0;
1300
    for (unsigned int i = 0; i < vin.size(); i++)
1301
1302
        nResult += GetOutputFor(vin[i], inputs).nValue;

Pieter Wuille's avatar
Pieter Wuille committed
1303
    return nResult;
1304
1305
}

Pieter Wuille's avatar
Pieter Wuille committed
1306
unsigned int CTransaction::GetP2SHSigOpCount(CCoinsViewCache& inputs) const
1307
1308
1309
1310
{
    if (IsCoinBase())
        return 0;

1311
    unsigned int nSigOps = 0;
1312
    for (unsigned int i = 0; i < vin.size(); i++)
1313
    {
Pieter Wuille's avatar
Pieter Wuille committed
1314
        const CTxOut &prevout = GetOutputFor(vin[i], inputs);
1315
1316
        if (prevout.scriptPubKey.IsPayToScriptHash())
            nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig);
1317
1318
1319
1320
    }
    return nSigOps;
}

Pieter Wuille's avatar
Pieter Wuille committed
1321
bool CTransaction::UpdateCoins(CValidationState &state, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight, const uint256 &txhash) const
Pieter Wuille's avatar
Pieter Wuille committed
1322
1323
1324
1325
{
    // mark inputs spent
    if (!IsCoinBase()) {
        BOOST_FOREACH(const CTxIn &txin, vin) {
Pieter Wuille's avatar
Pieter Wuille committed
1326
            CCoins &coins = inputs.GetCoins(txin.prevout.hash);
Pieter Wuille's avatar
Pieter Wuille committed
1327
            CTxInUndo undo;
Pieter Wuille's avatar
Pieter Wuille committed
1328
            assert(coins.Spend(txin.prevout, undo));
Pieter Wuille's avatar
Pieter Wuille committed
1329
1330
1331
1332
1333
            txundo.vprevout.push_back(undo);
        }
    }

    // add outputs
Pieter Wuille's avatar
Pieter Wuille committed
1334
    assert(inputs.SetCoins(txhash, CCoins(*this, nHeight)));
Pieter Wuille's avatar
Pieter Wuille committed
1335
1336
1337
1338

    return true;
}

Pieter Wuille's avatar
Pieter Wuille committed
1339
bool CTransaction::HaveInputs(CCoinsViewCache &inputs) const
Pieter Wuille's avatar
Pieter Wuille committed
1340
{
1341
    if (!IsCoinBase()) {
Pieter Wuille's avatar
Pieter Wuille committed
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
        // first check whether information about the prevout hash is available
        for (unsigned int i = 0; i < vin.size(); i++) {
            const COutPoint &prevout = vin[i].prevout;
            if (!inputs.HaveCoins(prevout.hash))
                return false;
        }

        // then check whether the actual outputs are available
        for (unsigned int i = 0; i < vin.size(); i++) {
            const COutPoint &prevout = vin[i].prevout;
Pieter Wuille's avatar
Pieter Wuille committed
1352
            const CCoins &coins = inputs.GetCoins(prevout.hash);
Pieter Wuille's avatar
Pieter Wuille committed
1353
1354
1355
1356
1357
1358
1359
            if (!coins.IsAvailable(prevout.n))
                return false;
        }
    }
    return true;
}

1360
1361
1362
1363
1364
1365
1366
bool CScriptCheck::operator()() const {
    const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
    if (!VerifyScript(scriptSig, scriptPubKey, *ptxTo, nIn, nFlags, nHashType))
        return error("CScriptCheck() : %s VerifySignature failed", ptxTo->GetHash().ToString().substr(0,10).c_str());
    return true;
}

Pieter Wuille's avatar
Pieter Wuille committed
1367
1368
bool VerifySignature(const CCoins& txFrom, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType)
{
1369
    return CScriptCheck(txFrom, txTo, nIn, flags, nHashType)();
Pieter Wuille's avatar
Pieter Wuille committed
1370
1371
}

Pieter Wuille's avatar
Pieter Wuille committed
1372
bool CTransaction::CheckInputs(CValidationState &state, CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, std::vector<CScriptCheck> *pvChecks) const
s_nakamoto's avatar
s_nakamoto committed
1373
1374
1375
{
    if (!IsCoinBase())
    {
1376
1377
1378
        if (pvChecks)
            pvChecks->reserve(vin.size());

Pieter Wuille's avatar
Pieter Wuille committed
1379
1380
1381
        // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
        // for an attacker to attempt to split the network.
        if (!HaveInputs(inputs))
Pieter Wuille's avatar
Pieter Wuille committed
1382
            return state.Invalid(error("CheckInputs() : %s inputs unavailable", GetHash().ToString().substr(0,10).c_str()));
Pieter Wuille's avatar
Pieter Wuille committed
1383

1384
1385
        // While checking, GetBestBlock() refers to the parent block.
        // This is also true for mempool checks.
1386
        int nSpendHeight = inputs.GetBestBlock()->nHeight + 1;
1387
        int64 nValueIn = 0;
1388
        int64 nFees = 0;
1389
        for (unsigned int i = 0; i < vin.size(); i++)
s_nakamoto's avatar
s_nakamoto committed
1390
        {
Pieter Wuille's avatar
Pieter Wuille committed
1391
            const COutPoint &prevout = vin[i].prevout;
Pieter Wuille's avatar
Pieter Wuille committed
1392
            const CCoins &coins = inputs.GetCoins(prevout.hash);
s_nakamoto's avatar
s_nakamoto committed
1393
1394

            // If prev is coinbase, check that it's matured
Pieter Wuille's avatar
Pieter Wuille committed
1395
            if (coins.IsCoinBase()) {
1396
                if (nSpendHeight - coins.nHeight < COINBASE_MATURITY)
Pieter Wuille's avatar
Pieter Wuille committed
1397
                    return state.Invalid(error("CheckInputs() : tried to spend coinbase at depth %d", nSpendHeight - coins.nHeight));
Pieter Wuille's avatar
Pieter Wuille committed
1398
            }
s_nakamoto's avatar
s_nakamoto committed
1399

1400
            // Check for negative or overflow input values
Pieter Wuille's avatar
Pieter Wuille committed
1401
1402
            nValueIn += coins.vout[prevout.n].nValue;
            if (!MoneyRange(coins.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
Pieter Wuille's avatar
Pieter Wuille committed
1403
                return state.DoS(100, error("CheckInputs() : txin values out of range"));
1404
1405

        }
Pieter Wuille's avatar
Pieter Wuille committed
1406
1407

        if (nValueIn < GetValueOut())
Pieter Wuille's avatar
Pieter Wuille committed
1408
            return state.DoS(100, error("ChecktInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
Pieter Wuille's avatar
Pieter Wuille committed
1409
1410
1411
1412

        // Tally transaction fees
        int64 nTxFee = nValueIn - GetValueOut();
        if (nTxFee < 0)
Pieter Wuille's avatar
Pieter Wuille committed
1413
            return state.DoS(100, error("CheckInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
Pieter Wuille's avatar
Pieter Wuille committed
1414
1415
        nFees += nTxFee;
        if (!MoneyRange(nFees))
Pieter Wuille's avatar
Pieter Wuille committed
1416
            return state.DoS(100, error("CheckInputs() : nFees out of range"));
Pieter Wuille's avatar
Pieter Wuille committed
1417

1418
1419
1420
1421
        // The first loop above does all the inexpensive checks.
        // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
        // Helps prevent CPU exhaustion attacks.

Pieter Wuille's avatar
Pieter Wuille committed
1422
        // Skip ECDSA signature verification when connecting blocks
1423
        // before the last block chain checkpoint. This is safe because block merkle hashes are
Pieter Wuille's avatar
Pieter Wuille committed
1424
        // still computed and checked, and any change will be caught at the next checkpoint.
1425
        if (fScriptChecks) {
Pieter Wuille's avatar
Pieter Wuille committed
1426
1427
            for (unsigned int i = 0; i < vin.size(); i++) {
                const COutPoint &prevout = vin[i].prevout;
Pieter Wuille's avatar
Pieter Wuille committed
1428
                const CCoins &coins = inputs.GetCoins(prevout.hash);
1429

1430
                // Verify signature
1431
1432
1433
1434
1435
                CScriptCheck check(coins, *this, i, flags, 0);
                if (pvChecks) {
                    pvChecks->push_back(CScriptCheck());
                    check.swap(pvChecks->back());
                } else if (!check())
Pieter Wuille's avatar
Pieter Wuille committed
1436
                    return state.DoS(100,false);
1437
            }
s_nakamoto's avatar
s_nakamoto committed
1438
1439
1440
1441
1442
1443
1444
1445
1446
        }
    }

    return true;
}




Pieter Wuille's avatar
Pieter Wuille committed
1447
bool CBlock::DisconnectBlock(CValidationState &state, CBlockIndex *pindex, CCoinsViewCache &view, bool *pfClean)
s_nakamoto's avatar
s_nakamoto committed
1448
{
Pieter Wuille's avatar
Pieter Wuille committed
1449
    assert(pindex == view.GetBestBlock());
s_nakamoto's avatar
s_nakamoto committed
1450

1451
1452
1453
1454
1455
    if (pfClean)
        *pfClean = false;

    bool fClean = true;

Pieter Wuille's avatar
Pieter Wuille committed
1456
    CBlockUndo blockUndo;
Pieter Wuille's avatar
Pieter Wuille committed
1457
1458
1459
1460
1461
    CDiskBlockPos pos = pindex->GetUndoPos();
    if (pos.IsNull())
        return error("DisconnectBlock() : no undo data available");
    if (!blockUndo.ReadFromDisk(pos, pindex->pprev->GetBlockHash()))
        return error("DisconnectBlock() : failure reading undo data");
s_nakamoto's avatar
s_nakamoto committed
1462

1463
1464
    if (blockUndo.vtxundo.size() + 1 != vtx.size())
        return error("DisconnectBlock() : block and undo data inconsistent");
Pieter Wuille's avatar
Pieter Wuille committed
1465
1466
1467
1468
1469
1470
1471

    // undo transactions in reverse order
    for (int i = vtx.size() - 1; i >= 0; i--) {
        const CTransaction &tx = vtx[i];
        uint256 hash = tx.GetHash();

        // check that all outputs are available
1472
1473
1474
1475
        if (!view.HaveCoins(hash)) {
            fClean = fClean && error("DisconnectBlock() : outputs still spent? database corrupted");
            view.SetCoins(hash, CCoins());
        }
Pieter Wuille's avatar
Pieter Wuille committed
1476
        CCoins &outs = view.GetCoins(hash);
Pieter Wuille's avatar
Pieter Wuille committed
1477
1478
1479

        CCoins outsBlock = CCoins(tx, pindex->nHeight);
        if (outs != outsBlock)
1480
            fClean = fClean && error("DisconnectBlock() : added transaction mismatch? database corrupted");
Pieter Wuille's avatar
Pieter Wuille committed
1481
1482

        // remove outputs
Pieter Wuille's avatar
Pieter Wuille committed
1483
        outs = CCoins();
Pieter Wuille's avatar
Pieter Wuille committed
1484
1485
1486
1487

        // restore inputs
        if (i > 0) { // not coinbases
            const CTxUndo &txundo = blockUndo.vtxundo[i-1];
1488
1489
            if (txundo.vprevout.size() != tx.vin.size())
                return error("DisconnectBlock() : transaction and undo data inconsistent");
Pieter Wuille's avatar
Pieter Wuille committed
1490
1491
1492
1493
1494
            for (unsigned int j = tx.vin.size(); j-- > 0;) {
                const COutPoint &out = tx.vin[j].prevout;
                const CTxInUndo &undo = txundo.vprevout[j];
                CCoins coins;
                view.GetCoins(out.hash, coins); // this can fail if the prevout was already entirely spent
1495
1496
1497
1498
1499
                if (undo.nHeight != 0) {
                    // undo data contains height: this is the last output of the prevout tx being spent
                    if (!coins.IsPruned())
                        fClean = fClean && error("DisconnectBlock() : undo data overwriting existing transaction");
                    coins = CCoins();
Pieter Wuille's avatar
Pieter Wuille committed
1500
1501
1502
1503
                    coins.fCoinBase = undo.fCoinBase;
                    coins.nHeight = undo.nHeight;
                    coins.nVersion = undo.nVersion;
                } else {
1504
1505
                    if (coins.IsPruned())
                        fClean = fClean && error("DisconnectBlock() : undo data adding output to missing transaction");
Pieter Wuille's avatar
Pieter Wuille committed
1506
1507
                }
                if (coins.IsAvailable(out.n))
1508
                    fClean = fClean && error("DisconnectBlock() : undo data overwriting existing output");
Pieter Wuille's avatar
Pieter Wuille committed
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
                if (coins.vout.size() < out.n+1)
                    coins.vout.resize(out.n+1);
                coins.vout[out.n] = undo.txout;
                if (!view.SetCoins(out.hash, coins))
                    return error("DisconnectBlock() : cannot restore coin inputs");
            }
        }
    }

    // move best block pointer to prevout block
    view.SetBestBlock(pindex->pprev);

1521
1522
1523
1524
1525
1526
    if (pfClean) {
        *pfClean = fClean;
        return true;
    } else {
        return fClean;
    }
s_nakamoto's avatar
s_nakamoto committed
1527
1528
}

Pieter Wuille's avatar
Pieter Wuille committed
1529
1530
1531
1532
void static FlushBlockFile()
{
    LOCK(cs_LastBlockFile);

1533
    CDiskBlockPos posOld(nLastBlockFile, 0);
Pieter Wuille's avatar
Pieter Wuille committed
1534
1535

    FILE *fileOld = OpenBlockFile(posOld);
1536
1537
1538
1539
    if (fileOld) {
        FileCommit(fileOld);
        fclose(fileOld);
    }
Pieter Wuille's avatar
Pieter Wuille committed
1540
1541

    fileOld = OpenUndoFile(posOld);
1542
1543
1544
1545
    if (fileOld) {
        FileCommit(fileOld);
        fclose(fileOld);
    }
Pieter Wuille's avatar
Pieter Wuille committed
1546
1547
}

Pieter Wuille's avatar
Pieter Wuille committed
1548
bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
Pieter Wuille's avatar
Pieter Wuille committed
1549

1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
static CCheckQueue<CScriptCheck> scriptcheckqueue(128);

void ThreadScriptCheck(void*) {
    vnThreadsRunning[THREAD_SCRIPTCHECK]++;
    RenameThread("bitcoin-scriptch");
    scriptcheckqueue.Thread();
    vnThreadsRunning[THREAD_SCRIPTCHECK]--;
}

void ThreadScriptCheckQuit() {
    scriptcheckqueue.Quit();
}

Pieter Wuille's avatar
Pieter Wuille committed
1563
bool CBlock::ConnectBlock(CValidationState &state, CBlockIndex* pindex, CCoinsViewCache &view, bool fJustCheck)
s_nakamoto's avatar
s_nakamoto committed
1564
1565
{
    // Check it again in case a previous version let a bad block in
Pieter Wuille's avatar
Pieter Wuille committed
1566
    if (!CheckBlock(state, !fJustCheck, !fJustCheck))
s_nakamoto's avatar
s_nakamoto committed
1567
1568
        return false;

Pieter Wuille's avatar
Pieter Wuille committed
1569
1570
1571
    // verify that the view's current state corresponds to the previous block
    assert(pindex->pprev == view.GetBestBlock());

1572
1573
1574
1575
1576
1577
1578
1579
    // Special case for the genesis block, skipping connection of its transactions
    // (its coinbase is unspendable)
    if (GetHash() == hashGenesisBlock) {
        view.SetBestBlock(pindex);
        pindexGenesisBlock = pindex;
        return true;
    }

1580
1581
    bool fScriptChecks = pindex->nHeight >= Checkpoints::GetTotalBlocksEstimate();

1582
1583
1584
1585
1586
1587
1588
    // Do not allow blocks that contain transactions which 'overwrite' older transactions,
    // unless those are already completely spent.
    // If such overwrites are allowed, coinbases and transactions depending upon those
    // can be duplicated to remove the ability to spend the first instance -- even after
    // being sent to another address.
    // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
    // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1589
    // already refuses previously-known transaction ids entirely.
1590
1591
1592
1593
    // This rule was originally applied all blocks whose timestamp was after March 15, 2012, 0:00 UTC.
    // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
    // two in the chain that violate it. This prevents exploiting the issue against nodes in their
    // initial block download.
1594
1595
    bool fEnforceBIP30 = (!pindex->phashBlock) || // Enforce on CreateNewBlock invocations which don't have a hash.
                          !((pindex->nHeight==91842 && pindex->GetBlockHash() == uint256("0x00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")) ||
1596
                           (pindex->nHeight==91880 && pindex->GetBlockHash() == uint256("0x00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721")));
Pieter Wuille's avatar
Pieter Wuille committed
1597
    if (fEnforceBIP30) {
Pieter Wuille's avatar
Pieter Wuille committed
1598
1599
        for (unsigned int i=0; i<vtx.size(); i++) {
            uint256 hash = GetTxHash(i);
Pieter Wuille's avatar
Pieter Wuille committed
1600
            if (view.HaveCoins(hash) && !view.GetCoins(hash).IsPruned())
Pieter Wuille's avatar
Pieter Wuille committed
1601
1602
1603
                return error("ConnectBlock() : tried to overwrite transaction");
        }
    }
1604

1605
1606
    // BIP16 didn't become active until Apr 1 2012
    int64 nBIP16SwitchTime = 1333238400;
1607
    bool fStrictPayToScriptHash = (pindex->nTime >= nBIP16SwitchTime);
1608

1609
1610
1611
    unsigned int flags = SCRIPT_VERIFY_NOCACHE |
                         (fStrictPayToScriptHash ? SCRIPT_VERIFY_P2SH : SCRIPT_VERIFY_NONE);

Pieter Wuille's avatar
Pieter Wuille committed
1612
1613
    CBlockUndo blockundo;

1614
1615
    CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);

1616
    int64 nStart = GetTimeMicros();
1617
    int64 nFees = 0;
1618
    int nInputs = 0;
1619
    unsigned int nSigOps = 0;
1620
1621
1622
    CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(vtx.size()));
    std::vector<std::pair<uint256, CDiskTxPos> > vPos;
    vPos.reserve(vtx.size());
Pieter Wuille's avatar
Pieter Wuille committed
1623
    for (unsigned int i=0; i<vtx.size(); i++)
s_nakamoto's avatar
s_nakamoto committed
1624
    {
1625

Pieter Wuille's avatar
Pieter Wuille committed
1626
1627
        const CTransaction &tx = vtx[i];

1628
        nInputs += tx.vin.size();
1629
1630
        nSigOps += tx.GetLegacySigOpCount();
        if (nSigOps > MAX_BLOCK_SIGOPS)
Pieter Wuille's avatar
Pieter Wuille committed
1631
            return state.DoS(100, error("ConnectBlock() : too many sigops"));
1632

1633
1634
        if (!tx.IsCoinBase())
        {
Pieter Wuille's avatar
Pieter Wuille committed
1635
            if (!tx.HaveInputs(view))
Pieter Wuille's avatar
Pieter Wuille committed
1636
                return state.DoS(100, error("ConnectBlock() : inputs missing/spent"));
1637

1638
1639
1640
1641
1642
            if (fStrictPayToScriptHash)
            {
                // Add in sigops done by pay-to-script-hash inputs;
                // this is to prevent a "rogue miner" from creating
                // an incredibly-expensive-to-validate block.
Pieter Wuille's avatar
Pieter Wuille committed
1643
                nSigOps += tx.GetP2SHSigOpCount(view);
1644
                if (nSigOps > MAX_BLOCK_SIGOPS)
Pieter Wuille's avatar
Pieter Wuille committed
1645
                     return state.DoS(100, error("ConnectBlock() : too many sigops"));
1646
            }
1647

Pieter Wuille's avatar
Pieter Wuille committed
1648
            nFees += tx.GetValueIn(view)-tx.GetValueOut();
Pieter Wuille's avatar
Pieter Wuille committed
1649

1650
            std::vector<CScriptCheck> vChecks;
Pieter Wuille's avatar
Pieter Wuille committed
1651
            if (!tx.CheckInputs(state, view, fScriptChecks, flags, nScriptCheckThreads ? &vChecks : NULL))
1652
                return false;
1653
            control.Add(vChecks);
1654
1655
        }

Pieter Wuille's avatar
Pieter Wuille committed
1656
        CTxUndo txundo;
Pieter Wuille's avatar
Pieter Wuille committed
1657
        if (!tx.UpdateCoins(state, view, txundo, pindex->nHeight, GetTxHash(i)))
Pieter Wuille's avatar
Pieter Wuille committed
1658
1659
1660
            return error("ConnectBlock() : UpdateInputs failed");
        if (!tx.IsCoinBase())
            blockundo.vtxundo.push_back(txundo);
1661

1662
1663
        vPos.push_back(std::make_pair(GetTxHash(i), pos));
        pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
s_nakamoto's avatar
s_nakamoto committed
1664
    }
1665
1666
1667
    int64 nTime = GetTimeMicros() - nStart;
    if (fBenchmark)
        printf("- Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin)\n", (unsigned)vtx.size(), 0.001 * nTime, 0.001 * nTime / vtx.size(), nInputs <= 1 ? 0 : 0.001 * nTime / (nInputs-1));
Gavin Andresen's avatar
Gavin Andresen committed
1668

Pieter Wuille's avatar
Pieter Wuille committed
1669
    if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))
1670
        return state.DoS(100, error("ConnectBlock() : coinbase pays too much (actual=%"PRI64d" vs limit=%"PRI64d")", vtx[0].GetValueOut(), GetBlockValue(pindex->nHeight, nFees)));
Pieter Wuille's avatar
Pieter Wuille committed
1671

1672
    if (!control.Wait())
Pieter Wuille's avatar
Pieter Wuille committed
1673
        return state.DoS(100, false);
1674
1675
1676
1677
    int64 nTime2 = GetTimeMicros() - nStart;
    if (fBenchmark)
        printf("- Verify %u txins: %.2fms (%.3fms/txin)\n", nInputs - 1, 0.001 * nTime2, nInputs <= 1 ? 0 : 0.001 * nTime2 / (nInputs-1));

1678
1679
1680
    if (fJustCheck)
        return true;

Pieter Wuille's avatar
Pieter Wuille committed
1681
    // Write undo information to disk
1682
    if (pindex->GetUndoPos().IsNull() || (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS)
Pieter Wuille's avatar
Pieter Wuille committed
1683
    {
1684
1685
        if (pindex->GetUndoPos().IsNull()) {
            CDiskBlockPos pos;
Pieter Wuille's avatar
Pieter Wuille committed
1686
            if (!FindUndoPos(state, pindex->nFile, pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40))
1687
                return error("ConnectBlock() : FindUndoPos failed");
Pieter Wuille's avatar
Pieter Wuille committed
1688
            if (!blockundo.WriteToDisk(pos, pindex->pprev->GetBlockHash()))
Pieter Wuille's avatar
Pieter Wuille committed
1689
                return state.Abort(_("Failed to write undo data"));
1690
1691
1692
1693
1694
1695
1696
1697

            // update nUndoPos in block index
            pindex->nUndoPos = pos.nPos;
            pindex->nStatus |= BLOCK_HAVE_UNDO;
        }

        pindex->nStatus = (pindex->nStatus & ~BLOCK_VALID_MASK) | BLOCK_VALID_SCRIPTS;

Pieter Wuille's avatar
Pieter Wuille committed
1698
        CDiskBlockIndex blockindex(pindex);
1699
        if (!pblocktree->WriteBlockIndex(blockindex))
Pieter Wuille's avatar
Pieter Wuille committed
1700
            return state.Abort(_("Failed to write block index"));
s_nakamoto's avatar
s_nakamoto committed
1701
1702
    }

1703
    if (fTxIndex)
Pieter Wuille's avatar
Pieter Wuille committed
1704
        if (!pblocktree->WriteTxIndex(vPos))
Pieter Wuille's avatar
Pieter Wuille committed
1705
            return state.Abort(_("Failed to write transaction index"));
1706

1707
    // add this block to the view's block chain
1708
    assert(view.SetBestBlock(pindex));
Pieter Wuille's avatar
Pieter Wuille committed
1709

s_nakamoto's avatar
s_nakamoto committed
1710
    // Watch for transactions paying to me
Pieter Wuille's avatar
Pieter Wuille committed
1711
1712
    for (unsigned int i=0; i<vtx.size(); i++)
        SyncWithWallets(GetTxHash(i), vtx[i], this, true);
s_nakamoto's avatar
s_nakamoto committed
1713
1714
1715
1716

    return true;
}

Pieter Wuille's avatar
Pieter Wuille committed
1717
bool SetBestChain(CValidationState &state, CBlockIndex* pindexNew)
s_nakamoto's avatar
s_nakamoto committed
1718
{
Pieter Wuille's avatar
Pieter Wuille committed
1719
1720
1721
    // All modifications to the coin state will be done in this cache.
    // Only when all have succeeded, we push it to pcoinsTip.
    CCoinsViewCache view(*pcoinsTip, true);
Pieter Wuille's avatar
Pieter Wuille committed
1722
1723
1724

    // Find the fork (typically, there is none)
    CBlockIndex* pfork = view.GetBestBlock();
s_nakamoto's avatar
s_nakamoto committed
1725
    CBlockIndex* plonger = pindexNew;
1726
    while (pfork && pfork != plonger)
s_nakamoto's avatar
s_nakamoto committed
1727
    {
1728
1729
1730
1731
        while (plonger->nHeight > pfork->nHeight) {
            plonger = plonger->pprev;
            assert(plonger != NULL);
        }
s_nakamoto's avatar
s_nakamoto committed
1732
1733
        if (pfork == plonger)
            break;
1734
1735
        pfork = pfork->pprev;
        assert(pfork != NULL);
s_nakamoto's avatar
s_nakamoto committed
1736
1737
    }

Pieter Wuille's avatar
Pieter Wuille committed
1738
    // List of what to disconnect (typically nothing)
s_nakamoto's avatar
s_nakamoto committed
1739
    vector<CBlockIndex*> vDisconnect;
Pieter Wuille's avatar
Pieter Wuille committed
1740
    for (CBlockIndex* pindex = view.GetBestBlock(); pindex != pfork; pindex = pindex->pprev)
s_nakamoto's avatar
s_nakamoto committed
1741
1742
        vDisconnect.push_back(pindex);

Pieter Wuille's avatar
Pieter Wuille committed
1743
    // List of what to connect (typically only pindexNew)
s_nakamoto's avatar
s_nakamoto committed
1744
1745
1746
1747
1748
    vector<CBlockIndex*> vConnect;
    for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
        vConnect.push_back(pindex);
    reverse(vConnect.begin(), vConnect.end());

Pieter Wuille's avatar
Pieter Wuille committed
1749
    if (vDisconnect.size() > 0) {
1750
1751
        printf("REORGANIZE: Disconnect %"PRIszu" blocks; %s..%s\n", vDisconnect.size(), BlockHashStr(pfork->GetBlockHash()).c_str(), BlockHashStr(pindexBest->GetBlockHash()).c_str());
        printf("REORGANIZE: Connect %"PRIszu" blocks; %s..%s\n", vConnect.size(), BlockHashStr(pfork->GetBlockHash()).c_str(), BlockHashStr(pindexNew->GetBlockHash()).c_str());
Pieter Wuille's avatar
Pieter Wuille committed
1752
    }
1753

s_nakamoto's avatar
s_nakamoto committed
1754
1755
    // Disconnect shorter branch
    vector<CTransaction> vResurrect;
Pieter Wuille's avatar
Pieter Wuille committed
1756
    BOOST_FOREACH(CBlockIndex* pindex, vDisconnect) {
s_nakamoto's avatar
s_nakamoto committed
1757
1758
        CBlock block;
        if (!block.ReadFromDisk(pindex))
Pieter Wuille's avatar
Pieter Wuille committed
1759
            return state.Abort(_("Failed to read block"));
1760
        int64 nStart = GetTimeMicros();
Pieter Wuille's avatar
Pieter Wuille committed
1761
        if (!block.DisconnectBlock(state, pindex, view))
1762
            return error("SetBestBlock() : DisconnectBlock %s failed", BlockHashStr(pindex->GetBlockHash()).c_str());
1763
1764
        if (fBenchmark)
            printf("- Disconnect: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
s_nakamoto's avatar
s_nakamoto committed
1765

1766
1767
1768
        // Queue memory transactions to resurrect.
        // We only do this for blocks after the last checkpoint (reorganisation before that
        // point should only happen with -reindex/-loadblock, or a misbehaving peer.
1769
        BOOST_FOREACH(const CTransaction& tx, block.vtx)
1770
            if (!tx.IsCoinBase() && pindex->nHeight > Checkpoints::GetTotalBlocksEstimate())
s_nakamoto's avatar
s_nakamoto committed
1771
1772
1773
1774
1775
                vResurrect.push_back(tx);
    }

    // Connect longer branch
    vector<CTransaction> vDelete;
Pieter Wuille's avatar
Pieter Wuille committed
1776
    BOOST_FOREACH(CBlockIndex *pindex, vConnect) {
s_nakamoto's avatar
s_nakamoto committed
1777
        CBlock block;
1778
        if (!block.ReadFromDisk(pindex))
Pieter Wuille's avatar
Pieter Wuille committed
1779
            return state.Abort(_("Failed to read block"));
1780
        int64 nStart = GetTimeMicros();
Pieter Wuille's avatar
Pieter Wuille committed
1781
1782
1783
1784
1785
        if (!block.ConnectBlock(state, pindex, view)) {
            if (state.IsInvalid()) {
                InvalidChainFound(pindexNew);
                InvalidBlockFound(pindex);
            }
1786
            return error("SetBestBlock() : ConnectBlock %s failed", BlockHashStr(pindex->GetBlockHash()).c_str());
s_nakamoto's avatar
s_nakamoto committed
1787
        }
1788
1789
        if (fBenchmark)
            printf("- Connect: %.2fms\n", (GetTimeMicros() - nStart) * 0.001); 
s_nakamoto's avatar
s_nakamoto committed
1790
1791

        // Queue memory transactions to delete
1792
        BOOST_FOREACH(const CTransaction& tx, block.vtx)
s_nakamoto's avatar
s_nakamoto committed
1793
1794
1795
            vDelete.push_back(tx);
    }

Pieter Wuille's avatar
Pieter Wuille committed
1796
    // Flush changes to global coin state
1797
1798
    int64 nStart = GetTimeMicros();
    int nModified = view.GetCacheSize();
1799
    assert(view.Flush());
1800
1801
1802
    int64 nTime = GetTimeMicros() - nStart;
    if (fBenchmark)
        printf("- Flush %i transactions: %.2fms (%.4fms/tx)\n", nModified, 0.001 * nTime, 0.001 * nTime / nModified);
Pieter Wuille's avatar
Pieter Wuille committed
1803

1804
    // Make sure it's successfully written to disk before changing memory structure
1805
    bool fIsInitialDownload = IsInitialBlockDownload();
Pieter Wuille's avatar
Pieter Wuille committed
1806
    if (!fIsInitialDownload || pcoinsTip->GetCacheSize() > nCoinCacheSize) {
1807
1808
1809
1810
1811
1812
1813
        // Typical CCoins structures on disk are around 100 bytes in size.
        // Pushing a new one to the database can cause it to be written
        // twice (once in the log, and once in the tables). This is already
        // an overestimation, as most will delete an existing entry or
        // overwrite one. Still, use a conservative safety factor of 2.
        if (!CheckDiskSpace(100 * 2 * 2 * pcoinsTip->GetCacheSize()))
            return state.Error();
Pieter Wuille's avatar
Pieter Wuille committed
1814
        FlushBlockFile();
1815
        pblocktree->Sync();
Pieter Wuille's avatar
Pieter Wuille committed
1816
        if (!pcoinsTip->Flush())
Pieter Wuille's avatar
Pieter Wuille committed
1817
            return state.Abort(_("Failed to write to coin database"));
Pieter Wuille's avatar
Pieter Wuille committed
1818
    }
Pieter Wuille's avatar
Pieter Wuille committed
1819
1820
1821

    // At this point, all changes have been done to the database.
    // Proceed by updating the memory structures.
s_nakamoto's avatar
s_nakamoto committed
1822
1823

    // Disconnect shorter branch
1824
    BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
s_nakamoto's avatar
s_nakamoto committed
1825
1826
1827
1828
        if (pindex->pprev)
            pindex->pprev->pnext = NULL;

    // Connect longer branch
1829
    BOOST_FOREACH(CBlockIndex* pindex, vConnect)
s_nakamoto's avatar
s_nakamoto committed
1830
1831
1832
1833
        if (pindex->pprev)
            pindex->pprev->pnext = pindex;

    // Resurrect memory transactions that were in the disconnected branch
Pieter Wuille's avatar
Pieter Wuille committed
1834
1835
1836
1837
1838
    BOOST_FOREACH(CTransaction& tx, vResurrect) {
        // ignore validation errors in resurrected transactions
        CValidationState stateDummy;
        tx.AcceptToMemoryPool(stateDummy, true, false);
    }
s_nakamoto's avatar
s_nakamoto committed
1839
1840

    // Delete redundant memory transactions that are in the connected branch
1841
    BOOST_FOREACH(CTransaction& tx, vDelete) {
1842
        mempool.remove(tx);
1843
1844
        mempool.removeConflicts(tx);
    }
s_nakamoto's avatar
s_nakamoto committed
1845

1846
    // Update best block in wallet (so we can detect restored wallets)
1847
    if (!fIsInitialDownload)
1848
1849
    {
        const CBlockLocator locator(pindexNew);
Pieter Wuille's avatar
Pieter Wuille committed
1850
        ::SetBestChain(locator);
1851
1852
    }

s_nakamoto's avatar
s_nakamoto committed
1853
    // New best block
Pieter Wuille's avatar
Pieter Wuille committed
1854
    hashBestChain = pindexNew->GetBlockHash();
s_nakamoto's avatar
s_nakamoto committed
1855
    pindexBest = pindexNew;
Luke Dashjr's avatar
Luke Dashjr committed
1856
    pblockindexFBBHLast = NULL;
s_nakamoto's avatar
s_nakamoto committed
1857
1858
1859
1860
    nBestHeight = pindexBest->nHeight;
    bnBestChainWork = pindexNew->bnChainWork;
    nTimeBestReceived = GetTime();
    nTransactionsUpdated++;
1861
    printf("SetBestChain: new best=%s  height=%d  work=%s  tx=%lu  date=%s\n",
1862
      BlockHashStr(hashBestChain).c_str(), nBestHeight, bnBestChainWork.ToString().c_str(), (unsigned long)pindexNew->nChainTx,
1863
      DateTimeStrFormat("%Y-%m-%d %H:%M:%S", pindexBest->GetBlockTime()).c_str());
s_nakamoto's avatar
s_nakamoto committed
1864

1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
    // Check the version of the last 100 blocks to see if we need to upgrade:
    if (!fIsInitialDownload)
    {
        int nUpgraded = 0;
        const CBlockIndex* pindex = pindexBest;
        for (int i = 0; i < 100 && pindex != NULL; i++)
        {
            if (pindex->nVersion > CBlock::CURRENT_VERSION)
                ++nUpgraded;
            pindex = pindex->pprev;
        }
        if (nUpgraded > 0)
            printf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, CBlock::CURRENT_VERSION);
        if (nUpgraded > 100/2)
            // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
1880
            strMiscWarning = _("Warning: This version is obsolete, upgrade required!");
1881
1882
    }

1883
1884
1885
1886
1887
1888
1889
1890
    std::string strCmd = GetArg("-blocknotify", "");

    if (!fIsInitialDownload && !strCmd.empty())
    {
        boost::replace_all(strCmd, "%s", hashBestChain.GetHex());
        boost::thread t(runCommand, strCmd); // thread runs free
    }

s_nakamoto's avatar
s_nakamoto committed
1891
1892
1893
1894
    return true;
}


Pieter Wuille's avatar
Pieter Wuille committed
1895
bool CBlock::AddToBlockIndex(CValidationState &state, const CDiskBlockPos &pos)
s_nakamoto's avatar
s_nakamoto committed
1896
1897
1898
1899
{
    // Check for duplicate
    uint256 hash = GetHash();
    if (mapBlockIndex.count(hash))
Pieter Wuille's avatar
Pieter Wuille committed
1900
        return state.Invalid(error("AddToBlockIndex() : %s already exists", BlockHashStr(hash).c_str()));
s_nakamoto's avatar
s_nakamoto committed
1901
1902

    // Construct new block index object
Pieter Wuille's avatar
Pieter Wuille committed
1903
    CBlockIndex* pindexNew = new CBlockIndex(*this);
1904
    assert(pindexNew);
s_nakamoto's avatar
s_nakamoto committed
1905
1906
1907
1908
1909
1910
1911
1912
    map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
    pindexNew->phashBlock = &((*mi).first);
    map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
    if (miPrev != mapBlockIndex.end())
    {
        pindexNew->pprev = (*miPrev).second;
        pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
    }
1913
    pindexNew->nTx = vtx.size();
s_nakamoto's avatar
s_nakamoto committed
1914
    pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork();
1915
1916
1917
    pindexNew->nChainTx = (pindexNew->pprev ? pindexNew->pprev->nChainTx : 0) + pindexNew->nTx;
    pindexNew->nFile = pos.nFile;
    pindexNew->nDataPos = pos.nPos;
Pieter Wuille's avatar
Pieter Wuille committed
1918
    pindexNew->nUndoPos = 0;
1919
1920
    pindexNew->nStatus = BLOCK_VALID_TRANSACTIONS | BLOCK_HAVE_DATA;
    setBlockIndexValid.insert(pindexNew);
s_nakamoto's avatar
s_nakamoto committed
1921

Pieter Wuille's avatar
Pieter Wuille committed
1922
    if (!pblocktree->WriteBlockIndex(CDiskBlockIndex(pindexNew)))
Pieter Wuille's avatar
Pieter Wuille committed
1923
        return state.Abort(_("Failed to write block index"));
s_nakamoto's avatar
s_nakamoto committed
1924

1925
    // New best?
Pieter Wuille's avatar
Pieter Wuille committed
1926
    if (!ConnectBestBlock(state))
1927
        return false;
s_nakamoto's avatar
s_nakamoto committed
1928
1929
1930
1931
1932

    if (pindexNew == pindexBest)
    {
        // Notify UI to display prev block's coinbase if it was ours
        static uint256 hashPrevBestCoinBase;
Pieter Wuille's avatar
Pieter Wuille committed
1933
        UpdatedTransaction(hashPrevBestCoinBase);
Pieter Wuille's avatar
Pieter Wuille committed
1934
        hashPrevBestCoinBase = GetTxHash(0);
s_nakamoto's avatar
s_nakamoto committed
1935
1936
    }

Pieter Wuille's avatar
Pieter Wuille committed
1937
    if (!pblocktree->Flush())
Pieter Wuille's avatar
Pieter Wuille committed
1938
        return state.Abort(_("Failed to sync block index"));
1939

1940
    uiInterface.NotifyBlocksChanged();
s_nakamoto's avatar
s_nakamoto committed
1941
1942
1943
1944
    return true;
}


Pieter Wuille's avatar
Pieter Wuille committed
1945
bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64 nTime, bool fKnown = false)
Pieter Wuille's avatar
Pieter Wuille committed
1946
1947
1948
1949
1950
{
    bool fUpdatedLast = false;

    LOCK(cs_LastBlockFile);

1951
1952
1953
1954
1955
    if (fKnown) {
        if (nLastBlockFile != pos.nFile) {
            nLastBlockFile = pos.nFile;
            infoLastBlockFile.SetNull();
            pblocktree->ReadBlockFileInfo(nLastBlockFile, infoLastBlockFile);
1956
            fUpdatedLast = true;
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
        }
    } else {
        while (infoLastBlockFile.nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
            printf("Leaving block file %i: %s\n", nLastBlockFile, infoLastBlockFile.ToString().c_str());
            FlushBlockFile();
            nLastBlockFile++;
            infoLastBlockFile.SetNull();
            pblocktree->ReadBlockFileInfo(nLastBlockFile, infoLastBlockFile); // check whether data for the new file somehow already exist; can fail just fine
            fUpdatedLast = true;
        }
        pos.nFile = nLastBlockFile;
        pos.nPos = infoLastBlockFile.nSize;
Pieter Wuille's avatar
Pieter Wuille committed
1969
1970
1971
1972
1973
    }

    infoLastBlockFile.nSize += nAddSize;
    infoLastBlockFile.AddBlock(nHeight, nTime);

1974
1975
1976
1977
    if (!fKnown) {
        unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
        unsigned int nNewChunks = (infoLastBlockFile.nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
        if (nNewChunks > nOldChunks) {
1978
1979
1980
1981
1982
1983
1984
            if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
                FILE *file = OpenBlockFile(pos);
                if (file) {
                    printf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
                    AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
                    fclose(file);
                }
1985
            }
1986
            else
1987
                return state.Error();
1988
1989
1990
        }
    }

1991
    if (!pblocktree->WriteBlockFileInfo(nLastBlockFile, infoLastBlockFile))
Pieter Wuille's avatar
Pieter Wuille committed
1992
        return state.Abort(_("Failed to write file info"));
Pieter Wuille's avatar
Pieter Wuille committed
1993
    if (fUpdatedLast)
1994
        pblocktree->WriteLastBlockFile(nLastBlockFile);
Pieter Wuille's avatar
Pieter Wuille committed
1995
1996
1997
1998

    return true;
}

Pieter Wuille's avatar
Pieter Wuille committed
1999
bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
Pieter Wuille's avatar
Pieter Wuille committed
2000
2001
2002
2003
2004
{
    pos.nFile = nFile;

    LOCK(cs_LastBlockFile);

2005
    unsigned int nNewSize;
Pieter Wuille's avatar
Pieter Wuille committed
2006
2007
    if (nFile == nLastBlockFile) {
        pos.nPos = infoLastBlockFile.nUndoSize;
2008
        nNewSize = (infoLastBlockFile.nUndoSize += nAddSize);
2009
        if (!pblocktree->WriteBlockFileInfo(nLastBlockFile, infoLastBlockFile))
Pieter Wuille's avatar
Pieter Wuille committed
2010
            return state.Abort(_("Failed to write block info"));
2011
2012
    } else {
        CBlockFileInfo info;
2013
        if (!pblocktree->ReadBlockFileInfo(nFile, info))
Pieter Wuille's avatar
Pieter Wuille committed
2014
            return state.Abort(_("Failed to read block info"));
2015
2016
        pos.nPos = info.nUndoSize;
        nNewSize = (info.nUndoSize += nAddSize);
2017
        if (!pblocktree->WriteBlockFileInfo(nFile, info))
Pieter Wuille's avatar
Pieter Wuille committed
2018
            return state.Abort(_("Failed to write block info"));
2019
2020
2021
2022
2023
    }

    unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
    unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
    if (nNewChunks > nOldChunks) {
2024
2025
2026
2027
2028
2029
2030
        if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
            FILE *file = OpenUndoFile(pos);
            if (file) {
                printf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
                AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
                fclose(file);
            }
2031
        }
2032
        else
2033
            return state.Error();
Pieter Wuille's avatar
Pieter Wuille committed
2034
2035
2036
2037
2038
    }

    return true;
}

s_nakamoto's avatar
s_nakamoto committed
2039

Pieter Wuille's avatar
Pieter Wuille committed
2040
bool CBlock::CheckBlock(CValidationState &state, bool fCheckPOW, bool fCheckMerkleRoot) const
s_nakamoto's avatar
s_nakamoto committed
2041
2042
2043
2044
2045
{
    // These are checks that are independent of context
    // that can be verified before saving an orphan block.

    // Size limits
2046
    if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
Pieter Wuille's avatar
Pieter Wuille committed
2047
        return state.DoS(100, error("CheckBlock() : size limits failed"));
s_nakamoto's avatar
s_nakamoto committed
2048

2049
    // Check proof of work matches claimed amount
2050
    if (fCheckPOW && !CheckProofOfWork(GetHash(), nBits))
Pieter Wuille's avatar
Pieter Wuille committed
2051
        return state.DoS(50, error("CheckBlock() : proof of work failed"));
2052

s_nakamoto's avatar
s_nakamoto committed
2053
2054
    // Check timestamp
    if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
Pieter Wuille's avatar
Pieter Wuille committed
2055
        return state.Invalid(error("CheckBlock() : block timestamp too far in the future"));
s_nakamoto's avatar
s_nakamoto committed
2056
2057
2058

    // First transaction must be coinbase, the rest must not be
    if (vtx.empty() || !vtx[0].IsCoinBase())
Pieter Wuille's avatar
Pieter Wuille committed
2059
        return state.DoS(100, error("CheckBlock() : first tx is not coinbase"));
2060
    for (unsigned int i = 1; i < vtx.size(); i++)
s_nakamoto's avatar
s_nakamoto committed
2061
        if (vtx[i].IsCoinBase())
Pieter Wuille's avatar
Pieter Wuille committed
2062
            return state.DoS(100, error("CheckBlock() : more than one coinbase"));
s_nakamoto's avatar
s_nakamoto committed
2063
2064

    // Check transactions
2065
    BOOST_FOREACH(const CTransaction& tx, vtx)
Pieter Wuille's avatar
Pieter Wuille committed
2066
2067
        if (!tx.CheckTransaction(state))
            return error("CheckBlock() : CheckTransaction failed");
s_nakamoto's avatar
s_nakamoto committed
2068

Pieter Wuille's avatar
Pieter Wuille committed
2069
2070
2071
2072
2073
    // Build the merkle tree already. We need it anyway later, and it makes the
    // block cache the transaction hashes, which means they don't need to be
    // recalculated many times during this block's validation.
    BuildMerkleTree();

2074
2075
2076
    // Check for duplicate txids. This is caught by ConnectInputs(),
    // but catching it earlier avoids a potential DoS attack:
    set<uint256> uniqueTx;
Pieter Wuille's avatar
Pieter Wuille committed
2077
2078
    for (unsigned int i=0; i<vtx.size(); i++) {
        uniqueTx.insert(GetTxHash(i));
2079
2080
    }
    if (uniqueTx.size() != vtx.size())
Pieter Wuille's avatar
Pieter Wuille committed
2081
        return state.DoS(100, error("CheckBlock() : duplicate transaction"));
2082

2083
    unsigned int nSigOps = 0;
Gavin Andresen's avatar
Gavin Andresen committed
2084
2085
    BOOST_FOREACH(const CTransaction& tx, vtx)
    {
2086
        nSigOps += tx.GetLegacySigOpCount();
Gavin Andresen's avatar
Gavin Andresen committed
2087
2088
    }
    if (nSigOps > MAX_BLOCK_SIGOPS)
Pieter Wuille's avatar
Pieter Wuille committed
2089
        return state.DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
s_nakamoto's avatar
s_nakamoto committed
2090

2091
    // Check merkle root
2092
    if (fCheckMerkleRoot && hashMerkleRoot != BuildMerkleTree())
Pieter Wuille's avatar
Pieter Wuille committed
2093
        return state.DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
s_nakamoto's avatar
s_nakamoto committed
2094
2095
2096
2097

    return true;
}

Pieter Wuille's avatar
Pieter Wuille committed
2098
bool CBlock::AcceptBlock(CValidationState &state, CDiskBlockPos *dbp)
s_nakamoto's avatar
s_nakamoto committed
2099
2100
2101
2102
{
    // Check for duplicate
    uint256 hash = GetHash();
    if (mapBlockIndex.count(hash))
Pieter Wuille's avatar
Pieter Wuille committed
2103
        return state.Invalid(error("AcceptBlock() : block already in mapBlockIndex"));
s_nakamoto's avatar
s_nakamoto committed
2104
2105

    // Get prev block index
2106
2107
2108
    CBlockIndex* pindexPrev = NULL;
    int nHeight = 0;
    if (hash != hashGenesisBlock) {
2109
2110
        map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
        if (mi == mapBlockIndex.end())
Pieter Wuille's avatar
Pieter Wuille committed
2111
            return state.DoS(10, error("AcceptBlock() : prev block not found"));
2112
2113
2114
2115
2116
        pindexPrev = (*mi).second;
        nHeight = pindexPrev->nHeight+1;

        // Check proof of work
        if (nBits != GetNextWorkRequired(pindexPrev, this))
Pieter Wuille's avatar
Pieter Wuille committed
2117
            return state.DoS(100, error("AcceptBlock() : incorrect proof of work"));
2118
2119
2120

        // Check timestamp against prev
        if (GetBlockTime() <= pindexPrev->GetMedianTimePast())
Pieter Wuille's avatar
Pieter Wuille committed
2121
            return state.Invalid(error("AcceptBlock() : block's timestamp is too early"));
2122
2123
2124
2125

        // Check that all transactions are finalized
        BOOST_FOREACH(const CTransaction& tx, vtx)
            if (!tx.IsFinal(nHeight, GetBlockTime()))
Pieter Wuille's avatar
Pieter Wuille committed
2126
                return state.DoS(10, error("AcceptBlock() : contains a non-final transaction"));
2127
2128
2129

        // Check that the block chain matches the known block chain up to a checkpoint
        if (!Checkpoints::CheckBlock(nHeight, hash))
Pieter Wuille's avatar
Pieter Wuille committed
2130
            return state.DoS(100, error("AcceptBlock() : rejected by checkpoint lock-in at %d", nHeight));
2131
2132
2133

        // Reject block.nVersion=1 blocks when 95% (75% on testnet) of the network has upgraded:
        if (nVersion < 2)
2134
        {
2135
2136
2137
            if ((!fTestNet && CBlockIndex::IsSuperMajority(2, pindexPrev, 950, 1000)) ||
                (fTestNet && CBlockIndex::IsSuperMajority(2, pindexPrev, 75, 100)))
            {
Pieter Wuille's avatar
Pieter Wuille committed
2138
                return state.Invalid(error("AcceptBlock() : rejected nVersion=1 block"));
2139
            }
2140
        }
2141
2142
        // Enforce block.nVersion=2 rule that the coinbase starts with serialized block height
        if (nVersion >= 2)
2143
        {
2144
2145
2146
2147
2148
2149
            // if 750 of the last 1,000 blocks are version 2 or greater (51/100 if testnet):
            if ((!fTestNet && CBlockIndex::IsSuperMajority(2, pindexPrev, 750, 1000)) ||
                (fTestNet && CBlockIndex::IsSuperMajority(2, pindexPrev, 51, 100)))
            {
                CScript expect = CScript() << nHeight;
                if (!std::equal(expect.begin(), expect.end(), vtx[0].vin[0].scriptSig.begin()))
Pieter Wuille's avatar
Pieter Wuille committed
2150
                    return state.DoS(100, error("AcceptBlock() : block height mismatch in coinbase"));
2151
            }
2152
2153
2154
        }
    }

s_nakamoto's avatar
s_nakamoto committed
2155
    // Write block to history file
Pieter Wuille's avatar
Pieter Wuille committed
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
    try {
        unsigned int nBlockSize = ::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION);
        CDiskBlockPos blockPos;
        if (dbp != NULL)
            blockPos = *dbp;
        if (!FindBlockPos(state, blockPos, nBlockSize+8, nHeight, nTime, dbp != NULL))
            return error("AcceptBlock() : FindBlockPos failed");
        if (dbp == NULL)
            if (!WriteToDisk(blockPos))
                return state.Abort(_("Failed to write block"));
        if (!AddToBlockIndex(state, blockPos))
            return error("AcceptBlock() : AddToBlockIndex failed");
    } catch(std::runtime_error &e) {
        return state.Abort(_("System error: ") + e.what());
    }
s_nakamoto's avatar
s_nakamoto committed
2171
2172

    // Relay inventory, but don't relay old inventory during initial block download
2173
    int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
s_nakamoto's avatar
s_nakamoto committed
2174
    if (hashBestChain == hash)
2175
2176
2177
2178
2179
2180
    {
        LOCK(cs_vNodes);
        BOOST_FOREACH(CNode* pnode, vNodes)
            if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
                pnode->PushInventory(CInv(MSG_BLOCK, hash));
    }
s_nakamoto's avatar
s_nakamoto committed
2181
2182
2183
2184

    return true;
}

2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
bool CBlockIndex::IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired, unsigned int nToCheck)
{
    unsigned int nFound = 0;
    for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++)
    {
        if (pstart->nVersion >= minVersion)
            ++nFound;
        pstart = pstart->pprev;
    }
    return (nFound >= nRequired);
}

Pieter Wuille's avatar
Pieter Wuille committed
2197
bool ProcessBlock(CValidationState &state, CNode* pfrom, CBlock* pblock, CDiskBlockPos *dbp)
s_nakamoto's avatar
s_nakamoto committed
2198
2199
2200
2201
{
    // Check for duplicate
    uint256 hash = pblock->GetHash();
    if (mapBlockIndex.count(hash))
Pieter Wuille's avatar
Pieter Wuille committed
2202
        return state.Invalid(error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, BlockHashStr(hash).c_str()));
s_nakamoto's avatar
s_nakamoto committed
2203
    if (mapOrphanBlocks.count(hash))
Pieter Wuille's avatar
Pieter Wuille committed
2204
        return state.Invalid(error("ProcessBlock() : already have block (orphan) %s", BlockHashStr(hash).c_str()));
s_nakamoto's avatar
s_nakamoto committed
2205
2206

    // Preliminary checks
Pieter Wuille's avatar
Pieter Wuille committed
2207
    if (!pblock->CheckBlock(state))
s_nakamoto's avatar
s_nakamoto committed
2208
2209
        return error("ProcessBlock() : CheckBlock FAILED");

2210
2211
2212
2213
    CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(mapBlockIndex);
    if (pcheckpoint && pblock->hashPrevBlock != hashBestChain)
    {
        // Extra checks to prevent "fill up memory by spamming with bogus blocks"
2214
        int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
2215
2216
        if (deltaTime < 0)
        {
Pieter Wuille's avatar
Pieter Wuille committed
2217
            return state.DoS(100, error("ProcessBlock() : block with timestamp before last checkpoint"));
2218
2219
2220
2221
2222
2223
2224
        }
        CBigNum bnNewBlock;
        bnNewBlock.SetCompact(pblock->nBits);
        CBigNum bnRequired;
        bnRequired.SetCompact(ComputeMinWork(pcheckpoint->nBits, deltaTime));
        if (bnNewBlock > bnRequired)
        {
Pieter Wuille's avatar
Pieter Wuille committed
2225
            return state.DoS(100, error("ProcessBlock() : block with too little proof-of-work"));
2226
2227
2228
2229
        }
    }


2230
    // If we don't already have its previous block, shunt it off to holding area until we get it
2231
    if (pblock->hashPrevBlock != 0 && !mapBlockIndex.count(pblock->hashPrevBlock))
s_nakamoto's avatar
s_nakamoto committed
2232
    {
2233
        printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", BlockHashStr(pblock->hashPrevBlock).c_str());
s_nakamoto's avatar
s_nakamoto committed
2234

2235
2236
2237
2238
2239
2240
2241
        // Accept orphans as long as there is a node to request its parents from
        if (pfrom) {
            CBlock* pblock2 = new CBlock(*pblock);
            mapOrphanBlocks.insert(make_pair(hash, pblock2));
            mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));

            // Ask this guy to fill in what we're missing
s_nakamoto's avatar
s_nakamoto committed
2242
            pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
2243
        }
s_nakamoto's avatar
s_nakamoto committed
2244
2245
2246
2247
        return true;
    }

    // Store to disk
Pieter Wuille's avatar
Pieter Wuille committed
2248
    if (!pblock->AcceptBlock(state, dbp))
s_nakamoto's avatar
s_nakamoto committed
2249
2250
2251
2252
2253
        return error("ProcessBlock() : AcceptBlock FAILED");

    // Recursively process any orphan blocks that depended on this one
    vector<uint256> vWorkQueue;
    vWorkQueue.push_back(hash);
2254
    for (unsigned int i = 0; i < vWorkQueue.size(); i++)
s_nakamoto's avatar
s_nakamoto committed
2255
2256
2257
2258
2259
2260
2261
    {
        uint256 hashPrev = vWorkQueue[i];
        for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
             mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
             ++mi)
        {
            CBlock* pblockOrphan = (*mi).second;
Pieter Wuille's avatar
Pieter Wuille committed
2262
            if (pblockOrphan->AcceptBlock(state))
s_nakamoto's avatar
s_nakamoto committed
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
                vWorkQueue.push_back(pblockOrphan->GetHash());
            mapOrphanBlocks.erase(pblockOrphan->GetHash());
            delete pblockOrphan;
        }
        mapOrphanBlocksByPrev.erase(hashPrev);
    }

    printf("ProcessBlock: ACCEPTED\n");
    return true;
}








2281
2282
2283
2284
CMerkleBlock::CMerkleBlock(const CBlock& block, CBloomFilter& filter)
{
    header = block.GetBlockHeader();

2285
2286
2287
2288
2289
2290
2291
    vector<bool> vMatch;
    vector<uint256> vHashes;

    vMatch.reserve(block.vtx.size());
    vHashes.reserve(block.vtx.size());

    for (unsigned int i = 0; i < block.vtx.size(); i++)
2292
2293
2294
2295
    {
        uint256 hash = block.vtx[i].GetHash();
        if (filter.IsRelevantAndUpdate(block.vtx[i], hash))
        {
2296
2297
            vMatch.push_back(true);
            vMatchedTxn.push_back(make_pair(i, hash));
2298
        }
2299
2300
2301
        else
            vMatch.push_back(false);
        vHashes.push_back(hash);
2302
    }
2303
2304

    txn = CPartialMerkleTree(vHashes, vMatch);
2305
2306
2307
2308
2309
2310
2311
2312
2313
}








Pieter Wuille's avatar
Pieter Wuille committed
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
uint256 CPartialMerkleTree::CalcHash(int height, unsigned int pos, const std::vector<uint256> &vTxid) {
    if (height == 0) {
        // hash at height 0 is the txids themself
        return vTxid[pos];
    } else {
        // calculate left hash
        uint256 left = CalcHash(height-1, pos*2, vTxid), right;
        // calculate right hash if not beyong the end of the array - copy left hash otherwise1
        if (pos*2+1 < CalcTreeWidth(height-1))
            right = CalcHash(height-1, pos*2+1, vTxid);
        else
            right = left;
        // combine subhashes
        return Hash(BEGIN(left), END(left), BEGIN(right), END(right));
    }
}

void CPartialMerkleTree::TraverseAndBuild(int height, unsigned int pos, const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch) {
    // determine whether this node is the parent of at least one matched txid
    bool fParentOfMatch = false;
    for (unsigned int p = pos << height; p < (pos+1) << height && p < nTransactions; p++)
        fParentOfMatch |= vMatch[p];
    // store as flag bit
    vBits.push_back(fParentOfMatch);
    if (height==0 || !fParentOfMatch) {
        // if at height 0, or nothing interesting below, store hash and stop
        vHash.push_back(CalcHash(height, pos, vTxid));
    } else {
        // otherwise, don't store any hash, but descend into the subtrees
        TraverseAndBuild(height-1, pos*2, vTxid, vMatch);
        if (pos*2+1 < CalcTreeWidth(height-1))
            TraverseAndBuild(height-1, pos*2+1, vTxid, vMatch);
    }
}

uint256 CPartialMerkleTree::TraverseAndExtract(int height, unsigned int pos, unsigned int &nBitsUsed, unsigned int &nHashUsed, std::vector<uint256> &vMatch) {
    if (nBitsUsed >= vBits.size()) {
        // overflowed the bits array - failure
        fBad = true;
        return 0;
    }
    bool fParentOfMatch = vBits[nBitsUsed++];
    if (height==0 || !fParentOfMatch) {
        // if at height 0, or nothing interesting below, use stored hash and do not descend
        if (nHashUsed >= vHash.size()) {
            // overflowed the hash array - failure
            fBad = true;
            return 0;
        }
        const uint256 &hash = vHash[nHashUsed++];
        if (height==0 && fParentOfMatch) // in case of height 0, we have a matched txid
            vMatch.push_back(hash);
        return hash;
    } else {
        // otherwise, descend into the subtrees to extract matched txids and hashes
        uint256 left = TraverseAndExtract(height-1, pos*2, nBitsUsed, nHashUsed, vMatch), right;
        if (pos*2+1 < CalcTreeWidth(height-1))
            right = TraverseAndExtract(height-1, pos*2+1, nBitsUsed, nHashUsed, vMatch);
        else
            right = left;
        // and combine them before returning
        return Hash(BEGIN(left), END(left), BEGIN(right), END(right));
    }
}

CPartialMerkleTree::CPartialMerkleTree(const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch) : nTransactions(vTxid.size()), fBad(false) {
    // reset state
    vBits.clear();
    vHash.clear();

    // calculate height of tree
    int nHeight = 0;
    while (CalcTreeWidth(nHeight) > 1)
        nHeight++;

    // traverse the partial tree
    TraverseAndBuild(nHeight, 0, vTxid, vMatch);
}

CPartialMerkleTree::CPartialMerkleTree() : nTransactions(0), fBad(true) {}

uint256 CPartialMerkleTree::ExtractMatches(std::vector<uint256> &vMatch) {
    vMatch.clear();
    // An empty set will not work
    if (nTransactions == 0)
        return 0;
    // check for excessively high numbers of transactions
    if (nTransactions > MAX_BLOCK_SIZE / 60) // 60 is the lower bound for the size of a serialized CTransaction
        return 0;
    // there can never be more hashes provided than one for every txid
    if (vHash.size() > nTransactions)
        return 0;
    // there must be at least one bit per node in the partial tree, and at least one node per hash
    if (vBits.size() < vHash.size())
        return 0;
    // calculate height of tree
    int nHeight = 0;
    while (CalcTreeWidth(nHeight) > 1)
        nHeight++;
    // traverse the partial tree
    unsigned int nBitsUsed = 0, nHashUsed = 0;
    uint256 hashMerkleRoot = TraverseAndExtract(nHeight, 0, nBitsUsed, nHashUsed, vMatch);
    // verify that no problems occured during the tree traversal
    if (fBad)
        return 0;
    // verify that all bits were consumed (except for the padding caused by serializing it as a byte sequence)
    if ((nBitsUsed+7)/8 != (vBits.size()+7)/8)
        return 0;
    // verify that all hashes were consumed
    if (nHashUsed != vHash.size())
        return 0;
    return hashMerkleRoot;
}







2434
2435
2436
2437
bool AbortNode(const std::string &strMessage) {
    fRequestShutdown = true;
    strMiscWarning = strMessage;
    printf("*** %s\n", strMessage.c_str());
Pieter Wuille's avatar
Pieter Wuille committed
2438
    uiInterface.ThreadSafeMessageBox(strMessage, "", CClientUIInterface::MSG_ERROR | CClientUIInterface::MODAL);
2439
2440
2441
    StartShutdown();
    return false;
}
Pieter Wuille's avatar
Pieter Wuille committed
2442

2443
bool CheckDiskSpace(uint64 nAdditionalBytes)
s_nakamoto's avatar
s_nakamoto committed
2444
{
2445
    uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
s_nakamoto's avatar
s_nakamoto committed
2446

2447
2448
    // Check for nMinDiskSpace bytes (currently 50MB)
    if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
2449
2450
        return AbortNode(_("Error: Disk space is low!"));

s_nakamoto's avatar
s_nakamoto committed
2451
2452
2453
    return true;
}

Pieter Wuille's avatar
Pieter Wuille committed
2454
2455
2456
2457
2458
CCriticalSection cs_LastBlockFile;
CBlockFileInfo infoLastBlockFile;
int nLastBlockFile = 0;

FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
2459
{
Pieter Wuille's avatar
Pieter Wuille committed
2460
    if (pos.IsNull())
s_nakamoto's avatar
s_nakamoto committed
2461
        return NULL;
Pieter Wuille's avatar
Pieter Wuille committed
2462
2463
2464
2465
2466
    boost::filesystem::path path = GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
    boost::filesystem::create_directories(path.parent_path());
    FILE* file = fopen(path.string().c_str(), "rb+");
    if (!file && !fReadOnly)
        file = fopen(path.string().c_str(), "wb+");
Pieter Wuille's avatar
Pieter Wuille committed
2467
2468
    if (!file) {
        printf("Unable to open file %s\n", path.string().c_str());
s_nakamoto's avatar
s_nakamoto committed
2469
        return NULL;
Pieter Wuille's avatar
Pieter Wuille committed
2470
    }
Pieter Wuille's avatar
Pieter Wuille committed
2471
2472
2473
2474
2475
2476
2477
    if (pos.nPos) {
        if (fseek(file, pos.nPos, SEEK_SET)) {
            printf("Unable to seek to position %u of %s\n", pos.nPos, path.string().c_str());
            fclose(file);
            return NULL;
        }
    }
s_nakamoto's avatar
s_nakamoto committed
2478
2479
2480
    return file;
}

Pieter Wuille's avatar
Pieter Wuille committed
2481
2482
2483
2484
2485
2486
2487
2488
FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
    return OpenDiskFile(pos, "blk", fReadOnly);
}

FILE *OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
    return OpenDiskFile(pos, "rev", fReadOnly);
}

2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
CBlockIndex * InsertBlockIndex(uint256 hash)
{
    if (hash == 0)
        return NULL;

    // Return existing
    map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
    if (mi != mapBlockIndex.end())
        return (*mi).second;

    // Create new
    CBlockIndex* pindexNew = new CBlockIndex();
    if (!pindexNew)
        throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
    mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
    pindexNew->phashBlock = &((*mi).first);

    return pindexNew;
}

bool static LoadBlockIndexDB()
{
    if (!pblocktree->LoadBlockIndexGuts())
        return false;

    if (fRequestShutdown)
        return true;

    // Calculate bnChainWork
    vector<pair<int, CBlockIndex*> > vSortedByHeight;
    vSortedByHeight.reserve(mapBlockIndex.size());
    BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
    {
        CBlockIndex* pindex = item.second;
        vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
    }
    sort(vSortedByHeight.begin(), vSortedByHeight.end());
    BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
    {
        CBlockIndex* pindex = item.second;
        pindex->bnChainWork = (pindex->pprev ? pindex->pprev->bnChainWork : 0) + pindex->GetBlockWork();
        pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
        if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS && !(pindex->nStatus & BLOCK_FAILED_MASK))
            setBlockIndexValid.insert(pindex);
    }

    // Load block file info
    pblocktree->ReadLastBlockFile(nLastBlockFile);
    printf("LoadBlockIndex(): last block file = %i\n", nLastBlockFile);
    if (pblocktree->ReadBlockFileInfo(nLastBlockFile, infoLastBlockFile))
        printf("LoadBlockIndex(): last block file: %s\n", infoLastBlockFile.ToString().c_str());
2540

2541
2542
2543
2544
2545
2546
2547
2548
    // Load bnBestInvalidWork, OK if it doesn't exist
    pblocktree->ReadBestInvalidWork(bnBestInvalidWork);

    // Check whether we need to continue reindexing
    bool fReindexing = false;
    pblocktree->ReadReindexing(fReindexing);
    fReindex |= fReindexing;

2549
2550
2551
2552
    // Check whether we have a transaction index
    pblocktree->ReadFlag("txindex", fTxIndex);
    printf("LoadBlockIndex(): transaction index %s\n", fTxIndex ? "enabled" : "disabled");

2553
2554
2555
    // Load hashBestChain pointer to end of best chain
    pindexBest = pcoinsTip->GetBestBlock();
    if (pindexBest == NULL)
2556
        return true;
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
    hashBestChain = pindexBest->GetBlockHash();
    nBestHeight = pindexBest->nHeight;
    bnBestChainWork = pindexBest->bnChainWork;

    // set 'next' pointers in best chain
    CBlockIndex *pindex = pindexBest;
    while(pindex != NULL && pindex->pprev != NULL) {
         CBlockIndex *pindexPrev = pindex->pprev;
         pindexPrev->pnext = pindex;
         pindex = pindexPrev;
    }
    printf("LoadBlockIndex(): hashBestChain=%s  height=%d date=%s\n",
2569
        BlockHashStr(hashBestChain).c_str(), nBestHeight,
2570
        DateTimeStrFormat("%Y-%m-%d %H:%M:%S", pindexBest->GetBlockTime()).c_str());
2571

Pieter Wuille's avatar
Pieter Wuille committed
2572
2573
2574
2575
2576
2577
2578
    return true;
}

bool VerifyDB() {
    if (pindexBest == NULL || pindexBest->pprev == NULL)
        return true;

2579
    // Verify blocks in the best chain
Pieter Wuille's avatar
Pieter Wuille committed
2580
    int nCheckLevel = GetArg("-checklevel", 3);
2581
    int nCheckDepth = GetArg( "-checkblocks", 288);
2582
2583
2584
2585
    if (nCheckDepth == 0)
        nCheckDepth = 1000000000; // suffices until the year 19000
    if (nCheckDepth > nBestHeight)
        nCheckDepth = nBestHeight;
Pieter Wuille's avatar
Pieter Wuille committed
2586
    nCheckLevel = std::max(0, std::min(4, nCheckLevel));
2587
    printf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
Pieter Wuille's avatar
Pieter Wuille committed
2588
2589
2590
2591
    CCoinsViewCache coins(*pcoinsTip, true);
    CBlockIndex* pindexState = pindexBest;
    CBlockIndex* pindexFailure = NULL;
    int nGoodTransactions = 0;
Pieter Wuille's avatar
Pieter Wuille committed
2592
    CValidationState state;
2593
2594
2595
2596
2597
    for (CBlockIndex* pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev)
    {
        if (fRequestShutdown || pindex->nHeight < nBestHeight-nCheckDepth)
            break;
        CBlock block;
Pieter Wuille's avatar
Pieter Wuille committed
2598
        // check level 0: read from disk
2599
        if (!block.ReadFromDisk(pindex))
Pieter Wuille's avatar
Pieter Wuille committed
2600
            return error("VerifyDB() : *** block.ReadFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
2601
        // check level 1: verify block validity
Pieter Wuille's avatar
Pieter Wuille committed
2602
        if (nCheckLevel >= 1 && !block.CheckBlock(state))
Pieter Wuille's avatar
Pieter Wuille committed
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
            return error("VerifyDB() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
        // check level 2: verify undo validity
        if (nCheckLevel >= 2 && pindex) {
            CBlockUndo undo;
            CDiskBlockPos pos = pindex->GetUndoPos();
            if (!pos.IsNull()) {
                if (!undo.ReadFromDisk(pos, pindex->pprev->GetBlockHash()))
                    return error("VerifyDB() : *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
            }
        }
        // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
        if (nCheckLevel >= 3 && pindex == pindexState && (coins.GetCacheSize() + pcoinsTip->GetCacheSize()) <= 2*nCoinCacheSize + 32000) {
            bool fClean = true;
Pieter Wuille's avatar
Pieter Wuille committed
2616
            if (!block.DisconnectBlock(state, pindex, coins, &fClean))
Pieter Wuille's avatar
Pieter Wuille committed
2617
2618
2619
2620
2621
2622
2623
                return error("VerifyDB() : *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
            pindexState = pindex->pprev;
            if (!fClean) {
                nGoodTransactions = 0;
                pindexFailure = pindex;
            } else
                nGoodTransactions += block.vtx.size();
2624
2625
        }
    }
Pieter Wuille's avatar
Pieter Wuille committed
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
    if (pindexFailure)
        return error("VerifyDB() : *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", pindexBest->nHeight - pindexFailure->nHeight + 1, nGoodTransactions);

    // check level 4: try reconnecting blocks
    if (nCheckLevel >= 4) {
        CBlockIndex *pindex = pindexState;
        while (pindex != pindexBest && !fRequestShutdown) {
             pindex = pindex->pnext;
             CBlock block;
             if (!block.ReadFromDisk(pindex))
                 return error("VerifyDB() : *** block.ReadFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
Pieter Wuille's avatar
Pieter Wuille committed
2637
             if (!block.ConnectBlock(state, pindex, coins))
Pieter Wuille's avatar
Pieter Wuille committed
2638
2639
                 return error("VerifyDB() : *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
        }
2640
2641
    }

Pieter Wuille's avatar
Pieter Wuille committed
2642
2643
    printf("No coin database inconsistencies in last %i blocks (%i transactions)\n", pindexBest->nHeight - pindexState->nHeight, nGoodTransactions);

2644
2645
2646
    return true;
}

2647
bool LoadBlockIndex()
s_nakamoto's avatar
s_nakamoto committed
2648
{
2649
2650
    if (fTestNet)
    {
2651
2652
2653
2654
        pchMessageStart[0] = 0x0b;
        pchMessageStart[1] = 0x11;
        pchMessageStart[2] = 0x09;
        pchMessageStart[3] = 0x07;
Gavin Andresen's avatar
Gavin Andresen committed
2655
        hashGenesisBlock = uint256("000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943");
2656
2657
    }

s_nakamoto's avatar
s_nakamoto committed
2658
    //
2659
    // Load block index from databases
s_nakamoto's avatar
s_nakamoto committed
2660
    //
2661
    if (!fReindex && !LoadBlockIndexDB())
s_nakamoto's avatar
s_nakamoto committed
2662
2663
2664
2665
2666
2667
2668
        return false;

    //
    // Init with genesis block
    //
    if (mapBlockIndex.empty())
    {
2669
2670
2671
2672
2673
2674
2675
        fTxIndex = GetBoolArg("-txindex", false);
        pblocktree->WriteFlag("txindex", fTxIndex);
        printf("Initializing databases...\n");

        if (fReindex)
            return true;

s_nakamoto's avatar
s_nakamoto committed
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
        // Genesis Block:
        // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
        //   CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
        //     CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
        //     CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
        //   vMerkleTree: 4a5e1e

        // Genesis block
        const char* pszTimestamp = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks";
        CTransaction txNew;
        txNew.vin.resize(1);
        txNew.vout.resize(1);
        txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
        txNew.vout[0].nValue = 50 * COIN;
        txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG;
        CBlock block;
        block.vtx.push_back(txNew);
        block.hashPrevBlock = 0;
        block.hashMerkleRoot = block.BuildMerkleTree();
        block.nVersion = 1;
        block.nTime    = 1231006505;
        block.nBits    = 0x1d00ffff;
        block.nNonce   = 2083236893;

2700
2701
        if (fTestNet)
        {
2702
            block.nTime    = 1296688602;
Gavin Andresen's avatar
Gavin Andresen committed
2703
            block.nNonce   = 414098458;
2704
        }
s_nakamoto's avatar
s_nakamoto committed
2705

2706
        //// debug print
Pieter Wuille's avatar
Pieter Wuille committed
2707
2708
        uint256 hash = block.GetHash();
        printf("%s\n", hash.ToString().c_str());
2709
2710
2711
2712
        printf("%s\n", hashGenesisBlock.ToString().c_str());
        printf("%s\n", block.hashMerkleRoot.ToString().c_str());
        assert(block.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));
        block.print();
Pieter Wuille's avatar
Pieter Wuille committed
2713
        assert(hash == hashGenesisBlock);
s_nakamoto's avatar
s_nakamoto committed
2714
2715

        // Start new block file
Pieter Wuille's avatar
Pieter Wuille committed
2716
2717
        unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
        CDiskBlockPos blockPos;
Pieter Wuille's avatar
Pieter Wuille committed
2718
2719
        CValidationState state;
        if (!FindBlockPos(state, blockPos, nBlockSize+8, 0, block.nTime))
2720
            return error("AcceptBlock() : FindBlockPos failed");
Pieter Wuille's avatar
Pieter Wuille committed
2721
        if (!block.WriteToDisk(blockPos))
s_nakamoto's avatar
s_nakamoto committed
2722
            return error("LoadBlockIndex() : writing genesis block to disk failed");
Pieter Wuille's avatar
Pieter Wuille committed
2723
        if (!block.AddToBlockIndex(state, blockPos))
s_nakamoto's avatar
s_nakamoto committed
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
            return error("LoadBlockIndex() : genesis block not accepted");
    }

    return true;
}



void PrintBlockTree()
{
2734
    // pre-compute tree structure
s_nakamoto's avatar
s_nakamoto committed
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
    map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
    for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
    {
        CBlockIndex* pindex = (*mi).second;
        mapNext[pindex->pprev].push_back(pindex);
        // test
        //while (rand() % 3 == 0)
        //    mapNext[pindex->pprev].push_back(pindex);
    }

    vector<pair<int, CBlockIndex*> > vStack;
    vStack.push_back(make_pair(0, pindexGenesisBlock));

    int nPrevCol = 0;
    while (!vStack.empty())
    {
        int nCol = vStack.back().first;
        CBlockIndex* pindex = vStack.back().second;
        vStack.pop_back();

        // print split or gap
        if (nCol > nPrevCol)
        {
            for (int i = 0; i < nCol-1; i++)
                printf("| ");
            printf("|\\\n");
        }
        else if (nCol < nPrevCol)
        {
            for (int i = 0; i < nCol; i++)
                printf("| ");
            printf("|\n");
Pieter Wuille's avatar
Pieter Wuille committed
2767
       }
s_nakamoto's avatar
s_nakamoto committed
2768
2769
2770
2771
2772
2773
2774
2775
2776
        nPrevCol = nCol;

        // print columns
        for (int i = 0; i < nCol; i++)
            printf("| ");

        // print item
        CBlock block;
        block.ReadFromDisk(pindex);
Pieter Wuille's avatar
Pieter Wuille committed
2777
        printf("%d (blk%05u.dat:0x%x)  %s  tx %"PRIszu"",
s_nakamoto's avatar
s_nakamoto committed
2778
            pindex->nHeight,
Pieter Wuille's avatar
Pieter Wuille committed
2779
            pindex->GetBlockPos().nFile, pindex->GetBlockPos().nPos,
2780
            DateTimeStrFormat("%Y-%m-%d %H:%M:%S", block.GetBlockTime()).c_str(),
s_nakamoto's avatar
s_nakamoto committed
2781
2782
            block.vtx.size());

Pieter Wuille's avatar
Pieter Wuille committed
2783
        PrintWallets(block);
s_nakamoto's avatar
s_nakamoto committed
2784

2785
        // put the main time-chain first
s_nakamoto's avatar
s_nakamoto committed
2786
        vector<CBlockIndex*>& vNext = mapNext[pindex];
2787
        for (unsigned int i = 0; i < vNext.size(); i++)
s_nakamoto's avatar
s_nakamoto committed
2788
2789
2790
2791
2792
2793
2794
2795
2796
        {
            if (vNext[i]->pnext)
            {
                swap(vNext[0], vNext[i]);
                break;
            }
        }

        // iterate children
2797
        for (unsigned int i = 0; i < vNext.size(); i++)
s_nakamoto's avatar
s_nakamoto committed
2798
2799
2800
2801
            vStack.push_back(make_pair(nCol+i, vNext[i]));
    }
}

2802
bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp)
2803
{
2804
2805
    int64 nStart = GetTimeMillis();

2806
    int nLoaded = 0;
Pieter Wuille's avatar
Pieter Wuille committed
2807
    try {
2808
        CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SIZE, MAX_BLOCK_SIZE+8, SER_DISK, CLIENT_VERSION);
2809
2810
2811
2812
2813
2814
2815
2816
2817
        uint64 nStartByte = 0;
        if (dbp) {
            // (try to) skip already indexed part
            CBlockFileInfo info;
            if (pblocktree->ReadBlockFileInfo(dbp->nFile, info)) {
                nStartByte = info.nSize;
                blkdat.Seek(info.nSize);
            }
        }
2818
        uint64 nRewind = blkdat.GetPos();
2819
        while (blkdat.good() && !blkdat.eof() && !fRequestShutdown) {
2820
2821
2822
            blkdat.SetPos(nRewind);
            nRewind++; // start one byte further next time, in case of failure
            blkdat.SetLimit(); // remove former limit
2823
            unsigned int nSize = 0;
2824
2825
2826
2827
2828
2829
2830
2831
2832
            try {
                // locate a header
                unsigned char buf[4];
                blkdat.FindByte(pchMessageStart[0]);
                nRewind = blkdat.GetPos()+1;
                blkdat >> FLATDATA(buf);
                if (memcmp(buf, pchMessageStart, 4))
                    continue;
                // read size
2833
                blkdat >> nSize;
2834
2835
                if (nSize < 80 || nSize > MAX_BLOCK_SIZE)
                    continue;
2836
2837
2838
2839
2840
            } catch (std::exception &e) {
                // no valid block header found; don't complain
                break;
            }
            try {
2841
                // read block
2842
2843
                uint64 nBlockPos = blkdat.GetPos();
                blkdat.SetLimit(nBlockPos + nSize);
2844
2845
2846
                CBlock block;
                blkdat >> block;
                nRewind = blkdat.GetPos();
2847
2848
2849

                // process block
                if (nBlockPos >= nStartByte) {
2850
                    LOCK(cs_main);
2851
2852
                    if (dbp)
                        dbp->nPos = nBlockPos;
Pieter Wuille's avatar
Pieter Wuille committed
2853
2854
                    CValidationState state;
                    if (ProcessBlock(state, NULL, &block, dbp))
2855
                        nLoaded++;
Pieter Wuille's avatar
Pieter Wuille committed
2856
2857
                    if (state.IsError())
                        break;
2858
                }
2859
2860
            } catch (std::exception &e) {
                printf("%s() : Deserialize or I/O error caught during load\n", __PRETTY_FUNCTION__);
2861
2862
            }
        }
2863
        fclose(fileIn);
Pieter Wuille's avatar
Pieter Wuille committed
2864
2865
    } catch(std::runtime_error &e) {
        AbortNode(_("Error: system error: ") + e.what());
2866
    }
2867
2868
    if (nLoaded > 0)
        printf("Loaded %i blocks from external file in %"PRI64d"ms\n", nLoaded, GetTimeMillis() - nStart);
2869
2870
    return nLoaded > 0;
}
s_nakamoto's avatar
s_nakamoto committed
2871

2872

s_nakamoto's avatar
s_nakamoto committed
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885








//////////////////////////////////////////////////////////////////////////////
//
// CAlert
//

2886
2887
extern map<uint256, CAlert> mapAlerts;
extern CCriticalSection cs_mapAlerts;
s_nakamoto's avatar
s_nakamoto committed
2888
2889
2890
2891
2892
2893

string GetWarnings(string strFor)
{
    int nPriority = 0;
    string strStatusBar;
    string strRPC;
2894

2895
    if (GetBoolArg("-testsafemode"))
s_nakamoto's avatar
s_nakamoto committed
2896
2897
        strRPC = "test";

2898
2899
2900
    if (!CLIENT_VERSION_IS_RELEASE)
        strStatusBar = _("This is a pre-release test build - use at your own risk - do not use for mining or merchant applications");

s_nakamoto's avatar
s_nakamoto committed
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
    // Misc warnings like out of disk space and clock is wrong
    if (strMiscWarning != "")
    {
        nPriority = 1000;
        strStatusBar = strMiscWarning;
    }

    // Longer invalid proof-of-work chain
    if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
    {
        nPriority = 2000;
2912
        strStatusBar = strRPC = _("Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.");
s_nakamoto's avatar
s_nakamoto committed
2913
2914
2915
2916
    }

    // Alerts
    {
2917
        LOCK(cs_mapAlerts);
2918
        BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
s_nakamoto's avatar
s_nakamoto committed
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
        {
            const CAlert& alert = item.second;
            if (alert.AppliesToMe() && alert.nPriority > nPriority)
            {
                nPriority = alert.nPriority;
                strStatusBar = alert.strStatusBar;
            }
        }
    }

    if (strFor == "statusbar")
        return strStatusBar;
    else if (strFor == "rpc")
        return strRPC;
2933
    assert(!"GetWarnings() : invalid parameter");
s_nakamoto's avatar
s_nakamoto committed
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
    return "error";
}








//////////////////////////////////////////////////////////////////////////////
//
// Messages
//


2950
bool static AlreadyHave(const CInv& inv)
s_nakamoto's avatar
s_nakamoto committed
2951
2952
2953
{
    switch (inv.type)
    {
Jeff Garzik's avatar
Jeff Garzik committed
2954
2955
    case MSG_TX:
        {
Pieter Wuille's avatar
Pieter Wuille committed
2956
            bool txInMap = false;
2957
            {
Pieter Wuille's avatar
Pieter Wuille committed
2958
2959
                LOCK(mempool.cs);
                txInMap = mempool.exists(inv.hash);
2960
            }
Pieter Wuille's avatar
Pieter Wuille committed
2961
            return txInMap || mapOrphanTransactions.count(inv.hash) ||
2962
                pcoinsTip->HaveCoins(inv.hash);
Jeff Garzik's avatar
Jeff Garzik committed
2963
2964
2965
2966
        }
    case MSG_BLOCK:
        return mapBlockIndex.count(inv.hash) ||
               mapOrphanBlocks.count(inv.hash);
s_nakamoto's avatar
s_nakamoto committed
2967
2968
2969
2970
2971
2972
2973
2974
    }
    // Don't know what it is, just say we already got one
    return true;
}




2975
// The message start string is designed to be unlikely to occur in normal data.
2976
// The characters are rarely used upper ASCII, not valid as UTF-8, and produce
2977
// a large 4-byte int at any alignment.
2978
unsigned char pchMessageStart[4] = { 0xf9, 0xbe, 0xb4, 0xd9 };
s_nakamoto's avatar
s_nakamoto committed
2979
2980


Pieter Wuille's avatar
Pieter Wuille committed
2981
bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
s_nakamoto's avatar
s_nakamoto committed
2982
2983
{
    RandAddSeedPerfmon();
2984
    if (fDebug)
2985
        printf("received: %s (%"PRIszu" bytes)\n", strCommand.c_str(), vRecv.size());
s_nakamoto's avatar
s_nakamoto committed
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
    if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
    {
        printf("dropmessagestest DROPPING RECV MESSAGE\n");
        return true;
    }





    if (strCommand == "version")
    {
        // Each connection can only send one version message
        if (pfrom->nVersion != 0)
3000
3001
        {
            pfrom->Misbehaving(1);
s_nakamoto's avatar
s_nakamoto committed
3002
            return false;
3003
        }
s_nakamoto's avatar
s_nakamoto committed
3004

3005
        int64 nTime;
s_nakamoto's avatar
s_nakamoto committed
3006
3007
        CAddress addrMe;
        CAddress addrFrom;
3008
        uint64 nNonce = 1;
s_nakamoto's avatar
s_nakamoto committed
3009
        vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
3010
        if (pfrom->nVersion < MIN_PROTO_VERSION)
Pieter Wuille's avatar
Pieter Wuille committed
3011
        {
Michael Ford's avatar
Michael Ford committed
3012
            // Since February 20, 2012, the protocol is initiated at version 209,
Pieter Wuille's avatar
Pieter Wuille committed
3013
3014
3015
3016
3017
3018
            // and earlier versions are no longer supported
            printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
            pfrom->fDisconnect = true;
            return false;
        }

s_nakamoto's avatar
s_nakamoto committed
3019
3020
        if (pfrom->nVersion == 10300)
            pfrom->nVersion = 300;
Pieter Wuille's avatar
Pieter Wuille committed
3021
        if (!vRecv.empty())
s_nakamoto's avatar
s_nakamoto committed
3022
            vRecv >> addrFrom >> nNonce;
Pieter Wuille's avatar
Pieter Wuille committed
3023
        if (!vRecv.empty())
s_nakamoto's avatar
s_nakamoto committed
3024
            vRecv >> pfrom->strSubVer;
Pieter Wuille's avatar
Pieter Wuille committed
3025
        if (!vRecv.empty())
s_nakamoto's avatar
s_nakamoto committed
3026
            vRecv >> pfrom->nStartingHeight;
3027
3028
3029
3030
        if (!vRecv.empty())
            vRecv >> pfrom->fRelayTxes; // set to true after we get the first filter* message
        else
            pfrom->fRelayTxes = true;
s_nakamoto's avatar
s_nakamoto committed
3031

3032
3033
3034
3035
3036
3037
        if (pfrom->fInbound && addrMe.IsRoutable())
        {
            pfrom->addrLocal = addrMe;
            SeenLocal(addrMe);
        }

s_nakamoto's avatar
s_nakamoto committed
3038
3039
3040
        // Disconnect if we connected to ourself
        if (nNonce == nLocalHostNonce && nNonce > 1)
        {
3041
            printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
s_nakamoto's avatar
s_nakamoto committed
3042
3043
3044
3045
            pfrom->fDisconnect = true;
            return true;
        }

Gavin Andresen's avatar
Gavin Andresen committed
3046
3047
3048
3049
        // Be shy and don't send version until we hear
        if (pfrom->fInbound)
            pfrom->PushVersion();

s_nakamoto's avatar
s_nakamoto committed
3050
3051
        pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);

Pieter Wuille's avatar
Pieter Wuille committed
3052
        AddTimeData(pfrom->addr, nTime);
s_nakamoto's avatar
s_nakamoto committed
3053
3054

        // Change version
Pieter Wuille's avatar
Pieter Wuille committed
3055
        pfrom->PushMessage("verack");
3056
        pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
s_nakamoto's avatar
s_nakamoto committed
3057

s_nakamoto's avatar
s_nakamoto committed
3058
3059
3060
        if (!pfrom->fInbound)
        {
            // Advertise our address
Pieter Wuille's avatar
Pieter Wuille committed
3061
            if (!fNoListen && !IsInitialBlockDownload())
s_nakamoto's avatar
s_nakamoto committed
3062
            {
3063
3064
3065
                CAddress addr = GetLocalAddress(&pfrom->addr);
                if (addr.IsRoutable())
                    pfrom->PushAddress(addr);
s_nakamoto's avatar
s_nakamoto committed
3066
3067
3068
            }

            // Get recent addresses
3069
            if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
s_nakamoto's avatar
s_nakamoto committed
3070
3071
3072
3073
            {
                pfrom->PushMessage("getaddr");
                pfrom->fGetAddr = true;
            }
3074
3075
3076
3077
3078
3079
3080
            addrman.Good(pfrom->addr);
        } else {
            if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
            {
                addrman.Add(addrFrom, addrFrom);
                addrman.Good(addrFrom);
            }
s_nakamoto's avatar
s_nakamoto committed
3081
3082
        }

s_nakamoto's avatar
s_nakamoto committed
3083
        // Ask the first connected node for block updates
3084
        static int nAskedForBlocks = 0;
3085
        if (!pfrom->fClient && !pfrom->fOneShot && !fImporting && !fReindex &&
3086
            (pfrom->nStartingHeight > (nBestHeight - 144)) &&
3087
            (pfrom->nVersion < NOBLKS_VERSION_START ||
3088
             pfrom->nVersion >= NOBLKS_VERSION_END) &&
3089
             (nAskedForBlocks < 1 || vNodes.size() <= 1))
s_nakamoto's avatar
s_nakamoto committed
3090
3091
3092
3093
3094
3095
        {
            nAskedForBlocks++;
            pfrom->PushGetBlocks(pindexBest, uint256(0));
        }

        // Relay alerts
3096
3097
        {
            LOCK(cs_mapAlerts);
3098
            BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
s_nakamoto's avatar
s_nakamoto committed
3099
                item.second.RelayTo(pfrom);
3100
        }
s_nakamoto's avatar
s_nakamoto committed
3101
3102
3103

        pfrom->fSuccessfullyConnected = true;

Pieter Wuille's avatar
Pieter Wuille committed
3104
        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());
3105
3106

        cPeerBlockCounts.input(pfrom->nStartingHeight);
s_nakamoto's avatar
s_nakamoto committed
3107
3108
3109
3110
3111
3112
    }


    else if (pfrom->nVersion == 0)
    {
        // Must have a version message before anything else
3113
        pfrom->Misbehaving(1);
s_nakamoto's avatar
s_nakamoto committed
3114
3115
3116
3117
3118
3119
        return false;
    }


    else if (strCommand == "verack")
    {
3120
        pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
s_nakamoto's avatar
s_nakamoto committed
3121
3122
3123
3124
3125
3126
3127
    }


    else if (strCommand == "addr")
    {
        vector<CAddress> vAddr;
        vRecv >> vAddr;
s_nakamoto's avatar
s_nakamoto committed
3128
3129

        // Don't want addr from older versions unless seeding
3130
        if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
s_nakamoto's avatar
s_nakamoto committed
3131
3132
            return true;
        if (vAddr.size() > 1000)
3133
3134
        {
            pfrom->Misbehaving(20);
3135
            return error("message addr size() = %"PRIszu"", vAddr.size());
3136
        }
s_nakamoto's avatar
s_nakamoto committed
3137
3138

        // Store the new addresses
3139
        vector<CAddress> vAddrOk;
3140
3141
        int64 nNow = GetAdjustedTime();
        int64 nSince = nNow - 10 * 60;
3142
        BOOST_FOREACH(CAddress& addr, vAddr)
s_nakamoto's avatar
s_nakamoto committed
3143
3144
3145
        {
            if (fShutdown)
                return true;
s_nakamoto's avatar
s_nakamoto committed
3146
3147
            if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
                addr.nTime = nNow - 5 * 24 * 60 * 60;
s_nakamoto's avatar
s_nakamoto committed
3148
            pfrom->AddAddressKnown(addr);
3149
            bool fReachable = IsReachable(addr);
s_nakamoto's avatar
s_nakamoto committed
3150
            if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
s_nakamoto's avatar
s_nakamoto committed
3151
3152
3153
            {
                // Relay to a limited number of other nodes
                {
3154
                    LOCK(cs_vNodes);
3155
3156
                    // Use deterministic randomness to send to the same nodes for 24 hours
                    // at a time so the setAddrKnowns of the chosen nodes prevent repeats
s_nakamoto's avatar
s_nakamoto committed
3157
3158
                    static uint256 hashSalt;
                    if (hashSalt == 0)
3159
                        hashSalt = GetRandHash();
3160
                    uint64 hashAddr = addr.GetHash();
Pieter Wuille's avatar
Pieter Wuille committed
3161
                    uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60));
3162
                    hashRand = Hash(BEGIN(hashRand), END(hashRand));
s_nakamoto's avatar
s_nakamoto committed
3163
                    multimap<uint256, CNode*> mapMix;
3164
                    BOOST_FOREACH(CNode* pnode, vNodes)
3165
                    {
3166
                        if (pnode->nVersion < CADDR_TIME_VERSION)
s_nakamoto's avatar
s_nakamoto committed
3167
                            continue;
3168
3169
3170
3171
3172
3173
                        unsigned int nPointer;
                        memcpy(&nPointer, &pnode, sizeof(nPointer));
                        uint256 hashKey = hashRand ^ nPointer;
                        hashKey = Hash(BEGIN(hashKey), END(hashKey));
                        mapMix.insert(make_pair(hashKey, pnode));
                    }
3174
                    int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
s_nakamoto's avatar
s_nakamoto committed
3175
3176
3177
3178
                    for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
                        ((*mi).second)->PushAddress(addr);
                }
            }
3179
3180
3181
            // Do not store addresses outside our network
            if (fReachable)
                vAddrOk.push_back(addr);
s_nakamoto's avatar
s_nakamoto committed
3182
        }
3183
        addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
s_nakamoto's avatar
s_nakamoto committed
3184
3185
        if (vAddr.size() < 1000)
            pfrom->fGetAddr = false;
3186
3187
        if (pfrom->fOneShot)
            pfrom->fDisconnect = true;
s_nakamoto's avatar
s_nakamoto committed
3188
3189
3190
3191
3192
3193
3194
    }


    else if (strCommand == "inv")
    {
        vector<CInv> vInv;
        vRecv >> vInv;
3195
        if (vInv.size() > MAX_INV_SZ)
3196
3197
        {
            pfrom->Misbehaving(20);
3198
            return error("message inv size() = %"PRIszu"", vInv.size());
3199
        }
s_nakamoto's avatar
s_nakamoto committed
3200

3201
3202
3203
        // find last block in inv vector
        unsigned int nLastBlock = (unsigned int)(-1);
        for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) {
3204
            if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) {
3205
                nLastBlock = vInv.size() - 1 - nInv;
3206
3207
                break;
            }
3208
        }
3209
        for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
s_nakamoto's avatar
s_nakamoto committed
3210
        {
3211
3212
            const CInv &inv = vInv[nInv];

s_nakamoto's avatar
s_nakamoto committed
3213
3214
3215
3216
            if (fShutdown)
                return true;
            pfrom->AddInventoryKnown(inv);

3217
            bool fAlreadyHave = AlreadyHave(inv);
3218
3219
            if (fDebug)
                printf("  got inventory: %s  %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
s_nakamoto's avatar
s_nakamoto committed
3220

3221
            if (!fAlreadyHave) {
3222
                if (!fImporting && !fReindex)
3223
3224
                    pfrom->AskFor(inv);
            } else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) {
s_nakamoto's avatar
s_nakamoto committed
3225
                pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
3226
3227
3228
3229
3230
3231
3232
3233
            } else if (nInv == nLastBlock) {
                // In case we are on a very long side-chain, it is possible that we already have
                // the last block in an inv bundle sent in response to getblocks. Try to detect
                // this situation and push another getblocks to continue.
                pfrom->PushGetBlocks(mapBlockIndex[inv.hash], uint256(0));
                if (fDebug)
                    printf("force request: %s\n", inv.ToString().c_str());
            }
s_nakamoto's avatar
s_nakamoto committed
3234
3235

            // Track requests for our stuff
Pieter Wuille's avatar
Pieter Wuille committed
3236
            Inventory(inv.hash);
s_nakamoto's avatar
s_nakamoto committed
3237
3238
3239
3240
3241
3242
3243
3244
        }
    }


    else if (strCommand == "getdata")
    {
        vector<CInv> vInv;
        vRecv >> vInv;
3245
        if (vInv.size() > MAX_INV_SZ)
3246
3247
        {
            pfrom->Misbehaving(20);
3248
            return error("message getdata size() = %"PRIszu"", vInv.size());
3249
        }
s_nakamoto's avatar
s_nakamoto committed
3250

3251
        if (fDebugNet || (vInv.size() != 1))
3252
            printf("received getdata (%"PRIszu" invsz)\n", vInv.size());
3253

3254
        vector<CInv> vNotFound;
3255
        BOOST_FOREACH(const CInv& inv, vInv)
s_nakamoto's avatar
s_nakamoto committed
3256
3257
3258
        {
            if (fShutdown)
                return true;
3259
3260
            if (fDebugNet || (vInv.size() == 1))
                printf("received getdata for: %s\n", inv.ToString().c_str());
s_nakamoto's avatar
s_nakamoto committed
3261

3262
            if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
s_nakamoto's avatar
s_nakamoto committed
3263
3264
3265
3266
3267
3268
            {
                // Send block from disk
                map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
                if (mi != mapBlockIndex.end())
                {
                    CBlock block;
3269
                    block.ReadFromDisk((*mi).second);
3270
3271
3272
3273
3274
3275
3276
3277
                    if (inv.type == MSG_BLOCK)
                        pfrom->PushMessage("block", block);
                    else // MSG_FILTERED_BLOCK)
                    {
                        LOCK(pfrom->cs_filter);
                        if (pfrom->pfilter)
                        {
                            CMerkleBlock merkleBlock(block, *pfrom->pfilter);
3278
                            pfrom->PushMessage("merkleblock", merkleBlock);
3279
3280
3281
3282
3283
3284
                            // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see 
                            // This avoids hurting performance by pointlessly requiring a round-trip
                            // Note that there is currently no way for a node to request any single transactions we didnt send here -
                            // they must either disconnect and retry or request the full block.
                            // Thus, the protocol spec specified allows for us to provide duplicate txn here,
                            // however we MUST always provide at least what the remote peer needs
3285
3286
3287
3288
                            typedef std::pair<unsigned int, uint256> PairType;
                            BOOST_FOREACH(PairType& pair, merkleBlock.vMatchedTxn)
                                if (!pfrom->setInventoryKnown.count(CInv(MSG_TX, pair.second)))
                                    pfrom->PushMessage("tx", block.vtx[pair.first]);
3289
3290
3291
3292
                        }
                        // else
                            // no response
                    }
s_nakamoto's avatar
s_nakamoto committed
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309

                    // Trigger them to send a getblocks request for the next batch of inventory
                    if (inv.hash == pfrom->hashContinue)
                    {
                        // Bypass PushInventory, this must send even if redundant,
                        // and we want it right after the last block so they don't
                        // wait for other stuff first.
                        vector<CInv> vInv;
                        vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
                        pfrom->PushMessage("inv", vInv);
                        pfrom->hashContinue = 0;
                    }
                }
            }
            else if (inv.IsKnownType())
            {
                // Send stream from relay memory
3310
                bool pushed = false;
s_nakamoto's avatar
s_nakamoto committed
3311
                {
3312
                    LOCK(cs_mapRelay);
s_nakamoto's avatar
s_nakamoto committed
3313
                    map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
3314
                    if (mi != mapRelay.end()) {
s_nakamoto's avatar
s_nakamoto committed
3315
                        pfrom->PushMessage(inv.GetCommand(), (*mi).second);
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
                        pushed = true;
                    }
                }
                if (!pushed && inv.type == MSG_TX) {
                    LOCK(mempool.cs);
                    if (mempool.exists(inv.hash)) {
                        CTransaction tx = mempool.lookup(inv.hash);
                        CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
                        ss.reserve(1000);
                        ss << tx;
                        pfrom->PushMessage("tx", ss);
3327
                        pushed = true;
3328
                    }
s_nakamoto's avatar
s_nakamoto committed
3329
                }
3330
3331
3332
                if (!pushed) {
                    vNotFound.push_back(inv);
                }
s_nakamoto's avatar
s_nakamoto committed
3333
3334
            }

3335
            // Track requests for our stuff.
Pieter Wuille's avatar
Pieter Wuille committed
3336
            Inventory(inv.hash);
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347

            if (!vNotFound.empty()) {
                // Let the peer know that we didn't find what it asked for, so it doesn't
                // have to wait around forever. Currently only SPV clients actually care
                // about this message: it's needed when they are recursively walking the
                // dependencies of relevant unconfirmed transactions. SPV clients want to
                // do that because they want to know about (and store and rebroadcast and
                // risk analyze) the dependencies of transactions relevant to them, without
                // having to download the entire memory pool.
                pfrom->PushMessage("notfound", vNotFound);
            }
s_nakamoto's avatar
s_nakamoto committed
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
        }
    }


    else if (strCommand == "getblocks")
    {
        CBlockLocator locator;
        uint256 hashStop;
        vRecv >> locator >> hashStop;

3358
        // Find the last block the caller has in the main chain
s_nakamoto's avatar
s_nakamoto committed
3359
3360
3361
3362
3363
        CBlockIndex* pindex = locator.GetBlockIndex();

        // Send the rest of the chain
        if (pindex)
            pindex = pindex->pnext;
3364
        int nLimit = 500;
3365
        printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), BlockHashStr(hashStop).c_str(), nLimit);
s_nakamoto's avatar
s_nakamoto committed
3366
3367
3368
3369
        for (; pindex; pindex = pindex->pnext)
        {
            if (pindex->GetBlockHash() == hashStop)
            {
3370
                printf("  getblocks stopping at %d %s\n", pindex->nHeight, BlockHashStr(pindex->GetBlockHash()).c_str());
s_nakamoto's avatar
s_nakamoto committed
3371
3372
3373
                break;
            }
            pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
3374
            if (--nLimit <= 0)
s_nakamoto's avatar
s_nakamoto committed
3375
3376
3377
            {
                // When this block is requested, we'll send an inv that'll make them
                // getblocks the next batch of inventory.
3378
                printf("  getblocks stopping at limit %d %s\n", pindex->nHeight, BlockHashStr(pindex->GetBlockHash()).c_str());
s_nakamoto's avatar
s_nakamoto committed
3379
3380
3381
3382
3383
3384
3385
                pfrom->hashContinue = pindex->GetBlockHash();
                break;
            }
        }
    }


3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
    else if (strCommand == "getheaders")
    {
        CBlockLocator locator;
        uint256 hashStop;
        vRecv >> locator >> hashStop;

        CBlockIndex* pindex = NULL;
        if (locator.IsNull())
        {
            // If locator is null, return the hashStop block
            map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
            if (mi == mapBlockIndex.end())
                return true;
            pindex = (*mi).second;
        }
        else
        {
            // Find the last block the caller has in the main chain
            pindex = locator.GetBlockIndex();
            if (pindex)
                pindex = pindex->pnext;
        }

3409
        // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
3410
        vector<CBlock> vHeaders;
3411
        int nLimit = 2000;
3412
        printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), BlockHashStr(hashStop).c_str());
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
        for (; pindex; pindex = pindex->pnext)
        {
            vHeaders.push_back(pindex->GetBlockHeader());
            if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
                break;
        }
        pfrom->PushMessage("headers", vHeaders);
    }


s_nakamoto's avatar
s_nakamoto committed
3423
3424
3425
    else if (strCommand == "tx")
    {
        vector<uint256> vWorkQueue;
3426
        vector<uint256> vEraseQueue;
s_nakamoto's avatar
s_nakamoto committed
3427
3428
3429
3430
3431
3432
3433
3434
        CDataStream vMsg(vRecv);
        CTransaction tx;
        vRecv >> tx;

        CInv inv(MSG_TX, tx.GetHash());
        pfrom->AddInventoryKnown(inv);

        bool fMissingInputs = false;
Pieter Wuille's avatar
Pieter Wuille committed
3435
3436
        CValidationState state;
        if (tx.AcceptToMemoryPool(state, true, true, &fMissingInputs))
s_nakamoto's avatar
s_nakamoto committed
3437
        {
3438
            RelayTransaction(tx, inv.hash, vMsg);
s_nakamoto's avatar
s_nakamoto committed
3439
3440
            mapAlreadyAskedFor.erase(inv);
            vWorkQueue.push_back(inv.hash);
3441
            vEraseQueue.push_back(inv.hash);
s_nakamoto's avatar
s_nakamoto committed
3442
3443

            // Recursively process any orphan transactions that depended on this one
3444
            for (unsigned int i = 0; i < vWorkQueue.size(); i++)
s_nakamoto's avatar
s_nakamoto committed
3445
3446
            {
                uint256 hashPrev = vWorkQueue[i];
3447
3448
                for (map<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin();
                     mi != mapOrphanTransactionsByPrev[hashPrev].end();
s_nakamoto's avatar
s_nakamoto committed
3449
3450
3451
3452
3453
3454
                     ++mi)
                {
                    const CDataStream& vMsg = *((*mi).second);
                    CTransaction tx;
                    CDataStream(vMsg) >> tx;
                    CInv inv(MSG_TX, tx.GetHash());
3455
                    bool fMissingInputs2 = false;
s_nakamoto's avatar
s_nakamoto committed
3456

Pieter Wuille's avatar
Pieter Wuille committed
3457
                    if (tx.AcceptToMemoryPool(state, true, true, &fMissingInputs2))
s_nakamoto's avatar
s_nakamoto committed
3458
                    {
3459
                        printf("   accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
3460
                        RelayTransaction(tx, inv.hash, vMsg);
s_nakamoto's avatar
s_nakamoto committed
3461
3462
                        mapAlreadyAskedFor.erase(inv);
                        vWorkQueue.push_back(inv.hash);
3463
3464
3465
3466
                        vEraseQueue.push_back(inv.hash);
                    }
                    else if (!fMissingInputs2)
                    {
3467
                        // invalid or too-little-fee orphan
3468
                        vEraseQueue.push_back(inv.hash);
3469
                        printf("   removed orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
s_nakamoto's avatar
s_nakamoto committed
3470
3471
3472
3473
                    }
                }
            }

3474
            BOOST_FOREACH(uint256 hash, vEraseQueue)
s_nakamoto's avatar
s_nakamoto committed
3475
3476
3477
3478
3479
                EraseOrphanTx(hash);
        }
        else if (fMissingInputs)
        {
            AddOrphanTx(vMsg);
3480
3481

            // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
3482
            unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
3483
            if (nEvicted > 0)
3484
                printf("mapOrphan overflow, removed %u tx\n", nEvicted);
s_nakamoto's avatar
s_nakamoto committed
3485
        }
Pieter Wuille's avatar
Pieter Wuille committed
3486
3487
3488
        int nDoS;
        if (state.IsInvalid(nDoS))
            pfrom->Misbehaving(nDoS);
s_nakamoto's avatar
s_nakamoto committed
3489
3490
3491
    }


3492
    else if (strCommand == "block" && !fImporting && !fReindex) // Ignore blocks received while importing
s_nakamoto's avatar
s_nakamoto committed
3493
    {
3494
3495
        CBlock block;
        vRecv >> block;
s_nakamoto's avatar
s_nakamoto committed
3496

3497
        printf("received block %s\n", BlockHashStr(block.GetHash()).c_str());
3498
        // block.print();
s_nakamoto's avatar
s_nakamoto committed
3499

3500
        CInv inv(MSG_BLOCK, block.GetHash());
s_nakamoto's avatar
s_nakamoto committed
3501
3502
        pfrom->AddInventoryKnown(inv);

Pieter Wuille's avatar
Pieter Wuille committed
3503
3504
        CValidationState state;
        if (ProcessBlock(state, pfrom, &block))
s_nakamoto's avatar
s_nakamoto committed
3505
            mapAlreadyAskedFor.erase(inv);
Pieter Wuille's avatar
Pieter Wuille committed
3506
3507
3508
        int nDoS;
        if (state.IsInvalid(nDoS))
            pfrom->Misbehaving(nDoS);
s_nakamoto's avatar
s_nakamoto committed
3509
3510
3511
3512
3513
3514
    }


    else if (strCommand == "getaddr")
    {
        pfrom->vAddrToSend.clear();
3515
3516
3517
        vector<CAddress> vAddr = addrman.GetAddr();
        BOOST_FOREACH(const CAddress &addr, vAddr)
            pfrom->PushAddress(addr);
s_nakamoto's avatar
s_nakamoto committed
3518
3519
3520
    }


3521
3522
3523
    else if (strCommand == "mempool")
    {
        std::vector<uint256> vtxid;
Matt Corallo's avatar
Matt Corallo committed
3524
        LOCK2(mempool.cs, pfrom->cs_filter);
3525
3526
        mempool.queryHashes(vtxid);
        vector<CInv> vInv;
Matt Corallo's avatar
Matt Corallo committed
3527
3528
3529
3530
3531
3532
3533
        BOOST_FOREACH(uint256& hash, vtxid) {
            CInv inv(MSG_TX, hash);
            if ((pfrom->pfilter && pfrom->pfilter->IsRelevantAndUpdate(mempool.lookup(hash), hash)) ||
               (!pfrom->pfilter))
                vInv.push_back(inv);
            if (vInv.size() == MAX_INV_SZ)
                break;
3534
3535
3536
3537
3538
3539
        }
        if (vInv.size() > 0)
            pfrom->PushMessage("inv", vInv);
    }


s_nakamoto's avatar
s_nakamoto committed
3540
3541
    else if (strCommand == "ping")
    {
Jeff Garzik's avatar
Jeff Garzik committed
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
        if (pfrom->nVersion > BIP0031_VERSION)
        {
            uint64 nonce = 0;
            vRecv >> nonce;
            // Echo the message back with the nonce. This allows for two useful features:
            //
            // 1) A remote node can quickly check if the connection is operational
            // 2) Remote nodes can measure the latency of the network thread. If this node
            //    is overloaded it won't respond to pings quickly and the remote node can
            //    avoid sending us more work, like chain download requests.
            //
            // The nonce stops the remote getting confused between different pings: without
            // it, if the remote node sends a ping once per second and this node takes 5
            // seconds to respond to each, the 5th ping the remote sends would appear to
            // return very quickly.
            pfrom->PushMessage("pong", nonce);
        }
s_nakamoto's avatar
s_nakamoto committed
3559
3560
3561
3562
3563
3564
3565
3566
    }


    else if (strCommand == "alert")
    {
        CAlert alert;
        vRecv >> alert;

Gavin Andresen's avatar
Gavin Andresen committed
3567
3568
        uint256 alertHash = alert.GetHash();
        if (pfrom->setKnown.count(alertHash) == 0)
s_nakamoto's avatar
s_nakamoto committed
3569
        {
Gavin Andresen's avatar
Gavin Andresen committed
3570
            if (alert.ProcessAlert())
3571
            {
Gavin Andresen's avatar
Gavin Andresen committed
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
                // Relay
                pfrom->setKnown.insert(alertHash);
                {
                    LOCK(cs_vNodes);
                    BOOST_FOREACH(CNode* pnode, vNodes)
                        alert.RelayTo(pnode);
                }
            }
            else {
                // Small DoS penalty so peers that send us lots of
                // duplicate/expired/invalid-signature/whatever alerts
                // eventually get banned.
                // This isn't a Misbehaving(100) (immediate ban) because the
                // peer might be an older or different implementation with
                // a different signature key, etc.
                pfrom->Misbehaving(10);
3588
            }
s_nakamoto's avatar
s_nakamoto committed
3589
3590
3591
3592
        }
    }


3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
    else if (strCommand == "filterload")
    {
        CBloomFilter filter;
        vRecv >> filter;

        if (!filter.IsWithinSizeConstraints())
            // There is no excuse for sending a too-large filter
            pfrom->Misbehaving(100);
        else
        {
            LOCK(pfrom->cs_filter);
            delete pfrom->pfilter;
            pfrom->pfilter = new CBloomFilter(filter);
        }
3607
        pfrom->fRelayTxes = true;
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
    }


    else if (strCommand == "filteradd")
    {
        vector<unsigned char> vData;
        vRecv >> vData;

        // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
        // and thus, the maximum size any matched object can have) in a filteradd message
3618
        if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE)
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
        {
            pfrom->Misbehaving(100);
        } else {
            LOCK(pfrom->cs_filter);
            if (pfrom->pfilter)
                pfrom->pfilter->insert(vData);
            else
                pfrom->Misbehaving(100);
        }
    }


    else if (strCommand == "filterclear")
    {
        LOCK(pfrom->cs_filter);
        delete pfrom->pfilter;
        pfrom->pfilter = NULL;
3636
        pfrom->fRelayTxes = true;
3637
3638
3639
    }


s_nakamoto's avatar
s_nakamoto committed
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
    else
    {
        // Ignore unknown commands for extensibility
    }


    // Update the last seen time for this node's address
    if (pfrom->fNetworkNode)
        if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
            AddressCurrentlyConnected(pfrom->addr);


    return true;
}

3655
3656
3657
3658
3659
3660
3661
bool ProcessMessages(CNode* pfrom)
{
    CDataStream& vRecv = pfrom->vRecv;
    if (vRecv.empty())
        return true;
    //if (fDebug)
    //    printf("ProcessMessages(%u bytes)\n", vRecv.size());
s_nakamoto's avatar
s_nakamoto committed
3662

3663
3664
3665
3666
3667
3668
3669
3670
    //
    // Message format
    //  (4) message start
    //  (12) command
    //  (4) size
    //  (4) checksum
    //  (x) data
    //
s_nakamoto's avatar
s_nakamoto committed
3671

3672
3673
    loop
    {
3674
3675
3676
3677
        // Don't bother if send buffer is too full to respond anyway
        if (pfrom->vSend.size() >= SendBufferSize())
            break;

3678
3679
3680
3681
3682
        // Scan for message start
        CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
        int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
        if (vRecv.end() - pstart < nHeaderSize)
        {
3683
            if ((int)vRecv.size() > nHeaderSize)
3684
3685
3686
3687
3688
3689
3690
            {
                printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
                vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
            }
            break;
        }
        if (pstart - vRecv.begin() > 0)
3691
            printf("\n\nPROCESSMESSAGE SKIPPED %"PRIpdd" BYTES\n\n", pstart - vRecv.begin());
3692
        vRecv.erase(vRecv.begin(), pstart);
s_nakamoto's avatar
s_nakamoto committed
3693

3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
        // Read header
        vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
        CMessageHeader hdr;
        vRecv >> hdr;
        if (!hdr.IsValid())
        {
            printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
            continue;
        }
        string strCommand = hdr.GetCommand();

        // Message size
        unsigned int nMessageSize = hdr.nMessageSize;
        if (nMessageSize > MAX_SIZE)
        {
3709
            printf("ProcessMessages(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
            continue;
        }
        if (nMessageSize > vRecv.size())
        {
            // Rewind and wait for rest of message
            vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
            break;
        }

        // Checksum
Pieter Wuille's avatar
Pieter Wuille committed
3720
3721
3722
3723
        uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
        unsigned int nChecksum = 0;
        memcpy(&nChecksum, &hash, sizeof(nChecksum));
        if (nChecksum != hdr.nChecksum)
3724
        {
3725
            printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
Pieter Wuille's avatar
Pieter Wuille committed
3726
3727
               strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
            continue;
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
        }

        // Copy message to its own buffer
        CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
        vRecv.ignore(nMessageSize);

        // Process message
        bool fRet = false;
        try
        {
3738
3739
            {
                LOCK(cs_main);
3740
                fRet = ProcessMessage(pfrom, strCommand, vMsg);
3741
            }
3742
3743
3744
3745
3746
3747
3748
            if (fShutdown)
                return true;
        }
        catch (std::ios_base::failure& e)
        {
            if (strstr(e.what(), "end of data"))
            {
3749
                // Allow exceptions from under-length message on vRecv
3750
                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());
3751
3752
3753
            }
            else if (strstr(e.what(), "size too large"))
            {
3754
                // Allow exceptions from over-long size
3755
                printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
3756
3757
3758
            }
            else
            {
3759
                PrintExceptionContinue(&e, "ProcessMessages()");
3760
3761
3762
            }
        }
        catch (std::exception& e) {
3763
            PrintExceptionContinue(&e, "ProcessMessages()");
3764
        } catch (...) {
3765
            PrintExceptionContinue(NULL, "ProcessMessages()");
3766
3767
3768
3769
3770
3771
3772
3773
3774
        }

        if (!fRet)
            printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
    }

    vRecv.Compact();
    return true;
}
s_nakamoto's avatar
s_nakamoto committed
3775
3776
3777
3778


bool SendMessages(CNode* pto, bool fSendTrickle)
{
Pieter Wuille's avatar
Pieter Wuille committed
3779
3780
    TRY_LOCK(cs_main, lockMain);
    if (lockMain) {
s_nakamoto's avatar
s_nakamoto committed
3781
3782
3783
3784
        // Don't send anything until we get their version message
        if (pto->nVersion == 0)
            return true;

3785
        // Keep-alive ping. We send a nonce of zero because we don't use it anywhere
Jeff Garzik's avatar
Jeff Garzik committed
3786
3787
        // right now.
        if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty()) {
Pieter Wuille's avatar
Pieter Wuille committed
3788
            uint64 nonce = 0;
Jeff Garzik's avatar
Jeff Garzik committed
3789
            if (pto->nVersion > BIP0031_VERSION)
Pieter Wuille's avatar
Pieter Wuille committed
3790
                pto->PushMessage("ping", nonce);
Jeff Garzik's avatar
Jeff Garzik committed
3791
3792
3793
            else
                pto->PushMessage("ping");
        }
s_nakamoto's avatar
s_nakamoto committed
3794

s_nakamoto's avatar
s_nakamoto committed
3795
3796
3797
        // Resend wallet transactions that haven't gotten in a block yet
        ResendWalletTransactions();

s_nakamoto's avatar
s_nakamoto committed
3798
        // Address refresh broadcast
3799
        static int64 nLastRebroadcast;
3800
        if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
s_nakamoto's avatar
s_nakamoto committed
3801
3802
        {
            {
3803
                LOCK(cs_vNodes);
3804
                BOOST_FOREACH(CNode* pnode, vNodes)
s_nakamoto's avatar
s_nakamoto committed
3805
3806
                {
                    // Periodically clear setAddrKnown to allow refresh broadcasts
3807
3808
                    if (nLastRebroadcast)
                        pnode->setAddrKnown.clear();
s_nakamoto's avatar
s_nakamoto committed
3809
3810

                    // Rebroadcast our address
Pieter Wuille's avatar
Pieter Wuille committed
3811
                    if (!fNoListen)
s_nakamoto's avatar
s_nakamoto committed
3812
                    {
3813
3814
3815
                        CAddress addr = GetLocalAddress(&pnode->addr);
                        if (addr.IsRoutable())
                            pnode->PushAddress(addr);
s_nakamoto's avatar
s_nakamoto committed
3816
                    }
s_nakamoto's avatar
s_nakamoto committed
3817
3818
                }
            }
3819
            nLastRebroadcast = GetTime();
s_nakamoto's avatar
s_nakamoto committed
3820
3821
3822
3823
3824
3825
3826
3827
3828
        }

        //
        // Message: addr
        //
        if (fSendTrickle)
        {
            vector<CAddress> vAddr;
            vAddr.reserve(pto->vAddrToSend.size());
3829
            BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
s_nakamoto's avatar
s_nakamoto committed
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
            {
                // returns true if wasn't already contained in the set
                if (pto->setAddrKnown.insert(addr).second)
                {
                    vAddr.push_back(addr);
                    // receiver rejects addr messages larger than 1000
                    if (vAddr.size() >= 1000)
                    {
                        pto->PushMessage("addr", vAddr);
                        vAddr.clear();
                    }
                }
            }
            pto->vAddrToSend.clear();
            if (!vAddr.empty())
                pto->PushMessage("addr", vAddr);
        }


        //
        // Message: inventory
        //
        vector<CInv> vInv;
        vector<CInv> vInvWait;
        {
3855
            LOCK(pto->cs_inventory);
s_nakamoto's avatar
s_nakamoto committed
3856
3857
            vInv.reserve(pto->vInventoryToSend.size());
            vInvWait.reserve(pto->vInventoryToSend.size());
3858
            BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
s_nakamoto's avatar
s_nakamoto committed
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
            {
                if (pto->setInventoryKnown.count(inv))
                    continue;

                // trickle out tx inv to protect privacy
                if (inv.type == MSG_TX && !fSendTrickle)
                {
                    // 1/4 of tx invs blast to all immediately
                    static uint256 hashSalt;
                    if (hashSalt == 0)
3869
                        hashSalt = GetRandHash();
s_nakamoto's avatar
s_nakamoto committed
3870
3871
3872
3873
3874
3875
3876
                    uint256 hashRand = inv.hash ^ hashSalt;
                    hashRand = Hash(BEGIN(hashRand), END(hashRand));
                    bool fTrickleWait = ((hashRand & 3) != 0);

                    // always trickle our own transactions
                    if (!fTrickleWait)
                    {
Pieter Wuille's avatar
Pieter Wuille committed
3877
3878
3879
3880
                        CWalletTx wtx;
                        if (GetTransaction(inv.hash, wtx))
                            if (wtx.fFromMe)
                                fTrickleWait = true;
s_nakamoto's avatar
s_nakamoto committed
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
                    }

                    if (fTrickleWait)
                    {
                        vInvWait.push_back(inv);
                        continue;
                    }
                }

                // returns true if wasn't already contained in the set
                if (pto->setInventoryKnown.insert(inv).second)
                {
                    vInv.push_back(inv);
                    if (vInv.size() >= 1000)
                    {
                        pto->PushMessage("inv", vInv);
                        vInv.clear();
                    }
                }
            }
            pto->vInventoryToSend = vInvWait;
        }
        if (!vInv.empty())
            pto->PushMessage("inv", vInv);


        //
        // Message: getdata
        //
        vector<CInv> vGetData;
3911
        int64 nNow = GetTime() * 1000000;
s_nakamoto's avatar
s_nakamoto committed
3912
3913
3914
        while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
        {
            const CInv& inv = (*pto->mapAskFor.begin()).second;
3915
            if (!AlreadyHave(inv))
s_nakamoto's avatar
s_nakamoto committed
3916
            {
3917
3918
                if (fDebugNet)
                    printf("sending getdata: %s\n", inv.ToString().c_str());
s_nakamoto's avatar
s_nakamoto committed
3919
3920
3921
3922
3923
3924
                vGetData.push_back(inv);
                if (vGetData.size() >= 1000)
                {
                    pto->PushMessage("getdata", vGetData);
                    vGetData.clear();
                }
3925
                mapAlreadyAskedFor[inv] = nNow;
s_nakamoto's avatar
s_nakamoto committed
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
            }
            pto->mapAskFor.erase(pto->mapAskFor.begin());
        }
        if (!vGetData.empty())
            pto->PushMessage("getdata", vGetData);

    }
    return true;
}














//////////////////////////////////////////////////////////////////////////////
//
// BitcoinMiner
//

Pieter Wuille's avatar
Pieter Wuille committed
3954
int static FormatHashBlocks(void* pbuffer, unsigned int len)
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
{
    unsigned char* pdata = (unsigned char*)pbuffer;
    unsigned int blocks = 1 + ((len + 8) / 64);
    unsigned char* pend = pdata + 64 * blocks;
    memset(pdata + len, 0, 64 * blocks - len);
    pdata[len] = 0x80;
    unsigned int bits = len * 8;
    pend[-1] = (bits >> 0) & 0xff;
    pend[-2] = (bits >> 8) & 0xff;
    pend[-3] = (bits >> 16) & 0xff;
    pend[-4] = (bits >> 24) & 0xff;
    return blocks;
}

static const unsigned int pSHA256InitState[8] =
{0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};

3972
void SHA256Transform(void* pstate, void* pinput, const void* pinit)
3973
{
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
    SHA256_CTX ctx;
    unsigned char data[64];

    SHA256_Init(&ctx);

    for (int i = 0; i < 16; i++)
        ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);

    for (int i = 0; i < 8; i++)
        ctx.h[i] = ((uint32_t*)pinit)[i];

    SHA256_Update(&ctx, data, sizeof(data));
3986
    for (int i = 0; i < 8; i++)
3987
        ((uint32_t*)pstate)[i] = ctx.h[i];
3988
3989
3990
3991
3992
3993
}

//
// ScanHash scans nonces looking for a hash with at least some zero bits.
// It operates on big endian data.  Caller does the byte reversing.
// All input buffers are 16-byte aligned.  nNonce is usually preserved
s_nakamoto's avatar
s_nakamoto committed
3994
// between calls, but periodically or if nNonce is 0xffff0000 or above,
3995
3996
// the block is rebuilt and nNonce starts over at zero.
//
Pieter Wuille's avatar
Pieter Wuille committed
3997
unsigned int static ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)
3998
{
s_nakamoto's avatar
s_nakamoto committed
3999
    unsigned int& nNonce = *(unsigned int*)(pdata + 12);
4000
4001
    for (;;)
    {
4002
        // Crypto++ SHA256
s_nakamoto's avatar
s_nakamoto committed
4003
        // Hash pdata using pmidstate as the starting state into
4004
        // pre-formatted buffer phash1, then hash phash1 into phash
4005
        nNonce++;
s_nakamoto's avatar
s_nakamoto committed
4006
        SHA256Transform(phash1, pdata, pmidstate);
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
        SHA256Transform(phash, phash1, pSHA256InitState);

        // Return the nonce if the hash has at least some zero bits,
        // caller will check if it has enough to reach the target
        if (((unsigned short*)phash)[14] == 0)
            return nNonce;

        // If nothing found after trying for a while, return -1
        if ((nNonce & 0xffff) == 0)
        {
            nHashesDone = 0xffff+1;
4018
            return (unsigned int) -1;
4019
4020
4021
4022
        }
    }
}

4023
// Some explaining would be appreciated
4024
4025
4026
4027
4028
4029
class COrphan
{
public:
    CTransaction* ptx;
    set<uint256> setDependsOn;
    double dPriority;
4030
    double dFeePerKb;
4031
4032
4033
4034

    COrphan(CTransaction* ptxIn)
    {
        ptx = ptxIn;
4035
        dPriority = dFeePerKb = 0;
4036
4037
4038
4039
    }

    void print() const
    {
4040
4041
        printf("COrphan(hash=%s, dPriority=%.1f, dFeePerKb=%.1f)\n",
               ptx->GetHash().ToString().substr(0,10).c_str(), dPriority, dFeePerKb);
4042
        BOOST_FOREACH(uint256 hash, setDependsOn)
4043
4044
4045
4046
4047
            printf("   setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
    }
};


4048
4049
4050
uint64 nLastBlockTx = 0;
uint64 nLastBlockSize = 0;

4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
// We want to sort transactions by priority and fee, so:
typedef boost::tuple<double, double, CTransaction*> TxPriority;
class TxPriorityCompare
{
    bool byFee;
public:
    TxPriorityCompare(bool _byFee) : byFee(_byFee) { }
    bool operator()(const TxPriority& a, const TxPriority& b)
    {
        if (byFee)
        {
            if (a.get<1>() == b.get<1>())
                return a.get<0>() < b.get<0>();
            return a.get<1>() < b.get<1>();
        }
        else
        {
            if (a.get<0>() == b.get<0>())
                return a.get<1>() < b.get<1>();
            return a.get<0>() < b.get<0>();
        }
    }
};

4075
CBlockTemplate* CreateNewBlock(CReserveKey& reservekey)
s_nakamoto's avatar
s_nakamoto committed
4076
4077
{
    // Create new block
4078
4079
    auto_ptr<CBlockTemplate> pblocktemplate(new CBlockTemplate());
    if(!pblocktemplate.get())
s_nakamoto's avatar
s_nakamoto committed
4080
        return NULL;
4081
    CBlock *pblock = &pblocktemplate->block; // pointer for convenience
s_nakamoto's avatar
s_nakamoto committed
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091

    // Create coinbase tx
    CTransaction txNew;
    txNew.vin.resize(1);
    txNew.vin[0].prevout.SetNull();
    txNew.vout.resize(1);
    txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;

    // Add our coinbase tx as first transaction
    pblock->vtx.push_back(txNew);
4092
4093
    pblocktemplate->vTxFees.push_back(-1); // updated at end
    pblocktemplate->vTxSigOps.push_back(-1); // updated at end
s_nakamoto's avatar
s_nakamoto committed
4094

4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
    // Largest block you're willing to create:
    unsigned int nBlockMaxSize = GetArg("-blockmaxsize", MAX_BLOCK_SIZE_GEN/2);
    // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity:
    nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize));

    // How much of the block should be dedicated to high-priority transactions,
    // included regardless of the fees they pay
    unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", 27000);
    nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);

    // Minimum block size you want to create; block will be filled with free transactions
    // until there are no more or the block reaches this size:
    unsigned int nBlockMinSize = GetArg("-blockminsize", 0);
    nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);

    // Fee-per-kilobyte amount considered the same as "free"
    // Be careful setting this: if you set it to zero then
    // a transaction spammer can cheaply fill blocks using
    // 1-satoshi-fee transactions. It should be set above the real
    // cost to you of processing a transaction.
    int64 nMinTxFee = MIN_TX_FEE;
    if (mapArgs.count("-mintxfee"))
        ParseMoney(mapArgs["-mintxfee"], nMinTxFee);

s_nakamoto's avatar
s_nakamoto committed
4119
    // Collect memory pool transactions into the block
4120
    int64 nFees = 0;
s_nakamoto's avatar
s_nakamoto committed
4121
    {
4122
        LOCK2(cs_main, mempool.cs);
4123
        CBlockIndex* pindexPrev = pindexBest;
4124
        CCoinsViewCache view(*pcoinsTip, true);
s_nakamoto's avatar
s_nakamoto committed
4125
4126
4127
4128

        // Priority order to process transactions
        list<COrphan> vOrphan; // list memory doesn't move
        map<uint256, vector<COrphan*> > mapDependers;
4129
        bool fPrintPriority = GetBoolArg("-printpriority");
4130
4131
4132
4133

        // This vector will be sorted into a priority queue:
        vector<TxPriority> vecPriority;
        vecPriority.reserve(mempool.mapTx.size());
4134
        for (map<uint256, CTransaction>::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi)
s_nakamoto's avatar
s_nakamoto committed
4135
4136
4137
4138
4139
4140
4141
        {
            CTransaction& tx = (*mi).second;
            if (tx.IsCoinBase() || !tx.IsFinal())
                continue;

            COrphan* porphan = NULL;
            double dPriority = 0;
4142
            int64 nTotalIn = 0;
4143
            bool fMissingInputs = false;
4144
            BOOST_FOREACH(const CTxIn& txin, tx.vin)
s_nakamoto's avatar
s_nakamoto committed
4145
4146
            {
                // Read prev transaction
Pieter Wuille's avatar
Pieter Wuille committed
4147
4148
                CCoins coins;
                if (!view.GetCoins(txin.prevout.hash, coins))
s_nakamoto's avatar
s_nakamoto committed
4149
                {
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
                    // This should never happen; all transactions in the memory
                    // pool should connect to either transactions in the chain
                    // or other transactions in the memory pool.
                    if (!mempool.mapTx.count(txin.prevout.hash))
                    {
                        printf("ERROR: mempool transaction missing input\n");
                        if (fDebug) assert("mempool transaction missing input" == 0);
                        fMissingInputs = true;
                        if (porphan)
                            vOrphan.pop_back();
                        break;
                    }

s_nakamoto's avatar
s_nakamoto committed
4163
4164
4165
4166
4167
4168
4169
4170
4171
                    // Has to wait for dependencies
                    if (!porphan)
                    {
                        // Use list for automatic deletion
                        vOrphan.push_back(COrphan(&tx));
                        porphan = &vOrphan.back();
                    }
                    mapDependers[txin.prevout.hash].push_back(porphan);
                    porphan->setDependsOn.insert(txin.prevout.hash);
4172
                    nTotalIn += mempool.mapTx[txin.prevout.hash].vout[txin.prevout.n].nValue;
s_nakamoto's avatar
s_nakamoto committed
4173
4174
                    continue;
                }
Pieter Wuille's avatar
Pieter Wuille committed
4175
4176

                int64 nValueIn = coins.vout[txin.prevout.n].nValue;
4177
                nTotalIn += nValueIn;
s_nakamoto's avatar
s_nakamoto committed
4178

4179
                int nConf = pindexPrev->nHeight - coins.nHeight + 1;
Pieter Wuille's avatar
Pieter Wuille committed
4180

s_nakamoto's avatar
s_nakamoto committed
4181
4182
                dPriority += (double)nValueIn * nConf;
            }
4183
            if (fMissingInputs) continue;
s_nakamoto's avatar
s_nakamoto committed
4184
4185

            // Priority is sum(valuein * age) / txsize
4186
4187
            unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
            dPriority /= nTxSize;
s_nakamoto's avatar
s_nakamoto committed
4188

4189
4190
4191
4192
            // This is a more accurate fee-per-kilobyte than is used by the client code, because the
            // client code rounds up the size to the nearest 1K. That's good, because it gives an
            // incentive to create smaller transactions.
            double dFeePerKb =  double(nTotalIn-tx.GetValueOut()) / (double(nTxSize)/1000.0);
s_nakamoto's avatar
s_nakamoto committed
4193

4194
            if (porphan)
s_nakamoto's avatar
s_nakamoto committed
4195
            {
4196
4197
                porphan->dPriority = dPriority;
                porphan->dFeePerKb = dFeePerKb;
s_nakamoto's avatar
s_nakamoto committed
4198
            }
4199
4200
            else
                vecPriority.push_back(TxPriority(dPriority, dFeePerKb, &(*mi).second));
s_nakamoto's avatar
s_nakamoto committed
4201
4202
4203
        }

        // Collect transactions into block
4204
        uint64 nBlockSize = 1000;
4205
        uint64 nBlockTx = 0;
4206
        int nBlockSigOps = 100;
4207
4208
4209
4210
4211
4212
        bool fSortedByFee = (nBlockPrioritySize <= 0);

        TxPriorityCompare comparer(fSortedByFee);
        std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);

        while (!vecPriority.empty())
s_nakamoto's avatar
s_nakamoto committed
4213
        {
4214
4215
4216
4217
4218
4219
4220
            // Take highest priority transaction off the priority queue:
            double dPriority = vecPriority.front().get<0>();
            double dFeePerKb = vecPriority.front().get<1>();
            CTransaction& tx = *(vecPriority.front().get<2>());

            std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
            vecPriority.pop_back();
s_nakamoto's avatar
s_nakamoto committed
4221

Pieter Wuille's avatar
Pieter Wuille committed
4222
4223
4224
            // second layer cached modifications just for this transaction
            CCoinsViewCache viewTemp(view, true);

s_nakamoto's avatar
s_nakamoto committed
4225
            // Size limits
4226
            unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
4227
            if (nBlockSize + nTxSize >= nBlockMaxSize)
s_nakamoto's avatar
s_nakamoto committed
4228
4229
                continue;

4230
            // Legacy limits on sigOps:
4231
            unsigned int nTxSigOps = tx.GetLegacySigOpCount();
4232
            if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
4233
4234
                continue;

4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
            // Skip free transactions if we're past the minimum block size:
            if (fSortedByFee && (dFeePerKb < nMinTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))
                continue;

            // Prioritize by fee once past the priority size or we run out of high-priority
            // transactions:
            if (!fSortedByFee &&
                ((nBlockSize + nTxSize >= nBlockPrioritySize) || (dPriority < COIN * 144 / 250)))
            {
                fSortedByFee = true;
                comparer = TxPriorityCompare(fSortedByFee);
                std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
            }
s_nakamoto's avatar
s_nakamoto committed
4248

Pieter Wuille's avatar
Pieter Wuille committed
4249
            if (!tx.HaveInputs(viewTemp))
Gavin Andresen's avatar
Gavin Andresen committed
4250
                continue;
4251

Pieter Wuille's avatar
Pieter Wuille committed
4252
            int64 nTxFees = tx.GetValueIn(viewTemp)-tx.GetValueOut();
4253

Pieter Wuille's avatar
Pieter Wuille committed
4254
            nTxSigOps += tx.GetP2SHSigOpCount(viewTemp);
4255
            if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
s_nakamoto's avatar
s_nakamoto committed
4256
                continue;
4257

Pieter Wuille's avatar
Pieter Wuille committed
4258
4259
            CValidationState state;
            if (!tx.CheckInputs(state, viewTemp, true, SCRIPT_VERIFY_P2SH))
Pieter Wuille's avatar
Pieter Wuille committed
4260
4261
                continue;

Pieter Wuille's avatar
Pieter Wuille committed
4262
            CTxUndo txundo;
Pieter Wuille's avatar
Pieter Wuille committed
4263
            uint256 hash = tx.GetHash();
Pieter Wuille's avatar
Pieter Wuille committed
4264
            if (!tx.UpdateCoins(state, viewTemp, txundo, pindexPrev->nHeight+1, hash))
4265
                continue;
Pieter Wuille's avatar
Pieter Wuille committed
4266
4267
4268

            // push changes from the second layer cache to the first one
            viewTemp.Flush();
s_nakamoto's avatar
s_nakamoto committed
4269
4270
4271

            // Added
            pblock->vtx.push_back(tx);
4272
4273
            pblocktemplate->vTxFees.push_back(nTxFees);
            pblocktemplate->vTxSigOps.push_back(nTxSigOps);
s_nakamoto's avatar
s_nakamoto committed
4274
            nBlockSize += nTxSize;
4275
            ++nBlockTx;
4276
            nBlockSigOps += nTxSigOps;
4277
            nFees += nTxFees;
s_nakamoto's avatar
s_nakamoto committed
4278

4279
            if (fPrintPriority)
4280
4281
4282
4283
4284
            {
                printf("priority %.1f feeperkb %.1f txid %s\n",
                       dPriority, dFeePerKb, tx.GetHash().ToString().c_str());
            }

s_nakamoto's avatar
s_nakamoto committed
4285
4286
4287
            // Add transactions that depend on this one to the priority queue
            if (mapDependers.count(hash))
            {
4288
                BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
s_nakamoto's avatar
s_nakamoto committed
4289
4290
4291
4292
4293
                {
                    if (!porphan->setDependsOn.empty())
                    {
                        porphan->setDependsOn.erase(hash);
                        if (porphan->setDependsOn.empty())
4294
4295
4296
4297
                        {
                            vecPriority.push_back(TxPriority(porphan->dPriority, porphan->dFeePerKb, porphan->ptx));
                            std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
                        }
s_nakamoto's avatar
s_nakamoto committed
4298
4299
4300
4301
                    }
                }
            }
        }
4302
4303
4304

        nLastBlockTx = nBlockTx;
        nLastBlockSize = nBlockSize;
4305
        printf("CreateNewBlock(): total size %"PRI64u"\n", nBlockSize);
4306

Pieter Wuille's avatar
Pieter Wuille committed
4307
        pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);
4308
        pblocktemplate->vTxFees[0] = -nFees;
s_nakamoto's avatar
s_nakamoto committed
4309

Pieter Wuille's avatar
Pieter Wuille committed
4310
4311
4312
        // Fill in header
        pblock->hashPrevBlock  = pindexPrev->GetBlockHash();
        pblock->UpdateTime(pindexPrev);
4313
        pblock->nBits          = GetNextWorkRequired(pindexPrev, pblock);
Pieter Wuille's avatar
Pieter Wuille committed
4314
        pblock->nNonce         = 0;
4315
        pblock->vtx[0].vin[0].scriptSig = CScript() << OP_0 << OP_0;
4316
        pblocktemplate->vTxSigOps[0] = pblock->vtx[0].GetLegacySigOpCount();
Pieter Wuille's avatar
Pieter Wuille committed
4317

Pieter Wuille's avatar
Pieter Wuille committed
4318
        CBlockIndex indexDummy(*pblock);
4319
4320
        indexDummy.pprev = pindexPrev;
        indexDummy.nHeight = pindexPrev->nHeight + 1;
4321
        CCoinsViewCache viewNew(*pcoinsTip, true);
Pieter Wuille's avatar
Pieter Wuille committed
4322
4323
        CValidationState state;
        if (!pblock->ConnectBlock(state, &indexDummy, viewNew, true))
4324
4325
4326
            throw std::runtime_error("CreateNewBlock() : ConnectBlock failed");
    }

4327
    return pblocktemplate.release();
s_nakamoto's avatar
s_nakamoto committed
4328
4329
4330
}


4331
void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
s_nakamoto's avatar
s_nakamoto committed
4332
4333
{
    // Update nExtraNonce
4334
4335
    static uint256 hashPrevBlock;
    if (hashPrevBlock != pblock->hashPrevBlock)
s_nakamoto's avatar
s_nakamoto committed
4336
    {
4337
4338
        nExtraNonce = 0;
        hashPrevBlock = pblock->hashPrevBlock;
s_nakamoto's avatar
s_nakamoto committed
4339
    }
4340
    ++nExtraNonce;
4341
4342
    unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
    pblock->vtx[0].vin[0].scriptSig = (CScript() << nHeight << CBigNum(nExtraNonce)) + COINBASE_FLAGS;
4343
4344
    assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100);

s_nakamoto's avatar
s_nakamoto committed
4345
4346
4347
4348
4349
4350
4351
    pblock->hashMerkleRoot = pblock->BuildMerkleTree();
}


void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
{
    //
4352
    // Pre-build hash buffers
s_nakamoto's avatar
s_nakamoto committed
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
    //
    struct
    {
        struct unnamed2
        {
            int nVersion;
            uint256 hashPrevBlock;
            uint256 hashMerkleRoot;
            unsigned int nTime;
            unsigned int nBits;
            unsigned int nNonce;
        }
        block;
        unsigned char pchPadding0[64];
        uint256 hash1;
        unsigned char pchPadding1[64];
    }
    tmp;
    memset(&tmp, 0, sizeof(tmp));

    tmp.block.nVersion       = pblock->nVersion;
    tmp.block.hashPrevBlock  = pblock->hashPrevBlock;
    tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
    tmp.block.nTime          = pblock->nTime;
    tmp.block.nBits          = pblock->nBits;
    tmp.block.nNonce         = pblock->nNonce;

    FormatHashBlocks(&tmp.block, sizeof(tmp.block));
    FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));

    // Byte swap all the input buffer
4384
    for (unsigned int i = 0; i < sizeof(tmp)/4; i++)
s_nakamoto's avatar
s_nakamoto committed
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
        ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);

    // Precalc the first half of the first hash, which stays constant
    SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);

    memcpy(pdata, &tmp.block, 128);
    memcpy(phash1, &tmp.hash1, 64);
}


Pieter Wuille's avatar
Pieter Wuille committed
4395
bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
s_nakamoto's avatar
s_nakamoto committed
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
{
    uint256 hash = pblock->GetHash();
    uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();

    if (hash > hashTarget)
        return false;

    //// debug print
    printf("BitcoinMiner:\n");
    printf("proof-of-work found  \n  hash: %s  \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
    pblock->print();
    printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());

    // Found a solution
    {
4411
        LOCK(cs_main);
s_nakamoto's avatar
s_nakamoto committed
4412
4413
4414
4415
4416
4417
4418
        if (pblock->hashPrevBlock != hashBestChain)
            return error("BitcoinMiner : generated block is stale");

        // Remove key from key pool
        reservekey.KeepKey();

        // Track how many getdata requests this block gets
4419
4420
        {
            LOCK(wallet.cs_wallet);
Pieter Wuille's avatar
Pieter Wuille committed
4421
            wallet.mapRequestCount[pblock->GetHash()] = 0;
4422
        }
s_nakamoto's avatar
s_nakamoto committed
4423
4424

        // Process this block the same as if we had received it from another node
Pieter Wuille's avatar
Pieter Wuille committed
4425
4426
        CValidationState state;
        if (!ProcessBlock(state, NULL, pblock))
s_nakamoto's avatar
s_nakamoto committed
4427
4428
4429
4430
4431
4432
            return error("BitcoinMiner : ProcessBlock, block not accepted");
    }

    return true;
}

Pieter Wuille's avatar
Pieter Wuille committed
4433
4434
void static ThreadBitcoinMiner(void* parg);

4435
4436
4437
4438
static bool fGenerateBitcoins = false;
static bool fLimitProcessors = false;
static int nLimitProcessors = -1;

Pieter Wuille's avatar
Pieter Wuille committed
4439
void static BitcoinMiner(CWallet *pwallet)
s_nakamoto's avatar
s_nakamoto committed
4440
4441
4442
4443
{
    printf("BitcoinMiner started\n");
    SetThreadPriority(THREAD_PRIORITY_LOWEST);

4444
    // Make this thread recognisable as the mining thread
4445
    RenameThread("bitcoin-miner");
4446

s_nakamoto's avatar
s_nakamoto committed
4447
    // Each thread has its own key and counter
Pieter Wuille's avatar
Pieter Wuille committed
4448
    CReserveKey reservekey(pwallet);
4449
    unsigned int nExtraNonce = 0;
s_nakamoto's avatar
s_nakamoto committed
4450

s_nakamoto's avatar
s_nakamoto committed
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
    while (fGenerateBitcoins)
    {
        if (fShutdown)
            return;
        while (vNodes.empty() || IsInitialBlockDownload())
        {
            Sleep(1000);
            if (fShutdown)
                return;
            if (!fGenerateBitcoins)
                return;
        }


        //
        // Create new block
        //
s_nakamoto's avatar
s_nakamoto committed
4468
4469
4470
        unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
        CBlockIndex* pindexPrev = pindexBest;

4471
4472
        auto_ptr<CBlockTemplate> pblocktemplate(CreateNewBlock(reservekey));
        if (!pblocktemplate.get())
s_nakamoto's avatar
s_nakamoto committed
4473
            return;
4474
4475
        CBlock *pblock = &pblocktemplate->block;
        IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
s_nakamoto's avatar
s_nakamoto committed
4476

4477
        printf("Running BitcoinMiner with %"PRIszu" transactions in block (%u bytes)\n", pblock->vtx.size(),
4478
               ::GetSerializeSize(*pblock, SER_NETWORK, PROTOCOL_VERSION));
s_nakamoto's avatar
s_nakamoto committed
4479
4480
4481


        //
4482
        // Pre-build hash buffers
s_nakamoto's avatar
s_nakamoto committed
4483
        //
s_nakamoto's avatar
s_nakamoto committed
4484
4485
4486
4487
        char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
        char pdatabuf[128+16];    char* pdata     = alignup<16>(pdatabuf);
        char phash1buf[64+16];    char* phash1    = alignup<16>(phash1buf);

4488
        FormatHashBuffers(pblock, pmidstate, pdata, phash1);
s_nakamoto's avatar
s_nakamoto committed
4489
4490

        unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
4491
        unsigned int& nBlockBits = *(unsigned int*)(pdata + 64 + 8);
s_nakamoto's avatar
s_nakamoto committed
4492
        unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
s_nakamoto's avatar
s_nakamoto committed
4493
4494
4495
4496
4497


        //
        // Search
        //
4498
        int64 nStart = GetTime();
s_nakamoto's avatar
s_nakamoto committed
4499
4500
4501
4502
4503
        uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
        uint256 hashbuf[2];
        uint256& hash = *alignup<16>(hashbuf);
        loop
        {
4504
4505
4506
            unsigned int nHashesDone = 0;
            unsigned int nNonceFound;

4507
            // Crypto++ SHA256
4508
4509
            nNonceFound = ScanHash_CryptoPP(pmidstate, pdata + 64, phash1,
                                            (char*)&hash, nHashesDone);
s_nakamoto's avatar
s_nakamoto committed
4510

4511
            // Check if something found
4512
            if (nNonceFound != (unsigned int) -1)
s_nakamoto's avatar
s_nakamoto committed
4513
            {
4514
                for (unsigned int i = 0; i < sizeof(hash)/4; i++)
s_nakamoto's avatar
s_nakamoto committed
4515
4516
4517
4518
                    ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);

                if (hash <= hashTarget)
                {
4519
4520
                    // Found a solution
                    pblock->nNonce = ByteReverse(nNonceFound);
s_nakamoto's avatar
s_nakamoto committed
4521
4522
4523
                    assert(hash == pblock->GetHash());

                    SetThreadPriority(THREAD_PRIORITY_NORMAL);
4524
                    CheckWork(pblock, *pwalletMain, reservekey);
s_nakamoto's avatar
s_nakamoto committed
4525
4526
4527
4528
4529
                    SetThreadPriority(THREAD_PRIORITY_LOWEST);
                    break;
                }
            }

4530
            // Meter hashes/sec
4531
            static int64 nHashCounter;
4532
            if (nHPSTimerStart == 0)
s_nakamoto's avatar
s_nakamoto committed
4533
            {
4534
4535
4536
4537
4538
4539
4540
4541
                nHPSTimerStart = GetTimeMillis();
                nHashCounter = 0;
            }
            else
                nHashCounter += nHashesDone;
            if (GetTimeMillis() - nHPSTimerStart > 4000)
            {
                static CCriticalSection cs;
s_nakamoto's avatar
s_nakamoto committed
4542
                {
4543
                    LOCK(cs);
4544
                    if (GetTimeMillis() - nHPSTimerStart > 4000)
s_nakamoto's avatar
s_nakamoto committed
4545
                    {
4546
4547
4548
                        dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
                        nHPSTimerStart = GetTimeMillis();
                        nHashCounter = 0;
4549
                        static int64 nLogTime;
4550
                        if (GetTime() - nLogTime > 30 * 60)
s_nakamoto's avatar
s_nakamoto committed
4551
                        {
4552
                            nLogTime = GetTime();
Pieter Wuille's avatar
Pieter Wuille committed
4553
                            printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[THREAD_MINER], dHashesPerSec/1000.0);
s_nakamoto's avatar
s_nakamoto committed
4554
4555
4556
                        }
                    }
                }
4557
            }
s_nakamoto's avatar
s_nakamoto committed
4558

4559
4560
4561
4562
4563
            // Check for stop or if block needs to be rebuilt
            if (fShutdown)
                return;
            if (!fGenerateBitcoins)
                return;
Pieter Wuille's avatar
Pieter Wuille committed
4564
            if (fLimitProcessors && vnThreadsRunning[THREAD_MINER] > nLimitProcessors)
4565
4566
4567
                return;
            if (vNodes.empty())
                break;
s_nakamoto's avatar
s_nakamoto committed
4568
            if (nBlockNonce >= 0xffff0000)
4569
4570
4571
4572
4573
                break;
            if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
                break;
            if (pindexPrev != pindexBest)
                break;
s_nakamoto's avatar
s_nakamoto committed
4574

4575
            // Update nTime every few seconds
4576
            pblock->UpdateTime(pindexPrev);
s_nakamoto's avatar
s_nakamoto committed
4577
            nBlockTime = ByteReverse(pblock->nTime);
4578
4579
4580
4581
4582
4583
            if (fTestNet)
            {
                // Changing pblock->nTime can change work required on testnet:
                nBlockBits = ByteReverse(pblock->nBits);
                hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
            }
s_nakamoto's avatar
s_nakamoto committed
4584
4585
4586
4587
        }
    }
}

Pieter Wuille's avatar
Pieter Wuille committed
4588
void static ThreadBitcoinMiner(void* parg)
s_nakamoto's avatar
s_nakamoto committed
4589
{
Pieter Wuille's avatar
Pieter Wuille committed
4590
    CWallet* pwallet = (CWallet*)parg;
4591
    try
s_nakamoto's avatar
s_nakamoto committed
4592
    {
Pieter Wuille's avatar
Pieter Wuille committed
4593
        vnThreadsRunning[THREAD_MINER]++;
Pieter Wuille's avatar
Pieter Wuille committed
4594
        BitcoinMiner(pwallet);
Pieter Wuille's avatar
Pieter Wuille committed
4595
        vnThreadsRunning[THREAD_MINER]--;
4596
    }
4597
    catch (std::exception& e) {
Pieter Wuille's avatar
Pieter Wuille committed
4598
        vnThreadsRunning[THREAD_MINER]--;
4599
4600
        PrintException(&e, "ThreadBitcoinMiner()");
    } catch (...) {
Pieter Wuille's avatar
Pieter Wuille committed
4601
        vnThreadsRunning[THREAD_MINER]--;
4602
        PrintException(NULL, "ThreadBitcoinMiner()");
s_nakamoto's avatar
s_nakamoto committed
4603
    }
4604
    nHPSTimerStart = 0;
Pieter Wuille's avatar
Pieter Wuille committed
4605
    if (vnThreadsRunning[THREAD_MINER] == 0)
4606
        dHashesPerSec = 0;
Pieter Wuille's avatar
Pieter Wuille committed
4607
    printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[THREAD_MINER]);
4608
4609
}

s_nakamoto's avatar
s_nakamoto committed
4610

Pieter Wuille's avatar
Pieter Wuille committed
4611
void GenerateBitcoins(bool fGenerate, CWallet* pwallet)
s_nakamoto's avatar
s_nakamoto committed
4612
{
4613
4614
4615
4616
4617
4618
4619
    fGenerateBitcoins = fGenerate;
    nLimitProcessors = GetArg("-genproclimit", -1);
    if (nLimitProcessors == 0)
        fGenerateBitcoins = false;
    fLimitProcessors = (nLimitProcessors != -1);

    if (fGenerate)
s_nakamoto's avatar
s_nakamoto committed
4620
    {
4621
4622
4623
4624
4625
4626
        int nProcessors = boost::thread::hardware_concurrency();
        printf("%d processors\n", nProcessors);
        if (nProcessors < 1)
            nProcessors = 1;
        if (fLimitProcessors && nProcessors > nLimitProcessors)
            nProcessors = nLimitProcessors;
Pieter Wuille's avatar
Pieter Wuille committed
4627
        int nAddThreads = nProcessors - vnThreadsRunning[THREAD_MINER];
4628
4629
        printf("Starting %d BitcoinMiner threads\n", nAddThreads);
        for (int i = 0; i < nAddThreads; i++)
s_nakamoto's avatar
s_nakamoto committed
4630
        {
4631
4632
            if (!NewThread(ThreadBitcoinMiner, pwallet))
                printf("Error: NewThread(ThreadBitcoinMiner) failed\n");
4633
            Sleep(10);
s_nakamoto's avatar
s_nakamoto committed
4634
        }
4635
    }
s_nakamoto's avatar
s_nakamoto committed
4636
}
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690

// Amount compression:
// * If the amount is 0, output 0
// * first, divide the amount (in base units) by the largest power of 10 possible; call the exponent e (e is max 9)
// * if e<9, the last digit of the resulting number cannot be 0; store it as d, and drop it (divide by 10)
//   * call the result n
//   * output 1 + 10*(9*n + d - 1) + e
// * if e==9, we only know the resulting number is not zero, so output 1 + 10*(n - 1) + 9
// (this is decodable, as d is in [1-9] and e is in [0-9])

uint64 CTxOutCompressor::CompressAmount(uint64 n)
{
    if (n == 0)
        return 0;
    int e = 0;
    while (((n % 10) == 0) && e < 9) {
        n /= 10;
        e++;
    }
    if (e < 9) {
        int d = (n % 10);
        assert(d >= 1 && d <= 9);
        n /= 10;
        return 1 + (n*9 + d - 1)*10 + e;
    } else {
        return 1 + (n - 1)*10 + 9;
    }
}

uint64 CTxOutCompressor::DecompressAmount(uint64 x)
{
    // x = 0  OR  x = 1+10*(9*n + d - 1) + e  OR  x = 1+10*(n - 1) + 9
    if (x == 0)
        return 0;
    x--;
    // x = 10*(9*n + d - 1) + e
    int e = x % 10;
    x /= 10;
    uint64 n = 0;
    if (e < 9) {
        // x = 9*n + d - 1
        int d = (x % 9) + 1;
        x /= 9;
        // x = n
        n = x*10 + d;
    } else {
        n = x+1;
    }
    while (e) {
        n *= 10;
        e--;
    }
    return n;
}