~ubuntu-branches/ubuntu/precise/bitcoin/precise

« back to all changes in this revision

Viewing changes to src/main.cpp

  • Committer: Bazaar Package Importer
  • Author(s): Jonas Smedegaard
  • Date: 2011-01-17 19:48:35 UTC
  • Revision ID: james.westby@ubuntu.com-20110117194835-a3kljf7m1pcv2bbn
Tags: upstream-0.3.19~dfsg
ImportĀ upstreamĀ versionĀ 0.3.19~dfsg

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
// Copyright (c) 2009-2010 Satoshi Nakamoto
 
2
// Distributed under the MIT/X11 software license, see the accompanying
 
3
// file license.txt or http://www.opensource.org/licenses/mit-license.php.
 
4
 
 
5
#include "headers.h"
 
6
#include "cryptopp/sha.h"
 
7
 
 
8
 
 
9
 
 
10
 
 
11
 
 
12
//
 
13
// Global state
 
14
//
 
15
 
 
16
CCriticalSection cs_main;
 
17
 
 
18
map<uint256, CTransaction> mapTransactions;
 
19
CCriticalSection cs_mapTransactions;
 
20
unsigned int nTransactionsUpdated = 0;
 
21
map<COutPoint, CInPoint> mapNextTx;
 
22
 
 
23
map<uint256, CBlockIndex*> mapBlockIndex;
 
24
uint256 hashGenesisBlock("0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f");
 
25
CBigNum bnProofOfWorkLimit(~uint256(0) >> 32);
 
26
CBlockIndex* pindexGenesisBlock = NULL;
 
27
int nBestHeight = -1;
 
28
CBigNum bnBestChainWork = 0;
 
29
CBigNum bnBestInvalidWork = 0;
 
30
uint256 hashBestChain = 0;
 
31
CBlockIndex* pindexBest = NULL;
 
32
int64 nTimeBestReceived = 0;
 
33
 
 
34
map<uint256, CBlock*> mapOrphanBlocks;
 
35
multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
 
36
 
 
37
map<uint256, CDataStream*> mapOrphanTransactions;
 
38
multimap<uint256, CDataStream*> mapOrphanTransactionsByPrev;
 
39
 
 
40
map<uint256, CWalletTx> mapWallet;
 
41
vector<uint256> vWalletUpdated;
 
42
CCriticalSection cs_mapWallet;
 
43
 
 
44
map<vector<unsigned char>, CPrivKey> mapKeys;
 
45
map<uint160, vector<unsigned char> > mapPubKeys;
 
46
CCriticalSection cs_mapKeys;
 
47
CKey keyUser;
 
48
 
 
49
map<uint256, int> mapRequestCount;
 
50
CCriticalSection cs_mapRequestCount;
 
51
 
 
52
map<string, string> mapAddressBook;
 
53
CCriticalSection cs_mapAddressBook;
 
54
 
 
55
vector<unsigned char> vchDefaultKey;
 
56
 
 
57
double dHashesPerSec;
 
58
int64 nHPSTimerStart;
 
59
 
 
60
// Settings
 
61
int fGenerateBitcoins = false;
 
62
int64 nTransactionFee = 0;
 
63
CAddress addrIncoming;
 
64
int fLimitProcessors = false;
 
65
int nLimitProcessors = 1;
 
66
int fMinimizeToTray = true;
 
67
int fMinimizeOnClose = true;
 
68
 
 
69
 
 
70
 
 
71
 
 
72
 
 
73
 
 
74
//////////////////////////////////////////////////////////////////////////////
 
75
//
 
76
// mapKeys
 
77
//
 
78
 
 
79
bool AddKey(const CKey& key)
 
80
{
 
81
    CRITICAL_BLOCK(cs_mapKeys)
 
82
    {
 
83
        mapKeys[key.GetPubKey()] = key.GetPrivKey();
 
84
        mapPubKeys[Hash160(key.GetPubKey())] = key.GetPubKey();
 
85
    }
 
86
    return CWalletDB().WriteKey(key.GetPubKey(), key.GetPrivKey());
 
87
}
 
88
 
 
89
vector<unsigned char> GenerateNewKey()
 
90
{
 
91
    RandAddSeedPerfmon();
 
92
    CKey key;
 
93
    key.MakeNewKey();
 
94
    if (!AddKey(key))
 
95
        throw runtime_error("GenerateNewKey() : AddKey failed");
 
96
    return key.GetPubKey();
 
97
}
 
98
 
 
99
 
 
100
 
 
101
 
 
102
//////////////////////////////////////////////////////////////////////////////
 
103
//
 
104
// mapWallet
 
105
//
 
106
 
 
107
bool AddToWallet(const CWalletTx& wtxIn)
 
108
{
 
109
    uint256 hash = wtxIn.GetHash();
 
110
    CRITICAL_BLOCK(cs_mapWallet)
 
111
    {
 
112
        // Inserts only if not already there, returns tx inserted or tx found
 
113
        pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
 
114
        CWalletTx& wtx = (*ret.first).second;
 
115
        bool fInsertedNew = ret.second;
 
116
        if (fInsertedNew)
 
117
            wtx.nTimeReceived = GetAdjustedTime();
 
118
 
 
119
        bool fUpdated = false;
 
120
        if (!fInsertedNew)
 
121
        {
 
122
            // Merge
 
123
            if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
 
124
            {
 
125
                wtx.hashBlock = wtxIn.hashBlock;
 
126
                fUpdated = true;
 
127
            }
 
128
            if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
 
129
            {
 
130
                wtx.vMerkleBranch = wtxIn.vMerkleBranch;
 
131
                wtx.nIndex = wtxIn.nIndex;
 
132
                fUpdated = true;
 
133
            }
 
134
            if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
 
135
            {
 
136
                wtx.fFromMe = wtxIn.fFromMe;
 
137
                fUpdated = true;
 
138
            }
 
139
            if (wtxIn.fSpent && wtxIn.fSpent != wtx.fSpent)
 
140
            {
 
141
                wtx.fSpent = wtxIn.fSpent;
 
142
                fUpdated = true;
 
143
            }
 
144
        }
 
145
 
 
146
        //// debug print
 
147
        printf("AddToWallet %s  %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
 
148
 
 
149
        // Write to disk
 
150
        if (fInsertedNew || fUpdated)
 
151
            if (!wtx.WriteToDisk())
 
152
                return false;
 
153
 
 
154
        // If default receiving address gets used, replace it with a new one
 
155
        CScript scriptDefaultKey;
 
156
        scriptDefaultKey.SetBitcoinAddress(vchDefaultKey);
 
157
        foreach(const CTxOut& txout, wtx.vout)
 
158
        {
 
159
            if (txout.scriptPubKey == scriptDefaultKey)
 
160
            {
 
161
                CWalletDB walletdb;
 
162
                vchDefaultKey = GetKeyFromKeyPool();
 
163
                walletdb.WriteDefaultKey(vchDefaultKey);
 
164
                walletdb.WriteName(PubKeyToAddress(vchDefaultKey), "");
 
165
            }
 
166
        }
 
167
 
 
168
        // Notify UI
 
169
        vWalletUpdated.push_back(hash);
 
170
    }
 
171
 
 
172
    // Refresh UI
 
173
    MainFrameRepaint();
 
174
    return true;
 
175
}
 
176
 
 
177
bool AddToWalletIfMine(const CTransaction& tx, const CBlock* pblock)
 
178
{
 
179
    if (tx.IsMine() || mapWallet.count(tx.GetHash()))
 
180
    {
 
181
        CWalletTx wtx(tx);
 
182
        // Get merkle branch if transaction was found in a block
 
183
        if (pblock)
 
184
            wtx.SetMerkleBranch(pblock);
 
185
        return AddToWallet(wtx);
 
186
    }
 
187
    return true;
 
188
}
 
189
 
 
190
bool EraseFromWallet(uint256 hash)
 
191
{
 
192
    CRITICAL_BLOCK(cs_mapWallet)
 
193
    {
 
194
        if (mapWallet.erase(hash))
 
195
            CWalletDB().EraseTx(hash);
 
196
    }
 
197
    return true;
 
198
}
 
199
 
 
200
void WalletUpdateSpent(const COutPoint& prevout)
 
201
{
 
202
    // Anytime a signature is successfully verified, it's proof the outpoint is spent.
 
203
    // Update the wallet spent flag if it doesn't know due to wallet.dat being
 
204
    // restored from backup or the user making copies of wallet.dat.
 
205
    CRITICAL_BLOCK(cs_mapWallet)
 
206
    {
 
207
        map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);
 
208
        if (mi != mapWallet.end())
 
209
        {
 
210
            CWalletTx& wtx = (*mi).second;
 
211
            if (!wtx.fSpent && wtx.vout[prevout.n].IsMine())
 
212
            {
 
213
                printf("WalletUpdateSpent found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
 
214
                wtx.fSpent = true;
 
215
                wtx.WriteToDisk();
 
216
                vWalletUpdated.push_back(prevout.hash);
 
217
            }
 
218
        }
 
219
    }
 
220
}
 
221
 
 
222
 
 
223
 
 
224
 
 
225
 
 
226
 
 
227
 
 
228
 
 
229
//////////////////////////////////////////////////////////////////////////////
 
230
//
 
231
// mapOrphanTransactions
 
232
//
 
233
 
 
234
void AddOrphanTx(const CDataStream& vMsg)
 
235
{
 
236
    CTransaction tx;
 
237
    CDataStream(vMsg) >> tx;
 
238
    uint256 hash = tx.GetHash();
 
239
    if (mapOrphanTransactions.count(hash))
 
240
        return;
 
241
    CDataStream* pvMsg = mapOrphanTransactions[hash] = new CDataStream(vMsg);
 
242
    foreach(const CTxIn& txin, tx.vin)
 
243
        mapOrphanTransactionsByPrev.insert(make_pair(txin.prevout.hash, pvMsg));
 
244
}
 
245
 
 
246
void EraseOrphanTx(uint256 hash)
 
247
{
 
248
    if (!mapOrphanTransactions.count(hash))
 
249
        return;
 
250
    const CDataStream* pvMsg = mapOrphanTransactions[hash];
 
251
    CTransaction tx;
 
252
    CDataStream(*pvMsg) >> tx;
 
253
    foreach(const CTxIn& txin, tx.vin)
 
254
    {
 
255
        for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(txin.prevout.hash);
 
256
             mi != mapOrphanTransactionsByPrev.upper_bound(txin.prevout.hash);)
 
257
        {
 
258
            if ((*mi).second == pvMsg)
 
259
                mapOrphanTransactionsByPrev.erase(mi++);
 
260
            else
 
261
                mi++;
 
262
        }
 
263
    }
 
264
    delete pvMsg;
 
265
    mapOrphanTransactions.erase(hash);
 
266
}
 
267
 
 
268
 
 
269
 
 
270
 
 
271
 
 
272
 
 
273
 
 
274
 
 
275
//////////////////////////////////////////////////////////////////////////////
 
276
//
 
277
// CTransaction
 
278
//
 
279
 
 
280
bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
 
281
{
 
282
    SetNull();
 
283
    if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
 
284
        return false;
 
285
    if (!ReadFromDisk(txindexRet.pos))
 
286
        return false;
 
287
    if (prevout.n >= vout.size())
 
288
    {
 
289
        SetNull();
 
290
        return false;
 
291
    }
 
292
    return true;
 
293
}
 
294
 
 
295
bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
 
296
{
 
297
    CTxIndex txindex;
 
298
    return ReadFromDisk(txdb, prevout, txindex);
 
299
}
 
300
 
 
301
bool CTransaction::ReadFromDisk(COutPoint prevout)
 
302
{
 
303
    CTxDB txdb("r");
 
304
    CTxIndex txindex;
 
305
    return ReadFromDisk(txdb, prevout, txindex);
 
306
}
 
307
 
 
308
bool CTxIn::IsMine() const
 
309
{
 
310
    CRITICAL_BLOCK(cs_mapWallet)
 
311
    {
 
312
        map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);
 
313
        if (mi != mapWallet.end())
 
314
        {
 
315
            const CWalletTx& prev = (*mi).second;
 
316
            if (prevout.n < prev.vout.size())
 
317
                if (prev.vout[prevout.n].IsMine())
 
318
                    return true;
 
319
        }
 
320
    }
 
321
    return false;
 
322
}
 
323
 
 
324
int64 CTxIn::GetDebit() const
 
325
{
 
326
    CRITICAL_BLOCK(cs_mapWallet)
 
327
    {
 
328
        map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);
 
329
        if (mi != mapWallet.end())
 
330
        {
 
331
            const CWalletTx& prev = (*mi).second;
 
332
            if (prevout.n < prev.vout.size())
 
333
                if (prev.vout[prevout.n].IsMine())
 
334
                    return prev.vout[prevout.n].nValue;
 
335
        }
 
336
    }
 
337
    return 0;
 
338
}
 
339
 
 
340
int64 CWalletTx::GetTxTime() const
 
341
{
 
342
    if (!fTimeReceivedIsTxTime && hashBlock != 0)
 
343
    {
 
344
        // If we did not receive the transaction directly, we rely on the block's
 
345
        // time to figure out when it happened.  We use the median over a range
 
346
        // of blocks to try to filter out inaccurate block times.
 
347
        map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
 
348
        if (mi != mapBlockIndex.end())
 
349
        {
 
350
            CBlockIndex* pindex = (*mi).second;
 
351
            if (pindex)
 
352
                return pindex->GetMedianTime();
 
353
        }
 
354
    }
 
355
    return nTimeReceived;
 
356
}
 
357
 
 
358
int CWalletTx::GetRequestCount() const
 
359
{
 
360
    // Returns -1 if it wasn't being tracked
 
361
    int nRequests = -1;
 
362
    CRITICAL_BLOCK(cs_mapRequestCount)
 
363
    {
 
364
        if (IsCoinBase())
 
365
        {
 
366
            // Generated block
 
367
            if (hashBlock != 0)
 
368
            {
 
369
                map<uint256, int>::iterator mi = mapRequestCount.find(hashBlock);
 
370
                if (mi != mapRequestCount.end())
 
371
                    nRequests = (*mi).second;
 
372
            }
 
373
        }
 
374
        else
 
375
        {
 
376
            // Did anyone request this transaction?
 
377
            map<uint256, int>::iterator mi = mapRequestCount.find(GetHash());
 
378
            if (mi != mapRequestCount.end())
 
379
            {
 
380
                nRequests = (*mi).second;
 
381
 
 
382
                // How about the block it's in?
 
383
                if (nRequests == 0 && hashBlock != 0)
 
384
                {
 
385
                    map<uint256, int>::iterator mi = mapRequestCount.find(hashBlock);
 
386
                    if (mi != mapRequestCount.end())
 
387
                        nRequests = (*mi).second;
 
388
                    else
 
389
                        nRequests = 1; // If it's in someone else's block it must have got out
 
390
                }
 
391
            }
 
392
        }
 
393
    }
 
394
    return nRequests;
 
395
}
 
396
 
 
397
 
 
398
 
 
399
 
 
400
int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
 
401
{
 
402
    if (fClient)
 
403
    {
 
404
        if (hashBlock == 0)
 
405
            return 0;
 
406
    }
 
407
    else
 
408
    {
 
409
        CBlock blockTmp;
 
410
        if (pblock == NULL)
 
411
        {
 
412
            // Load the block this tx is in
 
413
            CTxIndex txindex;
 
414
            if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
 
415
                return 0;
 
416
            if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
 
417
                return 0;
 
418
            pblock = &blockTmp;
 
419
        }
 
420
 
 
421
        // Update the tx's hashBlock
 
422
        hashBlock = pblock->GetHash();
 
423
 
 
424
        // Locate the transaction
 
425
        for (nIndex = 0; nIndex < pblock->vtx.size(); nIndex++)
 
426
            if (pblock->vtx[nIndex] == *(CTransaction*)this)
 
427
                break;
 
428
        if (nIndex == pblock->vtx.size())
 
429
        {
 
430
            vMerkleBranch.clear();
 
431
            nIndex = -1;
 
432
            printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
 
433
            return 0;
 
434
        }
 
435
 
 
436
        // Fill in merkle branch
 
437
        vMerkleBranch = pblock->GetMerkleBranch(nIndex);
 
438
    }
 
439
 
 
440
    // Is the tx in a block that's in the main chain
 
441
    map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
 
442
    if (mi == mapBlockIndex.end())
 
443
        return 0;
 
444
    CBlockIndex* pindex = (*mi).second;
 
445
    if (!pindex || !pindex->IsInMainChain())
 
446
        return 0;
 
447
 
 
448
    return pindexBest->nHeight - pindex->nHeight + 1;
 
449
}
 
450
 
 
451
 
 
452
 
 
453
void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
 
454
{
 
455
    vtxPrev.clear();
 
456
 
 
457
    const int COPY_DEPTH = 3;
 
458
    if (SetMerkleBranch() < COPY_DEPTH)
 
459
    {
 
460
        vector<uint256> vWorkQueue;
 
461
        foreach(const CTxIn& txin, vin)
 
462
            vWorkQueue.push_back(txin.prevout.hash);
 
463
 
 
464
        // This critsect is OK because txdb is already open
 
465
        CRITICAL_BLOCK(cs_mapWallet)
 
466
        {
 
467
            map<uint256, const CMerkleTx*> mapWalletPrev;
 
468
            set<uint256> setAlreadyDone;
 
469
            for (int i = 0; i < vWorkQueue.size(); i++)
 
470
            {
 
471
                uint256 hash = vWorkQueue[i];
 
472
                if (setAlreadyDone.count(hash))
 
473
                    continue;
 
474
                setAlreadyDone.insert(hash);
 
475
 
 
476
                CMerkleTx tx;
 
477
                if (mapWallet.count(hash))
 
478
                {
 
479
                    tx = mapWallet[hash];
 
480
                    foreach(const CMerkleTx& txWalletPrev, mapWallet[hash].vtxPrev)
 
481
                        mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
 
482
                }
 
483
                else if (mapWalletPrev.count(hash))
 
484
                {
 
485
                    tx = *mapWalletPrev[hash];
 
486
                }
 
487
                else if (!fClient && txdb.ReadDiskTx(hash, tx))
 
488
                {
 
489
                    ;
 
490
                }
 
491
                else
 
492
                {
 
493
                    printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
 
494
                    continue;
 
495
                }
 
496
 
 
497
                int nDepth = tx.SetMerkleBranch();
 
498
                vtxPrev.push_back(tx);
 
499
 
 
500
                if (nDepth < COPY_DEPTH)
 
501
                    foreach(const CTxIn& txin, tx.vin)
 
502
                        vWorkQueue.push_back(txin.prevout.hash);
 
503
            }
 
504
        }
 
505
    }
 
506
 
 
507
    reverse(vtxPrev.begin(), vtxPrev.end());
 
508
}
 
509
 
 
510
 
 
511
 
 
512
 
 
513
 
 
514
 
 
515
 
 
516
 
 
517
 
 
518
 
 
519
 
 
520
bool CTransaction::CheckTransaction() const
 
521
{
 
522
    // Basic checks that don't depend on any context
 
523
    if (vin.empty() || vout.empty())
 
524
        return error("CTransaction::CheckTransaction() : vin or vout empty");
 
525
 
 
526
    // Size limits
 
527
    if (::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
 
528
        return error("CTransaction::CheckTransaction() : size limits failed");
 
529
 
 
530
    // Check for negative or overflow output values
 
531
    int64 nValueOut = 0;
 
532
    foreach(const CTxOut& txout, vout)
 
533
    {
 
534
        if (txout.nValue < 0)
 
535
            return error("CTransaction::CheckTransaction() : txout.nValue negative");
 
536
        if (txout.nValue > MAX_MONEY)
 
537
            return error("CTransaction::CheckTransaction() : txout.nValue too high");
 
538
        nValueOut += txout.nValue;
 
539
        if (!MoneyRange(nValueOut))
 
540
            return error("CTransaction::CheckTransaction() : txout total out of range");
 
541
    }
 
542
 
 
543
    if (IsCoinBase())
 
544
    {
 
545
        if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
 
546
            return error("CTransaction::CheckTransaction() : coinbase script size");
 
547
    }
 
548
    else
 
549
    {
 
550
        foreach(const CTxIn& txin, vin)
 
551
            if (txin.prevout.IsNull())
 
552
                return error("CTransaction::CheckTransaction() : prevout is null");
 
553
    }
 
554
 
 
555
    return true;
 
556
}
 
557
 
 
558
bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
 
559
{
 
560
    if (pfMissingInputs)
 
561
        *pfMissingInputs = false;
 
562
 
 
563
    if (!CheckTransaction())
 
564
        return error("AcceptToMemoryPool() : CheckTransaction failed");
 
565
 
 
566
    // Coinbase is only valid in a block, not as a loose transaction
 
567
    if (IsCoinBase())
 
568
        return error("AcceptToMemoryPool() : coinbase as individual tx");
 
569
 
 
570
    // To help v0.1.5 clients who would see it as a negative number
 
571
    if ((int64)nLockTime > INT_MAX)
 
572
        return error("AcceptToMemoryPool() : not accepting nLockTime beyond 2038 yet");
 
573
 
 
574
    // Safety limits
 
575
    unsigned int nSize = ::GetSerializeSize(*this, SER_NETWORK);
 
576
    if (GetSigOpCount() > 2 || nSize < 100)
 
577
        return error("AcceptToMemoryPool() : nonstandard transaction");
 
578
 
 
579
    // Rather not work on nonstandard transactions
 
580
    if (!IsStandard())
 
581
        return error("AcceptToMemoryPool() : nonstandard transaction type");
 
582
 
 
583
    // Do we already have it?
 
584
    uint256 hash = GetHash();
 
585
    CRITICAL_BLOCK(cs_mapTransactions)
 
586
        if (mapTransactions.count(hash))
 
587
            return false;
 
588
    if (fCheckInputs)
 
589
        if (txdb.ContainsTx(hash))
 
590
            return false;
 
591
 
 
592
    // Check for conflicts with in-memory transactions
 
593
    CTransaction* ptxOld = NULL;
 
594
    for (int i = 0; i < vin.size(); i++)
 
595
    {
 
596
        COutPoint outpoint = vin[i].prevout;
 
597
        if (mapNextTx.count(outpoint))
 
598
        {
 
599
            // Disable replacement feature for now
 
600
            return false;
 
601
 
 
602
            // Allow replacing with a newer version of the same transaction
 
603
            if (i != 0)
 
604
                return false;
 
605
            ptxOld = mapNextTx[outpoint].ptx;
 
606
            if (ptxOld->IsFinal())
 
607
                return false;
 
608
            if (!IsNewerThan(*ptxOld))
 
609
                return false;
 
610
            for (int i = 0; i < vin.size(); i++)
 
611
            {
 
612
                COutPoint outpoint = vin[i].prevout;
 
613
                if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
 
614
                    return false;
 
615
            }
 
616
            break;
 
617
        }
 
618
    }
 
619
 
 
620
    if (fCheckInputs)
 
621
    {
 
622
        // Check against previous transactions
 
623
        map<uint256, CTxIndex> mapUnused;
 
624
        int64 nFees = 0;
 
625
        if (!ConnectInputs(txdb, mapUnused, CDiskTxPos(1,1,1), pindexBest, nFees, false, false))
 
626
        {
 
627
            if (pfMissingInputs)
 
628
                *pfMissingInputs = true;
 
629
            return error("AcceptToMemoryPool() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
 
630
        }
 
631
 
 
632
        // Don't accept it if it can't get into a block
 
633
        if (nFees < GetMinFee(1000))
 
634
            return error("AcceptToMemoryPool() : not enough fees");
 
635
 
 
636
        // Limit free transactions per 10 minutes
 
637
        if (nFees < CENT && GetBoolArg("-limitfreerelay"))
 
638
        {
 
639
            static int64 nNextReset;
 
640
            static int64 nFreeCount;
 
641
            if (GetTime() > nNextReset)
 
642
            {
 
643
                nNextReset = GetTime() + 10 * 60;
 
644
                nFreeCount = 0;
 
645
            }
 
646
            if (nFreeCount > 150000 && !IsFromMe())
 
647
                return error("AcceptToMemoryPool() : free transaction rejected by rate limiter");
 
648
            nFreeCount += nSize;
 
649
        }
 
650
    }
 
651
 
 
652
    // Store transaction in memory
 
653
    CRITICAL_BLOCK(cs_mapTransactions)
 
654
    {
 
655
        if (ptxOld)
 
656
        {
 
657
            printf("AcceptToMemoryPool() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
 
658
            ptxOld->RemoveFromMemoryPool();
 
659
        }
 
660
        AddToMemoryPoolUnchecked();
 
661
    }
 
662
 
 
663
    ///// are we sure this is ok when loading transactions or restoring block txes
 
664
    // If updated, erase old tx from wallet
 
665
    if (ptxOld)
 
666
        EraseFromWallet(ptxOld->GetHash());
 
667
 
 
668
    printf("AcceptToMemoryPool(): accepted %s\n", hash.ToString().substr(0,10).c_str());
 
669
    return true;
 
670
}
 
671
 
 
672
 
 
673
bool CTransaction::AddToMemoryPoolUnchecked()
 
674
{
 
675
    // Add to memory pool without checking anything.  Don't call this directly,
 
676
    // call AcceptToMemoryPool to properly check the transaction first.
 
677
    CRITICAL_BLOCK(cs_mapTransactions)
 
678
    {
 
679
        uint256 hash = GetHash();
 
680
        mapTransactions[hash] = *this;
 
681
        for (int i = 0; i < vin.size(); i++)
 
682
            mapNextTx[vin[i].prevout] = CInPoint(&mapTransactions[hash], i);
 
683
        nTransactionsUpdated++;
 
684
    }
 
685
    return true;
 
686
}
 
687
 
 
688
 
 
689
bool CTransaction::RemoveFromMemoryPool()
 
690
{
 
691
    // Remove transaction from memory pool
 
692
    CRITICAL_BLOCK(cs_mapTransactions)
 
693
    {
 
694
        foreach(const CTxIn& txin, vin)
 
695
            mapNextTx.erase(txin.prevout);
 
696
        mapTransactions.erase(GetHash());
 
697
        nTransactionsUpdated++;
 
698
    }
 
699
    return true;
 
700
}
 
701
 
 
702
 
 
703
 
 
704
 
 
705
 
 
706
 
 
707
int CMerkleTx::GetDepthInMainChain(int& nHeightRet) const
 
708
{
 
709
    if (hashBlock == 0 || nIndex == -1)
 
710
        return 0;
 
711
 
 
712
    // Find the block it claims to be in
 
713
    map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
 
714
    if (mi == mapBlockIndex.end())
 
715
        return 0;
 
716
    CBlockIndex* pindex = (*mi).second;
 
717
    if (!pindex || !pindex->IsInMainChain())
 
718
        return 0;
 
719
 
 
720
    // Make sure the merkle branch connects to this block
 
721
    if (!fMerkleVerified)
 
722
    {
 
723
        if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
 
724
            return 0;
 
725
        fMerkleVerified = true;
 
726
    }
 
727
 
 
728
    nHeightRet = pindex->nHeight;
 
729
    return pindexBest->nHeight - pindex->nHeight + 1;
 
730
}
 
731
 
 
732
 
 
733
int CMerkleTx::GetBlocksToMaturity() const
 
734
{
 
735
    if (!IsCoinBase())
 
736
        return 0;
 
737
    return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
 
738
}
 
739
 
 
740
 
 
741
bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
 
742
{
 
743
    if (fClient)
 
744
    {
 
745
        if (!IsInMainChain() && !ClientConnectInputs())
 
746
            return false;
 
747
        return CTransaction::AcceptToMemoryPool(txdb, false);
 
748
    }
 
749
    else
 
750
    {
 
751
        return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
 
752
    }
 
753
}
 
754
 
 
755
 
 
756
 
 
757
bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
 
758
{
 
759
    CRITICAL_BLOCK(cs_mapTransactions)
 
760
    {
 
761
        // Add previous supporting transactions first
 
762
        foreach(CMerkleTx& tx, vtxPrev)
 
763
        {
 
764
            if (!tx.IsCoinBase())
 
765
            {
 
766
                uint256 hash = tx.GetHash();
 
767
                if (!mapTransactions.count(hash) && !txdb.ContainsTx(hash))
 
768
                    tx.AcceptToMemoryPool(txdb, fCheckInputs);
 
769
            }
 
770
        }
 
771
        return AcceptToMemoryPool(txdb, fCheckInputs);
 
772
    }
 
773
    return false;
 
774
}
 
775
 
 
776
void ReacceptWalletTransactions()
 
777
{
 
778
    CTxDB txdb("r");
 
779
    CRITICAL_BLOCK(cs_mapWallet)
 
780
    {
 
781
        foreach(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
 
782
        {
 
783
            CWalletTx& wtx = item.second;
 
784
            if (wtx.fSpent && wtx.IsCoinBase())
 
785
                continue;
 
786
 
 
787
            CTxIndex txindex;
 
788
            if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
 
789
            {
 
790
                // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
 
791
                if (!wtx.fSpent)
 
792
                {
 
793
                    if (txindex.vSpent.size() != wtx.vout.size())
 
794
                    {
 
795
                        printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %d != wtx.vout.size() %d\n", txindex.vSpent.size(), wtx.vout.size());
 
796
                        continue;
 
797
                    }
 
798
                    for (int i = 0; i < txindex.vSpent.size(); i++)
 
799
                    {
 
800
                        if (!txindex.vSpent[i].IsNull() && wtx.vout[i].IsMine())
 
801
                        {
 
802
                            printf("ReacceptWalletTransactions found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
 
803
                            wtx.fSpent = true;
 
804
                            wtx.WriteToDisk();
 
805
                            break;
 
806
                        }
 
807
                    }
 
808
                }
 
809
            }
 
810
            else
 
811
            {
 
812
                // Reaccept any txes of ours that aren't already in a block
 
813
                if (!wtx.IsCoinBase())
 
814
                    wtx.AcceptWalletTransaction(txdb, false);
 
815
            }
 
816
        }
 
817
    }
 
818
}
 
819
 
 
820
 
 
821
void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
 
822
{
 
823
    foreach(const CMerkleTx& tx, vtxPrev)
 
824
    {
 
825
        if (!tx.IsCoinBase())
 
826
        {
 
827
            uint256 hash = tx.GetHash();
 
828
            if (!txdb.ContainsTx(hash))
 
829
                RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx);
 
830
        }
 
831
    }
 
832
    if (!IsCoinBase())
 
833
    {
 
834
        uint256 hash = GetHash();
 
835
        if (!txdb.ContainsTx(hash))
 
836
        {
 
837
            printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
 
838
            RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this);
 
839
        }
 
840
    }
 
841
}
 
842
 
 
843
void ResendWalletTransactions()
 
844
{
 
845
    // Do this infrequently and randomly to avoid giving away
 
846
    // that these are our transactions.
 
847
    static int64 nNextTime;
 
848
    if (GetTime() < nNextTime)
 
849
        return;
 
850
    bool fFirst = (nNextTime == 0);
 
851
    nNextTime = GetTime() + GetRand(30 * 60);
 
852
    if (fFirst)
 
853
        return;
 
854
 
 
855
    // Only do it if there's been a new block since last time
 
856
    static int64 nLastTime;
 
857
    if (nTimeBestReceived < nLastTime)
 
858
        return;
 
859
    nLastTime = GetTime();
 
860
 
 
861
    // Rebroadcast any of our txes that aren't in a block yet
 
862
    printf("ResendWalletTransactions()\n");
 
863
    CTxDB txdb("r");
 
864
    CRITICAL_BLOCK(cs_mapWallet)
 
865
    {
 
866
        // Sort them in chronological order
 
867
        multimap<unsigned int, CWalletTx*> mapSorted;
 
868
        foreach(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
 
869
        {
 
870
            CWalletTx& wtx = item.second;
 
871
            // Don't rebroadcast until it's had plenty of time that
 
872
            // it should have gotten in already by now.
 
873
            if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
 
874
                mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
 
875
        }
 
876
        foreach(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
 
877
        {
 
878
            CWalletTx& wtx = *item.second;
 
879
            wtx.RelayWalletTransaction(txdb);
 
880
        }
 
881
    }
 
882
}
 
883
 
 
884
 
 
885
 
 
886
 
 
887
 
 
888
 
 
889
 
 
890
 
 
891
 
 
892
 
 
893
//////////////////////////////////////////////////////////////////////////////
 
894
//
 
895
// CBlock and CBlockIndex
 
896
//
 
897
 
 
898
bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
 
899
{
 
900
    if (!fReadTransactions)
 
901
    {
 
902
        *this = pindex->GetBlockHeader();
 
903
        return true;
 
904
    }
 
905
    if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
 
906
        return false;
 
907
    if (GetHash() != pindex->GetBlockHash())
 
908
        return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
 
909
    return true;
 
910
}
 
911
 
 
912
uint256 GetOrphanRoot(const CBlock* pblock)
 
913
{
 
914
    // Work back to the first block in the orphan chain
 
915
    while (mapOrphanBlocks.count(pblock->hashPrevBlock))
 
916
        pblock = mapOrphanBlocks[pblock->hashPrevBlock];
 
917
    return pblock->GetHash();
 
918
}
 
919
 
 
920
int64 GetBlockValue(int nHeight, int64 nFees)
 
921
{
 
922
    int64 nSubsidy = 50 * COIN;
 
923
 
 
924
    // Subsidy is cut in half every 4 years
 
925
    nSubsidy >>= (nHeight / 210000);
 
926
 
 
927
    return nSubsidy + nFees;
 
928
}
 
929
 
 
930
unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast)
 
931
{
 
932
    const int64 nTargetTimespan = 14 * 24 * 60 * 60; // two weeks
 
933
    const int64 nTargetSpacing = 10 * 60;
 
934
    const int64 nInterval = nTargetTimespan / nTargetSpacing;
 
935
 
 
936
    // Genesis block
 
937
    if (pindexLast == NULL)
 
938
        return bnProofOfWorkLimit.GetCompact();
 
939
 
 
940
    // Only change once per interval
 
941
    if ((pindexLast->nHeight+1) % nInterval != 0)
 
942
        return pindexLast->nBits;
 
943
 
 
944
    // Go back by what we want to be 14 days worth of blocks
 
945
    const CBlockIndex* pindexFirst = pindexLast;
 
946
    for (int i = 0; pindexFirst && i < nInterval-1; i++)
 
947
        pindexFirst = pindexFirst->pprev;
 
948
    assert(pindexFirst);
 
949
 
 
950
    // Limit adjustment step
 
951
    int64 nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();
 
952
    printf("  nActualTimespan = %"PRI64d"  before bounds\n", nActualTimespan);
 
953
    if (nActualTimespan < nTargetTimespan/4)
 
954
        nActualTimespan = nTargetTimespan/4;
 
955
    if (nActualTimespan > nTargetTimespan*4)
 
956
        nActualTimespan = nTargetTimespan*4;
 
957
 
 
958
    // Retarget
 
959
    CBigNum bnNew;
 
960
    bnNew.SetCompact(pindexLast->nBits);
 
961
    bnNew *= nActualTimespan;
 
962
    bnNew /= nTargetTimespan;
 
963
 
 
964
    if (bnNew > bnProofOfWorkLimit)
 
965
        bnNew = bnProofOfWorkLimit;
 
966
 
 
967
    /// debug print
 
968
    printf("GetNextWorkRequired RETARGET\n");
 
969
    printf("nTargetTimespan = %"PRI64d"    nActualTimespan = %"PRI64d"\n", nTargetTimespan, nActualTimespan);
 
970
    printf("Before: %08x  %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());
 
971
    printf("After:  %08x  %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());
 
972
 
 
973
    return bnNew.GetCompact();
 
974
}
 
975
 
 
976
bool CheckProofOfWork(uint256 hash, unsigned int nBits)
 
977
{
 
978
    CBigNum bnTarget;
 
979
    bnTarget.SetCompact(nBits);
 
980
 
 
981
    // Check range
 
982
    if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
 
983
        return error("CheckProofOfWork() : nBits below minimum work");
 
984
 
 
985
    // Check proof of work matches claimed amount
 
986
    if (hash > bnTarget.getuint256())
 
987
        return error("CheckProofOfWork() : hash doesn't match nBits");
 
988
 
 
989
    return true;
 
990
}
 
991
 
 
992
bool IsInitialBlockDownload()
 
993
{
 
994
    if (pindexBest == NULL || (!fTestNet && nBestHeight < 74000))
 
995
        return true;
 
996
    static int64 nLastUpdate;
 
997
    static CBlockIndex* pindexLastBest;
 
998
    if (pindexBest != pindexLastBest)
 
999
    {
 
1000
        pindexLastBest = pindexBest;
 
1001
        nLastUpdate = GetTime();
 
1002
    }
 
1003
    return (GetTime() - nLastUpdate < 10 &&
 
1004
            pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
 
1005
}
 
1006
 
 
1007
void InvalidChainFound(CBlockIndex* pindexNew)
 
1008
{
 
1009
    if (pindexNew->bnChainWork > bnBestInvalidWork)
 
1010
    {
 
1011
        bnBestInvalidWork = pindexNew->bnChainWork;
 
1012
        CTxDB().WriteBestInvalidWork(bnBestInvalidWork);
 
1013
        MainFrameRepaint();
 
1014
    }
 
1015
    printf("InvalidChainFound: invalid block=%s  height=%d  work=%s\n", pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight, pindexNew->bnChainWork.ToString().c_str());
 
1016
    printf("InvalidChainFound:  current best=%s  height=%d  work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
 
1017
    if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
 
1018
        printf("InvalidChainFound: WARNING: Displayed transactions may not be correct!  You may need to upgrade, or other nodes may need to upgrade.\n");
 
1019
}
 
1020
 
 
1021
 
 
1022
 
 
1023
 
 
1024
 
 
1025
 
 
1026
 
 
1027
 
 
1028
 
 
1029
 
 
1030
 
 
1031
bool CTransaction::DisconnectInputs(CTxDB& txdb)
 
1032
{
 
1033
    // Relinquish previous transactions' spent pointers
 
1034
    if (!IsCoinBase())
 
1035
    {
 
1036
        foreach(const CTxIn& txin, vin)
 
1037
        {
 
1038
            COutPoint prevout = txin.prevout;
 
1039
 
 
1040
            // Get prev txindex from disk
 
1041
            CTxIndex txindex;
 
1042
            if (!txdb.ReadTxIndex(prevout.hash, txindex))
 
1043
                return error("DisconnectInputs() : ReadTxIndex failed");
 
1044
 
 
1045
            if (prevout.n >= txindex.vSpent.size())
 
1046
                return error("DisconnectInputs() : prevout.n out of range");
 
1047
 
 
1048
            // Mark outpoint as not spent
 
1049
            txindex.vSpent[prevout.n].SetNull();
 
1050
 
 
1051
            // Write back
 
1052
            if (!txdb.UpdateTxIndex(prevout.hash, txindex))
 
1053
                return error("DisconnectInputs() : UpdateTxIndex failed");
 
1054
        }
 
1055
    }
 
1056
 
 
1057
    // Remove transaction from index
 
1058
    if (!txdb.EraseTxIndex(*this))
 
1059
        return error("DisconnectInputs() : EraseTxPos failed");
 
1060
 
 
1061
    return true;
 
1062
}
 
1063
 
 
1064
 
 
1065
bool CTransaction::ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
 
1066
                                 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee)
 
1067
{
 
1068
    // Take over previous transactions' spent pointers
 
1069
    if (!IsCoinBase())
 
1070
    {
 
1071
        int64 nValueIn = 0;
 
1072
        for (int i = 0; i < vin.size(); i++)
 
1073
        {
 
1074
            COutPoint prevout = vin[i].prevout;
 
1075
 
 
1076
            // Read txindex
 
1077
            CTxIndex txindex;
 
1078
            bool fFound = true;
 
1079
            if (fMiner && mapTestPool.count(prevout.hash))
 
1080
            {
 
1081
                // Get txindex from current proposed changes
 
1082
                txindex = mapTestPool[prevout.hash];
 
1083
            }
 
1084
            else
 
1085
            {
 
1086
                // Read txindex from txdb
 
1087
                fFound = txdb.ReadTxIndex(prevout.hash, txindex);
 
1088
            }
 
1089
            if (!fFound && (fBlock || fMiner))
 
1090
                return fMiner ? false : error("ConnectInputs() : %s prev tx %s index entry not found", GetHash().ToString().substr(0,10).c_str(),  prevout.hash.ToString().substr(0,10).c_str());
 
1091
 
 
1092
            // Read txPrev
 
1093
            CTransaction txPrev;
 
1094
            if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
 
1095
            {
 
1096
                // Get prev tx from single transactions in memory
 
1097
                CRITICAL_BLOCK(cs_mapTransactions)
 
1098
                {
 
1099
                    if (!mapTransactions.count(prevout.hash))
 
1100
                        return error("ConnectInputs() : %s mapTransactions prev not found %s", GetHash().ToString().substr(0,10).c_str(),  prevout.hash.ToString().substr(0,10).c_str());
 
1101
                    txPrev = mapTransactions[prevout.hash];
 
1102
                }
 
1103
                if (!fFound)
 
1104
                    txindex.vSpent.resize(txPrev.vout.size());
 
1105
            }
 
1106
            else
 
1107
            {
 
1108
                // Get prev tx from disk
 
1109
                if (!txPrev.ReadFromDisk(txindex.pos))
 
1110
                    return error("ConnectInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(),  prevout.hash.ToString().substr(0,10).c_str());
 
1111
            }
 
1112
 
 
1113
            if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
 
1114
                return error("ConnectInputs() : %s prevout.n out of range %d %d %d prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str());
 
1115
 
 
1116
            // If prev is coinbase, check that it's matured
 
1117
            if (txPrev.IsCoinBase())
 
1118
                for (CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev)
 
1119
                    if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
 
1120
                        return error("ConnectInputs() : tried to spend coinbase at depth %d", pindexBlock->nHeight - pindex->nHeight);
 
1121
 
 
1122
            // Verify signature
 
1123
            if (!VerifySignature(txPrev, *this, i))
 
1124
                return error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
 
1125
 
 
1126
            // Check for conflicts
 
1127
            if (!txindex.vSpent[prevout.n].IsNull())
 
1128
                return fMiner ? false : error("ConnectInputs() : %s prev tx already used at %s", GetHash().ToString().substr(0,10).c_str(), txindex.vSpent[prevout.n].ToString().c_str());
 
1129
 
 
1130
            // Check for negative or overflow input values
 
1131
            nValueIn += txPrev.vout[prevout.n].nValue;
 
1132
            if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
 
1133
                return error("ConnectInputs() : txin values out of range");
 
1134
 
 
1135
            // Mark outpoints as spent
 
1136
            txindex.vSpent[prevout.n] = posThisTx;
 
1137
 
 
1138
            // Write back
 
1139
            if (fBlock)
 
1140
            {
 
1141
                if (!txdb.UpdateTxIndex(prevout.hash, txindex))
 
1142
                    return error("ConnectInputs() : UpdateTxIndex failed");
 
1143
            }
 
1144
            else if (fMiner)
 
1145
            {
 
1146
                mapTestPool[prevout.hash] = txindex;
 
1147
            }
 
1148
        }
 
1149
 
 
1150
        if (nValueIn < GetValueOut())
 
1151
            return error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str());
 
1152
 
 
1153
        // Tally transaction fees
 
1154
        int64 nTxFee = nValueIn - GetValueOut();
 
1155
        if (nTxFee < 0)
 
1156
            return error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str());
 
1157
        if (nTxFee < nMinFee)
 
1158
            return false;
 
1159
        nFees += nTxFee;
 
1160
        if (!MoneyRange(nFees))
 
1161
            return error("ConnectInputs() : nFees out of range");
 
1162
    }
 
1163
 
 
1164
    if (fBlock)
 
1165
    {
 
1166
        // Add transaction to disk index
 
1167
        if (!txdb.AddTxIndex(*this, posThisTx, pindexBlock->nHeight))
 
1168
            return error("ConnectInputs() : AddTxPos failed");
 
1169
    }
 
1170
    else if (fMiner)
 
1171
    {
 
1172
        // Add transaction to test pool
 
1173
        mapTestPool[GetHash()] = CTxIndex(CDiskTxPos(1,1,1), vout.size());
 
1174
    }
 
1175
 
 
1176
    return true;
 
1177
}
 
1178
 
 
1179
 
 
1180
bool CTransaction::ClientConnectInputs()
 
1181
{
 
1182
    if (IsCoinBase())
 
1183
        return false;
 
1184
 
 
1185
    // Take over previous transactions' spent pointers
 
1186
    CRITICAL_BLOCK(cs_mapTransactions)
 
1187
    {
 
1188
        int64 nValueIn = 0;
 
1189
        for (int i = 0; i < vin.size(); i++)
 
1190
        {
 
1191
            // Get prev tx from single transactions in memory
 
1192
            COutPoint prevout = vin[i].prevout;
 
1193
            if (!mapTransactions.count(prevout.hash))
 
1194
                return false;
 
1195
            CTransaction& txPrev = mapTransactions[prevout.hash];
 
1196
 
 
1197
            if (prevout.n >= txPrev.vout.size())
 
1198
                return false;
 
1199
 
 
1200
            // Verify signature
 
1201
            if (!VerifySignature(txPrev, *this, i))
 
1202
                return error("ConnectInputs() : VerifySignature failed");
 
1203
 
 
1204
            ///// this is redundant with the mapNextTx stuff, not sure which I want to get rid of
 
1205
            ///// this has to go away now that posNext is gone
 
1206
            // // Check for conflicts
 
1207
            // if (!txPrev.vout[prevout.n].posNext.IsNull())
 
1208
            //     return error("ConnectInputs() : prev tx already used");
 
1209
            //
 
1210
            // // Flag outpoints as used
 
1211
            // txPrev.vout[prevout.n].posNext = posThisTx;
 
1212
 
 
1213
            nValueIn += txPrev.vout[prevout.n].nValue;
 
1214
 
 
1215
            if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
 
1216
                return error("ClientConnectInputs() : txin values out of range");
 
1217
        }
 
1218
        if (GetValueOut() > nValueIn)
 
1219
            return false;
 
1220
    }
 
1221
 
 
1222
    return true;
 
1223
}
 
1224
 
 
1225
 
 
1226
 
 
1227
 
 
1228
bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
 
1229
{
 
1230
    // Disconnect in reverse order
 
1231
    for (int i = vtx.size()-1; i >= 0; i--)
 
1232
        if (!vtx[i].DisconnectInputs(txdb))
 
1233
            return false;
 
1234
 
 
1235
    // Update block index on disk without changing it in memory.
 
1236
    // The memory index structure will be changed after the db commits.
 
1237
    if (pindex->pprev)
 
1238
    {
 
1239
        CDiskBlockIndex blockindexPrev(pindex->pprev);
 
1240
        blockindexPrev.hashNext = 0;
 
1241
        if (!txdb.WriteBlockIndex(blockindexPrev))
 
1242
            return error("DisconnectBlock() : WriteBlockIndex failed");
 
1243
    }
 
1244
 
 
1245
    return true;
 
1246
}
 
1247
 
 
1248
bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
 
1249
{
 
1250
    // Check it again in case a previous version let a bad block in
 
1251
    if (!CheckBlock())
 
1252
        return false;
 
1253
 
 
1254
    //// issue here: it doesn't know the version
 
1255
    unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK) - 1 + GetSizeOfCompactSize(vtx.size());
 
1256
 
 
1257
    map<uint256, CTxIndex> mapUnused;
 
1258
    int64 nFees = 0;
 
1259
    foreach(CTransaction& tx, vtx)
 
1260
    {
 
1261
        CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
 
1262
        nTxPos += ::GetSerializeSize(tx, SER_DISK);
 
1263
 
 
1264
        if (!tx.ConnectInputs(txdb, mapUnused, posThisTx, pindex, nFees, true, false))
 
1265
            return false;
 
1266
    }
 
1267
 
 
1268
    if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))
 
1269
        return false;
 
1270
 
 
1271
    // Update block index on disk without changing it in memory.
 
1272
    // The memory index structure will be changed after the db commits.
 
1273
    if (pindex->pprev)
 
1274
    {
 
1275
        CDiskBlockIndex blockindexPrev(pindex->pprev);
 
1276
        blockindexPrev.hashNext = pindex->GetBlockHash();
 
1277
        if (!txdb.WriteBlockIndex(blockindexPrev))
 
1278
            return error("ConnectBlock() : WriteBlockIndex failed");
 
1279
    }
 
1280
 
 
1281
    // Watch for transactions paying to me
 
1282
    foreach(CTransaction& tx, vtx)
 
1283
        AddToWalletIfMine(tx, this);
 
1284
 
 
1285
    return true;
 
1286
}
 
1287
 
 
1288
 
 
1289
 
 
1290
bool Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
 
1291
{
 
1292
    printf("REORGANIZE\n");
 
1293
 
 
1294
    // Find the fork
 
1295
    CBlockIndex* pfork = pindexBest;
 
1296
    CBlockIndex* plonger = pindexNew;
 
1297
    while (pfork != plonger)
 
1298
    {
 
1299
        while (plonger->nHeight > pfork->nHeight)
 
1300
            if (!(plonger = plonger->pprev))
 
1301
                return error("Reorganize() : plonger->pprev is null");
 
1302
        if (pfork == plonger)
 
1303
            break;
 
1304
        if (!(pfork = pfork->pprev))
 
1305
            return error("Reorganize() : pfork->pprev is null");
 
1306
    }
 
1307
 
 
1308
    // List of what to disconnect
 
1309
    vector<CBlockIndex*> vDisconnect;
 
1310
    for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
 
1311
        vDisconnect.push_back(pindex);
 
1312
 
 
1313
    // List of what to connect
 
1314
    vector<CBlockIndex*> vConnect;
 
1315
    for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
 
1316
        vConnect.push_back(pindex);
 
1317
    reverse(vConnect.begin(), vConnect.end());
 
1318
 
 
1319
    // Disconnect shorter branch
 
1320
    vector<CTransaction> vResurrect;
 
1321
    foreach(CBlockIndex* pindex, vDisconnect)
 
1322
    {
 
1323
        CBlock block;
 
1324
        if (!block.ReadFromDisk(pindex))
 
1325
            return error("Reorganize() : ReadFromDisk for disconnect failed");
 
1326
        if (!block.DisconnectBlock(txdb, pindex))
 
1327
            return error("Reorganize() : DisconnectBlock failed");
 
1328
 
 
1329
        // Queue memory transactions to resurrect
 
1330
        foreach(const CTransaction& tx, block.vtx)
 
1331
            if (!tx.IsCoinBase())
 
1332
                vResurrect.push_back(tx);
 
1333
    }
 
1334
 
 
1335
    // Connect longer branch
 
1336
    vector<CTransaction> vDelete;
 
1337
    for (int i = 0; i < vConnect.size(); i++)
 
1338
    {
 
1339
        CBlockIndex* pindex = vConnect[i];
 
1340
        CBlock block;
 
1341
        if (!block.ReadFromDisk(pindex))
 
1342
            return error("Reorganize() : ReadFromDisk for connect failed");
 
1343
        if (!block.ConnectBlock(txdb, pindex))
 
1344
        {
 
1345
            // Invalid block
 
1346
            txdb.TxnAbort();
 
1347
            return error("Reorganize() : ConnectBlock failed");
 
1348
        }
 
1349
 
 
1350
        // Queue memory transactions to delete
 
1351
        foreach(const CTransaction& tx, block.vtx)
 
1352
            vDelete.push_back(tx);
 
1353
    }
 
1354
    if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
 
1355
        return error("Reorganize() : WriteHashBestChain failed");
 
1356
 
 
1357
    // Make sure it's successfully written to disk before changing memory structure
 
1358
    if (!txdb.TxnCommit())
 
1359
        return error("Reorganize() : TxnCommit failed");
 
1360
 
 
1361
    // Disconnect shorter branch
 
1362
    foreach(CBlockIndex* pindex, vDisconnect)
 
1363
        if (pindex->pprev)
 
1364
            pindex->pprev->pnext = NULL;
 
1365
 
 
1366
    // Connect longer branch
 
1367
    foreach(CBlockIndex* pindex, vConnect)
 
1368
        if (pindex->pprev)
 
1369
            pindex->pprev->pnext = pindex;
 
1370
 
 
1371
    // Resurrect memory transactions that were in the disconnected branch
 
1372
    foreach(CTransaction& tx, vResurrect)
 
1373
        tx.AcceptToMemoryPool(txdb, false);
 
1374
 
 
1375
    // Delete redundant memory transactions that are in the connected branch
 
1376
    foreach(CTransaction& tx, vDelete)
 
1377
        tx.RemoveFromMemoryPool();
 
1378
 
 
1379
    return true;
 
1380
}
 
1381
 
 
1382
 
 
1383
bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
 
1384
{
 
1385
    uint256 hash = GetHash();
 
1386
 
 
1387
    txdb.TxnBegin();
 
1388
    if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)
 
1389
    {
 
1390
        txdb.WriteHashBestChain(hash);
 
1391
        if (!txdb.TxnCommit())
 
1392
            return error("SetBestChain() : TxnCommit failed");
 
1393
        pindexGenesisBlock = pindexNew;
 
1394
    }
 
1395
    else if (hashPrevBlock == hashBestChain)
 
1396
    {
 
1397
        // Adding to current best branch
 
1398
        if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
 
1399
        {
 
1400
            txdb.TxnAbort();
 
1401
            InvalidChainFound(pindexNew);
 
1402
            return error("SetBestChain() : ConnectBlock failed");
 
1403
        }
 
1404
        if (!txdb.TxnCommit())
 
1405
            return error("SetBestChain() : TxnCommit failed");
 
1406
 
 
1407
        // Add to current best branch
 
1408
        pindexNew->pprev->pnext = pindexNew;
 
1409
 
 
1410
        // Delete redundant memory transactions
 
1411
        foreach(CTransaction& tx, vtx)
 
1412
            tx.RemoveFromMemoryPool();
 
1413
    }
 
1414
    else
 
1415
    {
 
1416
        // New best branch
 
1417
        if (!Reorganize(txdb, pindexNew))
 
1418
        {
 
1419
            txdb.TxnAbort();
 
1420
            InvalidChainFound(pindexNew);
 
1421
            return error("SetBestChain() : Reorganize failed");
 
1422
        }
 
1423
    }
 
1424
 
 
1425
    // New best block
 
1426
    hashBestChain = hash;
 
1427
    pindexBest = pindexNew;
 
1428
    nBestHeight = pindexBest->nHeight;
 
1429
    bnBestChainWork = pindexNew->bnChainWork;
 
1430
    nTimeBestReceived = GetTime();
 
1431
    nTransactionsUpdated++;
 
1432
    printf("SetBestChain: new best=%s  height=%d  work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
 
1433
 
 
1434
    return true;
 
1435
}
 
1436
 
 
1437
 
 
1438
bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
 
1439
{
 
1440
    // Check for duplicate
 
1441
    uint256 hash = GetHash();
 
1442
    if (mapBlockIndex.count(hash))
 
1443
        return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
 
1444
 
 
1445
    // Construct new block index object
 
1446
    CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
 
1447
    if (!pindexNew)
 
1448
        return error("AddToBlockIndex() : new CBlockIndex failed");
 
1449
    map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
 
1450
    pindexNew->phashBlock = &((*mi).first);
 
1451
    map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
 
1452
    if (miPrev != mapBlockIndex.end())
 
1453
    {
 
1454
        pindexNew->pprev = (*miPrev).second;
 
1455
        pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
 
1456
    }
 
1457
    pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork();
 
1458
 
 
1459
    CTxDB txdb;
 
1460
    txdb.TxnBegin();
 
1461
    txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
 
1462
    if (!txdb.TxnCommit())
 
1463
        return false;
 
1464
 
 
1465
    // New best
 
1466
    if (pindexNew->bnChainWork > bnBestChainWork)
 
1467
        if (!SetBestChain(txdb, pindexNew))
 
1468
            return false;
 
1469
 
 
1470
    txdb.Close();
 
1471
 
 
1472
    if (pindexNew == pindexBest)
 
1473
    {
 
1474
        // Notify UI to display prev block's coinbase if it was ours
 
1475
        static uint256 hashPrevBestCoinBase;
 
1476
        CRITICAL_BLOCK(cs_mapWallet)
 
1477
            vWalletUpdated.push_back(hashPrevBestCoinBase);
 
1478
        hashPrevBestCoinBase = vtx[0].GetHash();
 
1479
    }
 
1480
 
 
1481
    MainFrameRepaint();
 
1482
    return true;
 
1483
}
 
1484
 
 
1485
 
 
1486
 
 
1487
 
 
1488
bool CBlock::CheckBlock() const
 
1489
{
 
1490
    // These are checks that are independent of context
 
1491
    // that can be verified before saving an orphan block.
 
1492
 
 
1493
    // Size limits
 
1494
    if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
 
1495
        return error("CheckBlock() : size limits failed");
 
1496
 
 
1497
    // Check proof of work matches claimed amount
 
1498
    if (!CheckProofOfWork(GetHash(), nBits))
 
1499
        return error("CheckBlock() : proof of work failed");
 
1500
 
 
1501
    // Check timestamp
 
1502
    if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
 
1503
        return error("CheckBlock() : block timestamp too far in the future");
 
1504
 
 
1505
    // First transaction must be coinbase, the rest must not be
 
1506
    if (vtx.empty() || !vtx[0].IsCoinBase())
 
1507
        return error("CheckBlock() : first tx is not coinbase");
 
1508
    for (int i = 1; i < vtx.size(); i++)
 
1509
        if (vtx[i].IsCoinBase())
 
1510
            return error("CheckBlock() : more than one coinbase");
 
1511
 
 
1512
    // Check transactions
 
1513
    foreach(const CTransaction& tx, vtx)
 
1514
        if (!tx.CheckTransaction())
 
1515
            return error("CheckBlock() : CheckTransaction failed");
 
1516
 
 
1517
    // Check that it's not full of nonstandard transactions
 
1518
    if (GetSigOpCount() > MAX_BLOCK_SIGOPS)
 
1519
        return error("CheckBlock() : too many nonstandard transactions");
 
1520
 
 
1521
    // Check merkleroot
 
1522
    if (hashMerkleRoot != BuildMerkleTree())
 
1523
        return error("CheckBlock() : hashMerkleRoot mismatch");
 
1524
 
 
1525
    return true;
 
1526
}
 
1527
 
 
1528
bool CBlock::AcceptBlock()
 
1529
{
 
1530
    // Check for duplicate
 
1531
    uint256 hash = GetHash();
 
1532
    if (mapBlockIndex.count(hash))
 
1533
        return error("AcceptBlock() : block already in mapBlockIndex");
 
1534
 
 
1535
    // Get prev block index
 
1536
    map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
 
1537
    if (mi == mapBlockIndex.end())
 
1538
        return error("AcceptBlock() : prev block not found");
 
1539
    CBlockIndex* pindexPrev = (*mi).second;
 
1540
    int nHeight = pindexPrev->nHeight+1;
 
1541
 
 
1542
    // Check proof of work
 
1543
    if (nBits != GetNextWorkRequired(pindexPrev))
 
1544
        return error("AcceptBlock() : incorrect proof of work");
 
1545
 
 
1546
    // Check timestamp against prev
 
1547
    if (GetBlockTime() <= pindexPrev->GetMedianTimePast())
 
1548
        return error("AcceptBlock() : block's timestamp is too early");
 
1549
 
 
1550
    // Check that all transactions are finalized
 
1551
    foreach(const CTransaction& tx, vtx)
 
1552
        if (!tx.IsFinal(nHeight, GetBlockTime()))
 
1553
            return error("AcceptBlock() : contains a non-final transaction");
 
1554
 
 
1555
    // Check that the block chain matches the known block chain up to a checkpoint
 
1556
    if (!fTestNet)
 
1557
        if ((nHeight == 11111 && hash != uint256("0x0000000069e244f73d78e8fd29ba2fd2ed618bd6fa2ee92559f542fdb26e7c1d")) ||
 
1558
            (nHeight == 33333 && hash != uint256("0x000000002dd5588a74784eaa7ab0507a18ad16a236e7b1ce69f00d7ddfb5d0a6")) ||
 
1559
            (nHeight == 68555 && hash != uint256("0x00000000001e1b4903550a0b96e9a9405c8a95f387162e4944e8d9fbe501cd6a")) ||
 
1560
            (nHeight == 70567 && hash != uint256("0x00000000006a49b14bcf27462068f1264c961f11fa2e0eddd2be0791e1d4124a")) ||
 
1561
            (nHeight == 74000 && hash != uint256("0x0000000000573993a3c9e41ce34471c079dcf5f52a0e824a81e7f953b8661a20")))
 
1562
            return error("AcceptBlock() : rejected by checkpoint lockin at %d", nHeight);
 
1563
 
 
1564
    // Write block to history file
 
1565
    if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK)))
 
1566
        return error("AcceptBlock() : out of disk space");
 
1567
    unsigned int nFile = -1;
 
1568
    unsigned int nBlockPos = 0;
 
1569
    if (!WriteToDisk(nFile, nBlockPos))
 
1570
        return error("AcceptBlock() : WriteToDisk failed");
 
1571
    if (!AddToBlockIndex(nFile, nBlockPos))
 
1572
        return error("AcceptBlock() : AddToBlockIndex failed");
 
1573
 
 
1574
    // Relay inventory, but don't relay old inventory during initial block download
 
1575
    if (hashBestChain == hash)
 
1576
        CRITICAL_BLOCK(cs_vNodes)
 
1577
            foreach(CNode* pnode, vNodes)
 
1578
                if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 55000))
 
1579
                    pnode->PushInventory(CInv(MSG_BLOCK, hash));
 
1580
 
 
1581
    return true;
 
1582
}
 
1583
 
 
1584
bool ProcessBlock(CNode* pfrom, CBlock* pblock)
 
1585
{
 
1586
    // Check for duplicate
 
1587
    uint256 hash = pblock->GetHash();
 
1588
    if (mapBlockIndex.count(hash))
 
1589
        return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
 
1590
    if (mapOrphanBlocks.count(hash))
 
1591
        return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
 
1592
 
 
1593
    // Preliminary checks
 
1594
    if (!pblock->CheckBlock())
 
1595
        return error("ProcessBlock() : CheckBlock FAILED");
 
1596
 
 
1597
    // If don't already have its previous block, shunt it off to holding area until we get it
 
1598
    if (!mapBlockIndex.count(pblock->hashPrevBlock))
 
1599
    {
 
1600
        printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
 
1601
        CBlock* pblock2 = new CBlock(*pblock);
 
1602
        mapOrphanBlocks.insert(make_pair(hash, pblock2));
 
1603
        mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
 
1604
 
 
1605
        // Ask this guy to fill in what we're missing
 
1606
        if (pfrom)
 
1607
            pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
 
1608
        return true;
 
1609
    }
 
1610
 
 
1611
    // Store to disk
 
1612
    if (!pblock->AcceptBlock())
 
1613
        return error("ProcessBlock() : AcceptBlock FAILED");
 
1614
 
 
1615
    // Recursively process any orphan blocks that depended on this one
 
1616
    vector<uint256> vWorkQueue;
 
1617
    vWorkQueue.push_back(hash);
 
1618
    for (int i = 0; i < vWorkQueue.size(); i++)
 
1619
    {
 
1620
        uint256 hashPrev = vWorkQueue[i];
 
1621
        for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
 
1622
             mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
 
1623
             ++mi)
 
1624
        {
 
1625
            CBlock* pblockOrphan = (*mi).second;
 
1626
            if (pblockOrphan->AcceptBlock())
 
1627
                vWorkQueue.push_back(pblockOrphan->GetHash());
 
1628
            mapOrphanBlocks.erase(pblockOrphan->GetHash());
 
1629
            delete pblockOrphan;
 
1630
        }
 
1631
        mapOrphanBlocksByPrev.erase(hashPrev);
 
1632
    }
 
1633
 
 
1634
    printf("ProcessBlock: ACCEPTED\n");
 
1635
    return true;
 
1636
}
 
1637
 
 
1638
 
 
1639
 
 
1640
 
 
1641
 
 
1642
 
 
1643
 
 
1644
 
 
1645
template<typename Stream>
 
1646
bool ScanMessageStart(Stream& s)
 
1647
{
 
1648
    // Scan ahead to the next pchMessageStart, which should normally be immediately
 
1649
    // at the file pointer.  Leaves file pointer at end of pchMessageStart.
 
1650
    s.clear(0);
 
1651
    short prevmask = s.exceptions(0);
 
1652
    const char* p = BEGIN(pchMessageStart);
 
1653
    try
 
1654
    {
 
1655
        loop
 
1656
        {
 
1657
            char c;
 
1658
            s.read(&c, 1);
 
1659
            if (s.fail())
 
1660
            {
 
1661
                s.clear(0);
 
1662
                s.exceptions(prevmask);
 
1663
                return false;
 
1664
            }
 
1665
            if (*p != c)
 
1666
                p = BEGIN(pchMessageStart);
 
1667
            if (*p == c)
 
1668
            {
 
1669
                if (++p == END(pchMessageStart))
 
1670
                {
 
1671
                    s.clear(0);
 
1672
                    s.exceptions(prevmask);
 
1673
                    return true;
 
1674
                }
 
1675
            }
 
1676
        }
 
1677
    }
 
1678
    catch (...)
 
1679
    {
 
1680
        s.clear(0);
 
1681
        s.exceptions(prevmask);
 
1682
        return false;
 
1683
    }
 
1684
}
 
1685
 
 
1686
bool CheckDiskSpace(uint64 nAdditionalBytes)
 
1687
{
 
1688
    uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
 
1689
 
 
1690
    // Check for 15MB because database could create another 10MB log file at any time
 
1691
    if (nFreeBytesAvailable < (uint64)15000000 + nAdditionalBytes)
 
1692
    {
 
1693
        fShutdown = true;
 
1694
        string strMessage = _("Warning: Disk space is low  ");
 
1695
        strMiscWarning = strMessage;
 
1696
        printf("*** %s\n", strMessage.c_str());
 
1697
        ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION);
 
1698
        CreateThread(Shutdown, NULL);
 
1699
        return false;
 
1700
    }
 
1701
    return true;
 
1702
}
 
1703
 
 
1704
FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
 
1705
{
 
1706
    if (nFile == -1)
 
1707
        return NULL;
 
1708
    FILE* file = fopen(strprintf("%s/blk%04d.dat", GetDataDir().c_str(), nFile).c_str(), pszMode);
 
1709
    if (!file)
 
1710
        return NULL;
 
1711
    if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
 
1712
    {
 
1713
        if (fseek(file, nBlockPos, SEEK_SET) != 0)
 
1714
        {
 
1715
            fclose(file);
 
1716
            return NULL;
 
1717
        }
 
1718
    }
 
1719
    return file;
 
1720
}
 
1721
 
 
1722
static unsigned int nCurrentBlockFile = 1;
 
1723
 
 
1724
FILE* AppendBlockFile(unsigned int& nFileRet)
 
1725
{
 
1726
    nFileRet = 0;
 
1727
    loop
 
1728
    {
 
1729
        FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
 
1730
        if (!file)
 
1731
            return NULL;
 
1732
        if (fseek(file, 0, SEEK_END) != 0)
 
1733
            return NULL;
 
1734
        // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
 
1735
        if (ftell(file) < 0x7F000000 - MAX_SIZE)
 
1736
        {
 
1737
            nFileRet = nCurrentBlockFile;
 
1738
            return file;
 
1739
        }
 
1740
        fclose(file);
 
1741
        nCurrentBlockFile++;
 
1742
    }
 
1743
}
 
1744
 
 
1745
bool LoadBlockIndex(bool fAllowNew)
 
1746
{
 
1747
    if (fTestNet)
 
1748
    {
 
1749
        hashGenesisBlock = uint256("0x0000000224b1593e3ff16a0e3b61285bbc393a39f78c8aa48c456142671f7110");
 
1750
        bnProofOfWorkLimit = CBigNum(~uint256(0) >> 28);
 
1751
        pchMessageStart[0] = 0xfa;
 
1752
        pchMessageStart[1] = 0xbf;
 
1753
        pchMessageStart[2] = 0xb5;
 
1754
        pchMessageStart[3] = 0xda;
 
1755
    }
 
1756
 
 
1757
    //
 
1758
    // Load block index
 
1759
    //
 
1760
    CTxDB txdb("cr");
 
1761
    if (!txdb.LoadBlockIndex())
 
1762
        return false;
 
1763
    txdb.Close();
 
1764
 
 
1765
    //
 
1766
    // Init with genesis block
 
1767
    //
 
1768
    if (mapBlockIndex.empty())
 
1769
    {
 
1770
        if (!fAllowNew)
 
1771
            return false;
 
1772
 
 
1773
        // Genesis Block:
 
1774
        // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
 
1775
        //   CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
 
1776
        //     CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
 
1777
        //     CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
 
1778
        //   vMerkleTree: 4a5e1e
 
1779
 
 
1780
        // Genesis block
 
1781
        const char* pszTimestamp = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks";
 
1782
        CTransaction txNew;
 
1783
        txNew.vin.resize(1);
 
1784
        txNew.vout.resize(1);
 
1785
        txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
 
1786
        txNew.vout[0].nValue = 50 * COIN;
 
1787
        txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG;
 
1788
        CBlock block;
 
1789
        block.vtx.push_back(txNew);
 
1790
        block.hashPrevBlock = 0;
 
1791
        block.hashMerkleRoot = block.BuildMerkleTree();
 
1792
        block.nVersion = 1;
 
1793
        block.nTime    = 1231006505;
 
1794
        block.nBits    = 0x1d00ffff;
 
1795
        block.nNonce   = 2083236893;
 
1796
 
 
1797
        if (fTestNet)
 
1798
        {
 
1799
            block.nTime    = 1279232055;
 
1800
            block.nBits    = 0x1d07fff8;
 
1801
            block.nNonce   = 81622180;
 
1802
        }
 
1803
 
 
1804
        //// debug print
 
1805
        printf("%s\n", block.GetHash().ToString().c_str());
 
1806
        printf("%s\n", hashGenesisBlock.ToString().c_str());
 
1807
        printf("%s\n", block.hashMerkleRoot.ToString().c_str());
 
1808
        assert(block.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));
 
1809
        block.print();
 
1810
        assert(block.GetHash() == hashGenesisBlock);
 
1811
 
 
1812
        // Start new block file
 
1813
        unsigned int nFile;
 
1814
        unsigned int nBlockPos;
 
1815
        if (!block.WriteToDisk(nFile, nBlockPos))
 
1816
            return error("LoadBlockIndex() : writing genesis block to disk failed");
 
1817
        if (!block.AddToBlockIndex(nFile, nBlockPos))
 
1818
            return error("LoadBlockIndex() : genesis block not accepted");
 
1819
    }
 
1820
 
 
1821
    return true;
 
1822
}
 
1823
 
 
1824
 
 
1825
 
 
1826
void PrintBlockTree()
 
1827
{
 
1828
    // precompute tree structure
 
1829
    map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
 
1830
    for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
 
1831
    {
 
1832
        CBlockIndex* pindex = (*mi).second;
 
1833
        mapNext[pindex->pprev].push_back(pindex);
 
1834
        // test
 
1835
        //while (rand() % 3 == 0)
 
1836
        //    mapNext[pindex->pprev].push_back(pindex);
 
1837
    }
 
1838
 
 
1839
    vector<pair<int, CBlockIndex*> > vStack;
 
1840
    vStack.push_back(make_pair(0, pindexGenesisBlock));
 
1841
 
 
1842
    int nPrevCol = 0;
 
1843
    while (!vStack.empty())
 
1844
    {
 
1845
        int nCol = vStack.back().first;
 
1846
        CBlockIndex* pindex = vStack.back().second;
 
1847
        vStack.pop_back();
 
1848
 
 
1849
        // print split or gap
 
1850
        if (nCol > nPrevCol)
 
1851
        {
 
1852
            for (int i = 0; i < nCol-1; i++)
 
1853
                printf("| ");
 
1854
            printf("|\\\n");
 
1855
        }
 
1856
        else if (nCol < nPrevCol)
 
1857
        {
 
1858
            for (int i = 0; i < nCol; i++)
 
1859
                printf("| ");
 
1860
            printf("|\n");
 
1861
        }
 
1862
        nPrevCol = nCol;
 
1863
 
 
1864
        // print columns
 
1865
        for (int i = 0; i < nCol; i++)
 
1866
            printf("| ");
 
1867
 
 
1868
        // print item
 
1869
        CBlock block;
 
1870
        block.ReadFromDisk(pindex);
 
1871
        printf("%d (%u,%u) %s  %s  tx %d",
 
1872
            pindex->nHeight,
 
1873
            pindex->nFile,
 
1874
            pindex->nBlockPos,
 
1875
            block.GetHash().ToString().substr(0,20).c_str(),
 
1876
            DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
 
1877
            block.vtx.size());
 
1878
 
 
1879
        CRITICAL_BLOCK(cs_mapWallet)
 
1880
        {
 
1881
            if (mapWallet.count(block.vtx[0].GetHash()))
 
1882
            {
 
1883
                CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
 
1884
                printf("    mine:  %d  %d  %d", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
 
1885
            }
 
1886
        }
 
1887
        printf("\n");
 
1888
 
 
1889
 
 
1890
        // put the main timechain first
 
1891
        vector<CBlockIndex*>& vNext = mapNext[pindex];
 
1892
        for (int i = 0; i < vNext.size(); i++)
 
1893
        {
 
1894
            if (vNext[i]->pnext)
 
1895
            {
 
1896
                swap(vNext[0], vNext[i]);
 
1897
                break;
 
1898
            }
 
1899
        }
 
1900
 
 
1901
        // iterate children
 
1902
        for (int i = 0; i < vNext.size(); i++)
 
1903
            vStack.push_back(make_pair(nCol+i, vNext[i]));
 
1904
    }
 
1905
}
 
1906
 
 
1907
 
 
1908
 
 
1909
 
 
1910
 
 
1911
 
 
1912
 
 
1913
 
 
1914
 
 
1915
 
 
1916
//////////////////////////////////////////////////////////////////////////////
 
1917
//
 
1918
// CAlert
 
1919
//
 
1920
 
 
1921
map<uint256, CAlert> mapAlerts;
 
1922
CCriticalSection cs_mapAlerts;
 
1923
 
 
1924
string GetWarnings(string strFor)
 
1925
{
 
1926
    int nPriority = 0;
 
1927
    string strStatusBar;
 
1928
    string strRPC;
 
1929
    if (GetBoolArg("-testsafemode"))
 
1930
        strRPC = "test";
 
1931
 
 
1932
    // Misc warnings like out of disk space and clock is wrong
 
1933
    if (strMiscWarning != "")
 
1934
    {
 
1935
        nPriority = 1000;
 
1936
        strStatusBar = strMiscWarning;
 
1937
    }
 
1938
 
 
1939
    // Longer invalid proof-of-work chain
 
1940
    if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
 
1941
    {
 
1942
        nPriority = 2000;
 
1943
        strStatusBar = strRPC = "WARNING: Displayed transactions may not be correct!  You may need to upgrade, or other nodes may need to upgrade.";
 
1944
    }
 
1945
 
 
1946
    // Alerts
 
1947
    CRITICAL_BLOCK(cs_mapAlerts)
 
1948
    {
 
1949
        foreach(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
 
1950
        {
 
1951
            const CAlert& alert = item.second;
 
1952
            if (alert.AppliesToMe() && alert.nPriority > nPriority)
 
1953
            {
 
1954
                nPriority = alert.nPriority;
 
1955
                strStatusBar = alert.strStatusBar;
 
1956
            }
 
1957
        }
 
1958
    }
 
1959
 
 
1960
    if (strFor == "statusbar")
 
1961
        return strStatusBar;
 
1962
    else if (strFor == "rpc")
 
1963
        return strRPC;
 
1964
    assert(("GetWarnings() : invalid parameter", false));
 
1965
    return "error";
 
1966
}
 
1967
 
 
1968
bool CAlert::ProcessAlert()
 
1969
{
 
1970
    if (!CheckSignature())
 
1971
        return false;
 
1972
    if (!IsInEffect())
 
1973
        return false;
 
1974
 
 
1975
    CRITICAL_BLOCK(cs_mapAlerts)
 
1976
    {
 
1977
        // Cancel previous alerts
 
1978
        for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)
 
1979
        {
 
1980
            const CAlert& alert = (*mi).second;
 
1981
            if (Cancels(alert))
 
1982
            {
 
1983
                printf("cancelling alert %d\n", alert.nID);
 
1984
                mapAlerts.erase(mi++);
 
1985
            }
 
1986
            else if (!alert.IsInEffect())
 
1987
            {
 
1988
                printf("expiring alert %d\n", alert.nID);
 
1989
                mapAlerts.erase(mi++);
 
1990
            }
 
1991
            else
 
1992
                mi++;
 
1993
        }
 
1994
 
 
1995
        // Check if this alert has been cancelled
 
1996
        foreach(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
 
1997
        {
 
1998
            const CAlert& alert = item.second;
 
1999
            if (alert.Cancels(*this))
 
2000
            {
 
2001
                printf("alert already cancelled by %d\n", alert.nID);
 
2002
                return false;
 
2003
            }
 
2004
        }
 
2005
 
 
2006
        // Add to mapAlerts
 
2007
        mapAlerts.insert(make_pair(GetHash(), *this));
 
2008
    }
 
2009
 
 
2010
    printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe());
 
2011
    MainFrameRepaint();
 
2012
    return true;
 
2013
}
 
2014
 
 
2015
 
 
2016
 
 
2017
 
 
2018
 
 
2019
 
 
2020
 
 
2021
 
 
2022
//////////////////////////////////////////////////////////////////////////////
 
2023
//
 
2024
// Messages
 
2025
//
 
2026
 
 
2027
 
 
2028
bool AlreadyHave(CTxDB& txdb, const CInv& inv)
 
2029
{
 
2030
    switch (inv.type)
 
2031
    {
 
2032
    case MSG_TX:    return mapTransactions.count(inv.hash) || mapOrphanTransactions.count(inv.hash) || txdb.ContainsTx(inv.hash);
 
2033
    case MSG_BLOCK: return mapBlockIndex.count(inv.hash) || mapOrphanBlocks.count(inv.hash);
 
2034
    }
 
2035
    // Don't know what it is, just say we already got one
 
2036
    return true;
 
2037
}
 
2038
 
 
2039
 
 
2040
 
 
2041
 
 
2042
// The message start string is designed to be unlikely to occur in normal data.
 
2043
// The characters are rarely used upper ascii, not valid as UTF-8, and produce
 
2044
// a large 4-byte int at any alignment.
 
2045
char pchMessageStart[4] = { 0xf9, 0xbe, 0xb4, 0xd9 };
 
2046
 
 
2047
 
 
2048
bool ProcessMessages(CNode* pfrom)
 
2049
{
 
2050
    CDataStream& vRecv = pfrom->vRecv;
 
2051
    if (vRecv.empty())
 
2052
        return true;
 
2053
    //if (fDebug)
 
2054
    //    printf("ProcessMessages(%u bytes)\n", vRecv.size());
 
2055
 
 
2056
    //
 
2057
    // Message format
 
2058
    //  (4) message start
 
2059
    //  (12) command
 
2060
    //  (4) size
 
2061
    //  (4) checksum
 
2062
    //  (x) data
 
2063
    //
 
2064
 
 
2065
    loop
 
2066
    {
 
2067
        // Scan for message start
 
2068
        CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
 
2069
        int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
 
2070
        if (vRecv.end() - pstart < nHeaderSize)
 
2071
        {
 
2072
            if (vRecv.size() > nHeaderSize)
 
2073
            {
 
2074
                printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
 
2075
                vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
 
2076
            }
 
2077
            break;
 
2078
        }
 
2079
        if (pstart - vRecv.begin() > 0)
 
2080
            printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());
 
2081
        vRecv.erase(vRecv.begin(), pstart);
 
2082
 
 
2083
        // Read header
 
2084
        vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
 
2085
        CMessageHeader hdr;
 
2086
        vRecv >> hdr;
 
2087
        if (!hdr.IsValid())
 
2088
        {
 
2089
            printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
 
2090
            continue;
 
2091
        }
 
2092
        string strCommand = hdr.GetCommand();
 
2093
 
 
2094
        // Message size
 
2095
        unsigned int nMessageSize = hdr.nMessageSize;
 
2096
        if (nMessageSize > MAX_SIZE)
 
2097
        {
 
2098
            printf("ProcessMessage(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
 
2099
            continue;
 
2100
        }
 
2101
        if (nMessageSize > vRecv.size())
 
2102
        {
 
2103
            // Rewind and wait for rest of message
 
2104
            vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
 
2105
            break;
 
2106
        }
 
2107
 
 
2108
        // Checksum
 
2109
        if (vRecv.GetVersion() >= 209)
 
2110
        {
 
2111
            uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
 
2112
            unsigned int nChecksum = 0;
 
2113
            memcpy(&nChecksum, &hash, sizeof(nChecksum));
 
2114
            if (nChecksum != hdr.nChecksum)
 
2115
            {
 
2116
                printf("ProcessMessage(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
 
2117
                       strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
 
2118
                continue;
 
2119
            }
 
2120
        }
 
2121
 
 
2122
        // Copy message to its own buffer
 
2123
        CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
 
2124
        vRecv.ignore(nMessageSize);
 
2125
 
 
2126
        // Process message
 
2127
        bool fRet = false;
 
2128
        try
 
2129
        {
 
2130
            CRITICAL_BLOCK(cs_main)
 
2131
                fRet = ProcessMessage(pfrom, strCommand, vMsg);
 
2132
            if (fShutdown)
 
2133
                return true;
 
2134
        }
 
2135
        catch (std::ios_base::failure& e)
 
2136
        {
 
2137
            if (strstr(e.what(), "end of data"))
 
2138
            {
 
2139
                // Allow exceptions from underlength message on vRecv
 
2140
                printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught, normally caused by a message being shorter than its stated length\n", strCommand.c_str(), nMessageSize, e.what());
 
2141
            }
 
2142
            else if (strstr(e.what(), "size too large"))
 
2143
            {
 
2144
                // Allow exceptions from overlong size
 
2145
                printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
 
2146
            }
 
2147
            else
 
2148
            {
 
2149
                PrintExceptionContinue(&e, "ProcessMessage()");
 
2150
            }
 
2151
        }
 
2152
        catch (std::exception& e) {
 
2153
            PrintExceptionContinue(&e, "ProcessMessage()");
 
2154
        } catch (...) {
 
2155
            PrintExceptionContinue(NULL, "ProcessMessage()");
 
2156
        }
 
2157
 
 
2158
        if (!fRet)
 
2159
            printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
 
2160
    }
 
2161
 
 
2162
    vRecv.Compact();
 
2163
    return true;
 
2164
}
 
2165
 
 
2166
 
 
2167
 
 
2168
 
 
2169
bool ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
 
2170
{
 
2171
    static map<unsigned int, vector<unsigned char> > mapReuseKey;
 
2172
    RandAddSeedPerfmon();
 
2173
    if (fDebug)
 
2174
        printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
 
2175
    printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size());
 
2176
    if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
 
2177
    {
 
2178
        printf("dropmessagestest DROPPING RECV MESSAGE\n");
 
2179
        return true;
 
2180
    }
 
2181
 
 
2182
 
 
2183
 
 
2184
 
 
2185
 
 
2186
    if (strCommand == "version")
 
2187
    {
 
2188
        // Each connection can only send one version message
 
2189
        if (pfrom->nVersion != 0)
 
2190
            return false;
 
2191
 
 
2192
        int64 nTime;
 
2193
        CAddress addrMe;
 
2194
        CAddress addrFrom;
 
2195
        uint64 nNonce = 1;
 
2196
        vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
 
2197
        if (pfrom->nVersion == 10300)
 
2198
            pfrom->nVersion = 300;
 
2199
        if (pfrom->nVersion >= 106 && !vRecv.empty())
 
2200
            vRecv >> addrFrom >> nNonce;
 
2201
        if (pfrom->nVersion >= 106 && !vRecv.empty())
 
2202
            vRecv >> pfrom->strSubVer;
 
2203
        if (pfrom->nVersion >= 209 && !vRecv.empty())
 
2204
            vRecv >> pfrom->nStartingHeight;
 
2205
 
 
2206
        if (pfrom->nVersion == 0)
 
2207
            return false;
 
2208
 
 
2209
        // Disconnect if we connected to ourself
 
2210
        if (nNonce == nLocalHostNonce && nNonce > 1)
 
2211
        {
 
2212
            printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
 
2213
            pfrom->fDisconnect = true;
 
2214
            return true;
 
2215
        }
 
2216
 
 
2217
        pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
 
2218
 
 
2219
        AddTimeData(pfrom->addr.ip, nTime);
 
2220
 
 
2221
        // Change version
 
2222
        if (pfrom->nVersion >= 209)
 
2223
            pfrom->PushMessage("verack");
 
2224
        pfrom->vSend.SetVersion(min(pfrom->nVersion, VERSION));
 
2225
        if (pfrom->nVersion < 209)
 
2226
            pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
 
2227
 
 
2228
        if (!pfrom->fInbound)
 
2229
        {
 
2230
            // Advertise our address
 
2231
            if (addrLocalHost.IsRoutable() && !fUseProxy)
 
2232
            {
 
2233
                CAddress addr(addrLocalHost);
 
2234
                addr.nTime = GetAdjustedTime();
 
2235
                pfrom->PushAddress(addr);
 
2236
            }
 
2237
 
 
2238
            // Get recent addresses
 
2239
            if (pfrom->nVersion >= 31402 || mapAddresses.size() < 1000)
 
2240
            {
 
2241
                pfrom->PushMessage("getaddr");
 
2242
                pfrom->fGetAddr = true;
 
2243
            }
 
2244
        }
 
2245
 
 
2246
        // Ask the first connected node for block updates
 
2247
        static int nAskedForBlocks;
 
2248
        if (!pfrom->fClient && (nAskedForBlocks < 1 || vNodes.size() <= 1))
 
2249
        {
 
2250
            nAskedForBlocks++;
 
2251
            pfrom->PushGetBlocks(pindexBest, uint256(0));
 
2252
        }
 
2253
 
 
2254
        // Relay alerts
 
2255
        CRITICAL_BLOCK(cs_mapAlerts)
 
2256
            foreach(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
 
2257
                item.second.RelayTo(pfrom);
 
2258
 
 
2259
        pfrom->fSuccessfullyConnected = true;
 
2260
 
 
2261
        printf("version message: version %d, blocks=%d\n", pfrom->nVersion, pfrom->nStartingHeight);
 
2262
    }
 
2263
 
 
2264
 
 
2265
    else if (pfrom->nVersion == 0)
 
2266
    {
 
2267
        // Must have a version message before anything else
 
2268
        return false;
 
2269
    }
 
2270
 
 
2271
 
 
2272
    else if (strCommand == "verack")
 
2273
    {
 
2274
        pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
 
2275
    }
 
2276
 
 
2277
 
 
2278
    else if (strCommand == "addr")
 
2279
    {
 
2280
        vector<CAddress> vAddr;
 
2281
        vRecv >> vAddr;
 
2282
 
 
2283
        // Don't want addr from older versions unless seeding
 
2284
        if (pfrom->nVersion < 209)
 
2285
            return true;
 
2286
        if (pfrom->nVersion < 31402 && mapAddresses.size() > 1000)
 
2287
            return true;
 
2288
        if (vAddr.size() > 1000)
 
2289
            return error("message addr size() = %d", vAddr.size());
 
2290
 
 
2291
        // Store the new addresses
 
2292
        int64 nNow = GetAdjustedTime();
 
2293
        int64 nSince = nNow - 10 * 60;
 
2294
        foreach(CAddress& addr, vAddr)
 
2295
        {
 
2296
            if (fShutdown)
 
2297
                return true;
 
2298
            // ignore IPv6 for now, since it isn't implemented anyway
 
2299
            if (!addr.IsIPv4())
 
2300
                continue;
 
2301
            if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
 
2302
                addr.nTime = nNow - 5 * 24 * 60 * 60;
 
2303
            AddAddress(addr, 2 * 60 * 60);
 
2304
            pfrom->AddAddressKnown(addr);
 
2305
            if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
 
2306
            {
 
2307
                // Relay to a limited number of other nodes
 
2308
                CRITICAL_BLOCK(cs_vNodes)
 
2309
                {
 
2310
                    // Use deterministic randomness to send to the same nodes for 24 hours
 
2311
                    // at a time so the setAddrKnowns of the chosen nodes prevent repeats
 
2312
                    static uint256 hashSalt;
 
2313
                    if (hashSalt == 0)
 
2314
                        RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
 
2315
                    uint256 hashRand = hashSalt ^ (((int64)addr.ip)<<32) ^ ((GetTime()+addr.ip)/(24*60*60));
 
2316
                    hashRand = Hash(BEGIN(hashRand), END(hashRand));
 
2317
                    multimap<uint256, CNode*> mapMix;
 
2318
                    foreach(CNode* pnode, vNodes)
 
2319
                    {
 
2320
                        if (pnode->nVersion < 31402)
 
2321
                            continue;
 
2322
                        unsigned int nPointer;
 
2323
                        memcpy(&nPointer, &pnode, sizeof(nPointer));
 
2324
                        uint256 hashKey = hashRand ^ nPointer;
 
2325
                        hashKey = Hash(BEGIN(hashKey), END(hashKey));
 
2326
                        mapMix.insert(make_pair(hashKey, pnode));
 
2327
                    }
 
2328
                    int nRelayNodes = 2;
 
2329
                    for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
 
2330
                        ((*mi).second)->PushAddress(addr);
 
2331
                }
 
2332
            }
 
2333
        }
 
2334
        if (vAddr.size() < 1000)
 
2335
            pfrom->fGetAddr = false;
 
2336
    }
 
2337
 
 
2338
 
 
2339
    else if (strCommand == "inv")
 
2340
    {
 
2341
        vector<CInv> vInv;
 
2342
        vRecv >> vInv;
 
2343
        if (vInv.size() > 50000)
 
2344
            return error("message inv size() = %d", vInv.size());
 
2345
 
 
2346
        CTxDB txdb("r");
 
2347
        foreach(const CInv& inv, vInv)
 
2348
        {
 
2349
            if (fShutdown)
 
2350
                return true;
 
2351
            pfrom->AddInventoryKnown(inv);
 
2352
 
 
2353
            bool fAlreadyHave = AlreadyHave(txdb, inv);
 
2354
            printf("  got inventory: %s  %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
 
2355
 
 
2356
            if (!fAlreadyHave)
 
2357
                pfrom->AskFor(inv);
 
2358
            else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash))
 
2359
                pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
 
2360
 
 
2361
            // Track requests for our stuff
 
2362
            CRITICAL_BLOCK(cs_mapRequestCount)
 
2363
            {
 
2364
                map<uint256, int>::iterator mi = mapRequestCount.find(inv.hash);
 
2365
                if (mi != mapRequestCount.end())
 
2366
                    (*mi).second++;
 
2367
            }
 
2368
        }
 
2369
    }
 
2370
 
 
2371
 
 
2372
    else if (strCommand == "getdata")
 
2373
    {
 
2374
        vector<CInv> vInv;
 
2375
        vRecv >> vInv;
 
2376
        if (vInv.size() > 50000)
 
2377
            return error("message getdata size() = %d", vInv.size());
 
2378
 
 
2379
        foreach(const CInv& inv, vInv)
 
2380
        {
 
2381
            if (fShutdown)
 
2382
                return true;
 
2383
            printf("received getdata for: %s\n", inv.ToString().c_str());
 
2384
 
 
2385
            if (inv.type == MSG_BLOCK)
 
2386
            {
 
2387
                // Send block from disk
 
2388
                map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
 
2389
                if (mi != mapBlockIndex.end())
 
2390
                {
 
2391
                    CBlock block;
 
2392
                    block.ReadFromDisk((*mi).second);
 
2393
                    pfrom->PushMessage("block", block);
 
2394
 
 
2395
                    // Trigger them to send a getblocks request for the next batch of inventory
 
2396
                    if (inv.hash == pfrom->hashContinue)
 
2397
                    {
 
2398
                        // Bypass PushInventory, this must send even if redundant,
 
2399
                        // and we want it right after the last block so they don't
 
2400
                        // wait for other stuff first.
 
2401
                        vector<CInv> vInv;
 
2402
                        vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
 
2403
                        pfrom->PushMessage("inv", vInv);
 
2404
                        pfrom->hashContinue = 0;
 
2405
                    }
 
2406
                }
 
2407
            }
 
2408
            else if (inv.IsKnownType())
 
2409
            {
 
2410
                // Send stream from relay memory
 
2411
                CRITICAL_BLOCK(cs_mapRelay)
 
2412
                {
 
2413
                    map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
 
2414
                    if (mi != mapRelay.end())
 
2415
                        pfrom->PushMessage(inv.GetCommand(), (*mi).second);
 
2416
                }
 
2417
            }
 
2418
 
 
2419
            // Track requests for our stuff
 
2420
            CRITICAL_BLOCK(cs_mapRequestCount)
 
2421
            {
 
2422
                map<uint256, int>::iterator mi = mapRequestCount.find(inv.hash);
 
2423
                if (mi != mapRequestCount.end())
 
2424
                    (*mi).second++;
 
2425
            }
 
2426
        }
 
2427
    }
 
2428
 
 
2429
 
 
2430
    else if (strCommand == "getblocks")
 
2431
    {
 
2432
        CBlockLocator locator;
 
2433
        uint256 hashStop;
 
2434
        vRecv >> locator >> hashStop;
 
2435
 
 
2436
        // Find the last block the caller has in the main chain
 
2437
        CBlockIndex* pindex = locator.GetBlockIndex();
 
2438
 
 
2439
        // Send the rest of the chain
 
2440
        if (pindex)
 
2441
            pindex = pindex->pnext;
 
2442
        int nLimit = 500 + locator.GetDistanceBack();
 
2443
        printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
 
2444
        for (; pindex; pindex = pindex->pnext)
 
2445
        {
 
2446
            if (pindex->GetBlockHash() == hashStop)
 
2447
            {
 
2448
                printf("  getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
 
2449
                break;
 
2450
            }
 
2451
            pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
 
2452
            if (--nLimit <= 0)
 
2453
            {
 
2454
                // When this block is requested, we'll send an inv that'll make them
 
2455
                // getblocks the next batch of inventory.
 
2456
                printf("  getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
 
2457
                pfrom->hashContinue = pindex->GetBlockHash();
 
2458
                break;
 
2459
            }
 
2460
        }
 
2461
    }
 
2462
 
 
2463
 
 
2464
    else if (strCommand == "getheaders")
 
2465
    {
 
2466
        CBlockLocator locator;
 
2467
        uint256 hashStop;
 
2468
        vRecv >> locator >> hashStop;
 
2469
 
 
2470
        CBlockIndex* pindex = NULL;
 
2471
        if (locator.IsNull())
 
2472
        {
 
2473
            // If locator is null, return the hashStop block
 
2474
            map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
 
2475
            if (mi == mapBlockIndex.end())
 
2476
                return true;
 
2477
            pindex = (*mi).second;
 
2478
        }
 
2479
        else
 
2480
        {
 
2481
            // Find the last block the caller has in the main chain
 
2482
            pindex = locator.GetBlockIndex();
 
2483
            if (pindex)
 
2484
                pindex = pindex->pnext;
 
2485
        }
 
2486
 
 
2487
        vector<CBlock> vHeaders;
 
2488
        int nLimit = 2000 + locator.GetDistanceBack();
 
2489
        printf("getheaders %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
 
2490
        for (; pindex; pindex = pindex->pnext)
 
2491
        {
 
2492
            vHeaders.push_back(pindex->GetBlockHeader());
 
2493
            if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
 
2494
                break;
 
2495
        }
 
2496
        pfrom->PushMessage("headers", vHeaders);
 
2497
    }
 
2498
 
 
2499
 
 
2500
    else if (strCommand == "tx")
 
2501
    {
 
2502
        vector<uint256> vWorkQueue;
 
2503
        CDataStream vMsg(vRecv);
 
2504
        CTransaction tx;
 
2505
        vRecv >> tx;
 
2506
 
 
2507
        CInv inv(MSG_TX, tx.GetHash());
 
2508
        pfrom->AddInventoryKnown(inv);
 
2509
 
 
2510
        bool fMissingInputs = false;
 
2511
        if (tx.AcceptToMemoryPool(true, &fMissingInputs))
 
2512
        {
 
2513
            AddToWalletIfMine(tx, NULL);
 
2514
            RelayMessage(inv, vMsg);
 
2515
            mapAlreadyAskedFor.erase(inv);
 
2516
            vWorkQueue.push_back(inv.hash);
 
2517
 
 
2518
            // Recursively process any orphan transactions that depended on this one
 
2519
            for (int i = 0; i < vWorkQueue.size(); i++)
 
2520
            {
 
2521
                uint256 hashPrev = vWorkQueue[i];
 
2522
                for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(hashPrev);
 
2523
                     mi != mapOrphanTransactionsByPrev.upper_bound(hashPrev);
 
2524
                     ++mi)
 
2525
                {
 
2526
                    const CDataStream& vMsg = *((*mi).second);
 
2527
                    CTransaction tx;
 
2528
                    CDataStream(vMsg) >> tx;
 
2529
                    CInv inv(MSG_TX, tx.GetHash());
 
2530
 
 
2531
                    if (tx.AcceptToMemoryPool(true))
 
2532
                    {
 
2533
                        printf("   accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
 
2534
                        AddToWalletIfMine(tx, NULL);
 
2535
                        RelayMessage(inv, vMsg);
 
2536
                        mapAlreadyAskedFor.erase(inv);
 
2537
                        vWorkQueue.push_back(inv.hash);
 
2538
                    }
 
2539
                }
 
2540
            }
 
2541
 
 
2542
            foreach(uint256 hash, vWorkQueue)
 
2543
                EraseOrphanTx(hash);
 
2544
        }
 
2545
        else if (fMissingInputs)
 
2546
        {
 
2547
            printf("storing orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
 
2548
            AddOrphanTx(vMsg);
 
2549
        }
 
2550
    }
 
2551
 
 
2552
 
 
2553
    else if (strCommand == "block")
 
2554
    {
 
2555
        CBlock block;
 
2556
        vRecv >> block;
 
2557
 
 
2558
        printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str());
 
2559
        // block.print();
 
2560
 
 
2561
        CInv inv(MSG_BLOCK, block.GetHash());
 
2562
        pfrom->AddInventoryKnown(inv);
 
2563
 
 
2564
        if (ProcessBlock(pfrom, &block))
 
2565
            mapAlreadyAskedFor.erase(inv);
 
2566
    }
 
2567
 
 
2568
 
 
2569
    else if (strCommand == "getaddr")
 
2570
    {
 
2571
        // Nodes rebroadcast an addr every 24 hours
 
2572
        pfrom->vAddrToSend.clear();
 
2573
        int64 nSince = GetAdjustedTime() - 3 * 60 * 60; // in the last 3 hours
 
2574
        CRITICAL_BLOCK(cs_mapAddresses)
 
2575
        {
 
2576
            unsigned int nCount = 0;
 
2577
            foreach(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
 
2578
            {
 
2579
                const CAddress& addr = item.second;
 
2580
                if (addr.nTime > nSince)
 
2581
                    nCount++;
 
2582
            }
 
2583
            foreach(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
 
2584
            {
 
2585
                const CAddress& addr = item.second;
 
2586
                if (addr.nTime > nSince && GetRand(nCount) < 2500)
 
2587
                    pfrom->PushAddress(addr);
 
2588
            }
 
2589
        }
 
2590
    }
 
2591
 
 
2592
 
 
2593
    else if (strCommand == "checkorder")
 
2594
    {
 
2595
        uint256 hashReply;
 
2596
        vRecv >> hashReply;
 
2597
 
 
2598
        if (!GetBoolArg("-allowreceivebyip"))
 
2599
        {
 
2600
            pfrom->PushMessage("reply", hashReply, (int)2, string(""));
 
2601
            return true;
 
2602
        }
 
2603
 
 
2604
        CWalletTx order;
 
2605
        vRecv >> order;
 
2606
 
 
2607
        /// we have a chance to check the order here
 
2608
 
 
2609
        // Keep giving the same key to the same ip until they use it
 
2610
        if (!mapReuseKey.count(pfrom->addr.ip))
 
2611
            mapReuseKey[pfrom->addr.ip] = GetKeyFromKeyPool();
 
2612
 
 
2613
        // Send back approval of order and pubkey to use
 
2614
        CScript scriptPubKey;
 
2615
        scriptPubKey << mapReuseKey[pfrom->addr.ip] << OP_CHECKSIG;
 
2616
        pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
 
2617
    }
 
2618
 
 
2619
 
 
2620
    else if (strCommand == "submitorder")
 
2621
    {
 
2622
        uint256 hashReply;
 
2623
        vRecv >> hashReply;
 
2624
 
 
2625
        if (!GetBoolArg("-allowreceivebyip"))
 
2626
        {
 
2627
            pfrom->PushMessage("reply", hashReply, (int)2);
 
2628
            return true;
 
2629
        }
 
2630
 
 
2631
        CWalletTx wtxNew;
 
2632
        vRecv >> wtxNew;
 
2633
        wtxNew.fFromMe = false;
 
2634
 
 
2635
        // Broadcast
 
2636
        if (!wtxNew.AcceptWalletTransaction())
 
2637
        {
 
2638
            pfrom->PushMessage("reply", hashReply, (int)1);
 
2639
            return error("submitorder AcceptWalletTransaction() failed, returning error 1");
 
2640
        }
 
2641
        wtxNew.fTimeReceivedIsTxTime = true;
 
2642
        AddToWallet(wtxNew);
 
2643
        wtxNew.RelayWalletTransaction();
 
2644
        mapReuseKey.erase(pfrom->addr.ip);
 
2645
 
 
2646
        // Send back confirmation
 
2647
        pfrom->PushMessage("reply", hashReply, (int)0);
 
2648
    }
 
2649
 
 
2650
 
 
2651
    else if (strCommand == "reply")
 
2652
    {
 
2653
        uint256 hashReply;
 
2654
        vRecv >> hashReply;
 
2655
 
 
2656
        CRequestTracker tracker;
 
2657
        CRITICAL_BLOCK(pfrom->cs_mapRequests)
 
2658
        {
 
2659
            map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
 
2660
            if (mi != pfrom->mapRequests.end())
 
2661
            {
 
2662
                tracker = (*mi).second;
 
2663
                pfrom->mapRequests.erase(mi);
 
2664
            }
 
2665
        }
 
2666
        if (!tracker.IsNull())
 
2667
            tracker.fn(tracker.param1, vRecv);
 
2668
    }
 
2669
 
 
2670
 
 
2671
    else if (strCommand == "ping")
 
2672
    {
 
2673
    }
 
2674
 
 
2675
 
 
2676
    else if (strCommand == "alert")
 
2677
    {
 
2678
        CAlert alert;
 
2679
        vRecv >> alert;
 
2680
 
 
2681
        if (alert.ProcessAlert())
 
2682
        {
 
2683
            // Relay
 
2684
            pfrom->setKnown.insert(alert.GetHash());
 
2685
            CRITICAL_BLOCK(cs_vNodes)
 
2686
                foreach(CNode* pnode, vNodes)
 
2687
                    alert.RelayTo(pnode);
 
2688
        }
 
2689
    }
 
2690
 
 
2691
 
 
2692
    else
 
2693
    {
 
2694
        // Ignore unknown commands for extensibility
 
2695
    }
 
2696
 
 
2697
 
 
2698
    // Update the last seen time for this node's address
 
2699
    if (pfrom->fNetworkNode)
 
2700
        if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
 
2701
            AddressCurrentlyConnected(pfrom->addr);
 
2702
 
 
2703
 
 
2704
    return true;
 
2705
}
 
2706
 
 
2707
 
 
2708
 
 
2709
 
 
2710
 
 
2711
 
 
2712
 
 
2713
 
 
2714
 
 
2715
bool SendMessages(CNode* pto, bool fSendTrickle)
 
2716
{
 
2717
    CRITICAL_BLOCK(cs_main)
 
2718
    {
 
2719
        // Don't send anything until we get their version message
 
2720
        if (pto->nVersion == 0)
 
2721
            return true;
 
2722
 
 
2723
        // Keep-alive ping
 
2724
        if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty())
 
2725
            pto->PushMessage("ping");
 
2726
 
 
2727
        // Resend wallet transactions that haven't gotten in a block yet
 
2728
        ResendWalletTransactions();
 
2729
 
 
2730
        // Address refresh broadcast
 
2731
        static int64 nLastRebroadcast;
 
2732
        if (GetTime() - nLastRebroadcast > 24 * 60 * 60)
 
2733
        {
 
2734
            nLastRebroadcast = GetTime();
 
2735
            CRITICAL_BLOCK(cs_vNodes)
 
2736
            {
 
2737
                foreach(CNode* pnode, vNodes)
 
2738
                {
 
2739
                    // Periodically clear setAddrKnown to allow refresh broadcasts
 
2740
                    pnode->setAddrKnown.clear();
 
2741
 
 
2742
                    // Rebroadcast our address
 
2743
                    if (addrLocalHost.IsRoutable() && !fUseProxy)
 
2744
                    {
 
2745
                        CAddress addr(addrLocalHost);
 
2746
                        addr.nTime = GetAdjustedTime();
 
2747
                        pnode->PushAddress(addr);
 
2748
                    }
 
2749
                }
 
2750
            }
 
2751
        }
 
2752
 
 
2753
        // Clear out old addresses periodically so it's not too much work at once
 
2754
        static int64 nLastClear;
 
2755
        if (nLastClear == 0)
 
2756
            nLastClear = GetTime();
 
2757
        if (GetTime() - nLastClear > 10 * 60 && vNodes.size() >= 3)
 
2758
        {
 
2759
            nLastClear = GetTime();
 
2760
            CRITICAL_BLOCK(cs_mapAddresses)
 
2761
            {
 
2762
                CAddrDB addrdb;
 
2763
                int64 nSince = GetAdjustedTime() - 14 * 24 * 60 * 60;
 
2764
                for (map<vector<unsigned char>, CAddress>::iterator mi = mapAddresses.begin();
 
2765
                     mi != mapAddresses.end();)
 
2766
                {
 
2767
                    const CAddress& addr = (*mi).second;
 
2768
                    if (addr.nTime < nSince)
 
2769
                    {
 
2770
                        if (mapAddresses.size() < 1000 || GetTime() > nLastClear + 20)
 
2771
                            break;
 
2772
                        addrdb.EraseAddress(addr);
 
2773
                        mapAddresses.erase(mi++);
 
2774
                    }
 
2775
                    else
 
2776
                        mi++;
 
2777
                }
 
2778
            }
 
2779
        }
 
2780
 
 
2781
 
 
2782
        //
 
2783
        // Message: addr
 
2784
        //
 
2785
        if (fSendTrickle)
 
2786
        {
 
2787
            vector<CAddress> vAddr;
 
2788
            vAddr.reserve(pto->vAddrToSend.size());
 
2789
            foreach(const CAddress& addr, pto->vAddrToSend)
 
2790
            {
 
2791
                // returns true if wasn't already contained in the set
 
2792
                if (pto->setAddrKnown.insert(addr).second)
 
2793
                {
 
2794
                    vAddr.push_back(addr);
 
2795
                    // receiver rejects addr messages larger than 1000
 
2796
                    if (vAddr.size() >= 1000)
 
2797
                    {
 
2798
                        pto->PushMessage("addr", vAddr);
 
2799
                        vAddr.clear();
 
2800
                    }
 
2801
                }
 
2802
            }
 
2803
            pto->vAddrToSend.clear();
 
2804
            if (!vAddr.empty())
 
2805
                pto->PushMessage("addr", vAddr);
 
2806
        }
 
2807
 
 
2808
 
 
2809
        //
 
2810
        // Message: inventory
 
2811
        //
 
2812
        vector<CInv> vInv;
 
2813
        vector<CInv> vInvWait;
 
2814
        CRITICAL_BLOCK(pto->cs_inventory)
 
2815
        {
 
2816
            vInv.reserve(pto->vInventoryToSend.size());
 
2817
            vInvWait.reserve(pto->vInventoryToSend.size());
 
2818
            foreach(const CInv& inv, pto->vInventoryToSend)
 
2819
            {
 
2820
                if (pto->setInventoryKnown.count(inv))
 
2821
                    continue;
 
2822
 
 
2823
                // trickle out tx inv to protect privacy
 
2824
                if (inv.type == MSG_TX && !fSendTrickle)
 
2825
                {
 
2826
                    // 1/4 of tx invs blast to all immediately
 
2827
                    static uint256 hashSalt;
 
2828
                    if (hashSalt == 0)
 
2829
                        RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
 
2830
                    uint256 hashRand = inv.hash ^ hashSalt;
 
2831
                    hashRand = Hash(BEGIN(hashRand), END(hashRand));
 
2832
                    bool fTrickleWait = ((hashRand & 3) != 0);
 
2833
 
 
2834
                    // always trickle our own transactions
 
2835
                    if (!fTrickleWait)
 
2836
                    {
 
2837
                        TRY_CRITICAL_BLOCK(cs_mapWallet)
 
2838
                        {
 
2839
                            map<uint256, CWalletTx>::iterator mi = mapWallet.find(inv.hash);
 
2840
                            if (mi != mapWallet.end())
 
2841
                            {
 
2842
                                CWalletTx& wtx = (*mi).second;
 
2843
                                if (wtx.fFromMe)
 
2844
                                    fTrickleWait = true;
 
2845
                            }
 
2846
                        }
 
2847
                    }
 
2848
 
 
2849
                    if (fTrickleWait)
 
2850
                    {
 
2851
                        vInvWait.push_back(inv);
 
2852
                        continue;
 
2853
                    }
 
2854
                }
 
2855
 
 
2856
                // returns true if wasn't already contained in the set
 
2857
                if (pto->setInventoryKnown.insert(inv).second)
 
2858
                {
 
2859
                    vInv.push_back(inv);
 
2860
                    if (vInv.size() >= 1000)
 
2861
                    {
 
2862
                        pto->PushMessage("inv", vInv);
 
2863
                        vInv.clear();
 
2864
                    }
 
2865
                }
 
2866
            }
 
2867
            pto->vInventoryToSend = vInvWait;
 
2868
        }
 
2869
        if (!vInv.empty())
 
2870
            pto->PushMessage("inv", vInv);
 
2871
 
 
2872
 
 
2873
        //
 
2874
        // Message: getdata
 
2875
        //
 
2876
        vector<CInv> vGetData;
 
2877
        int64 nNow = GetTime() * 1000000;
 
2878
        CTxDB txdb("r");
 
2879
        while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
 
2880
        {
 
2881
            const CInv& inv = (*pto->mapAskFor.begin()).second;
 
2882
            if (!AlreadyHave(txdb, inv))
 
2883
            {
 
2884
                printf("sending getdata: %s\n", inv.ToString().c_str());
 
2885
                vGetData.push_back(inv);
 
2886
                if (vGetData.size() >= 1000)
 
2887
                {
 
2888
                    pto->PushMessage("getdata", vGetData);
 
2889
                    vGetData.clear();
 
2890
                }
 
2891
            }
 
2892
            pto->mapAskFor.erase(pto->mapAskFor.begin());
 
2893
        }
 
2894
        if (!vGetData.empty())
 
2895
            pto->PushMessage("getdata", vGetData);
 
2896
 
 
2897
    }
 
2898
    return true;
 
2899
}
 
2900
 
 
2901
 
 
2902
 
 
2903
 
 
2904
 
 
2905
 
 
2906
 
 
2907
 
 
2908
 
 
2909
 
 
2910
 
 
2911
 
 
2912
 
 
2913
 
 
2914
//////////////////////////////////////////////////////////////////////////////
 
2915
//
 
2916
// BitcoinMiner
 
2917
//
 
2918
 
 
2919
void GenerateBitcoins(bool fGenerate)
 
2920
{
 
2921
    if (fGenerateBitcoins != fGenerate)
 
2922
    {
 
2923
        fGenerateBitcoins = fGenerate;
 
2924
        CWalletDB().WriteSetting("fGenerateBitcoins", fGenerateBitcoins);
 
2925
        MainFrameRepaint();
 
2926
    }
 
2927
    if (fGenerateBitcoins)
 
2928
    {
 
2929
        int nProcessors = boost::thread::hardware_concurrency();
 
2930
        printf("%d processors\n", nProcessors);
 
2931
        if (nProcessors < 1)
 
2932
            nProcessors = 1;
 
2933
        if (fLimitProcessors && nProcessors > nLimitProcessors)
 
2934
            nProcessors = nLimitProcessors;
 
2935
        int nAddThreads = nProcessors - vnThreadsRunning[3];
 
2936
        printf("Starting %d BitcoinMiner threads\n", nAddThreads);
 
2937
        for (int i = 0; i < nAddThreads; i++)
 
2938
        {
 
2939
            if (!CreateThread(ThreadBitcoinMiner, NULL))
 
2940
                printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");
 
2941
            Sleep(10);
 
2942
        }
 
2943
    }
 
2944
}
 
2945
 
 
2946
void ThreadBitcoinMiner(void* parg)
 
2947
{
 
2948
    try
 
2949
    {
 
2950
        vnThreadsRunning[3]++;
 
2951
        BitcoinMiner();
 
2952
        vnThreadsRunning[3]--;
 
2953
    }
 
2954
    catch (std::exception& e) {
 
2955
        vnThreadsRunning[3]--;
 
2956
        PrintException(&e, "ThreadBitcoinMiner()");
 
2957
    } catch (...) {
 
2958
        vnThreadsRunning[3]--;
 
2959
        PrintException(NULL, "ThreadBitcoinMiner()");
 
2960
    }
 
2961
    UIThreadCall(boost::bind(CalledSetStatusBar, "", 0));
 
2962
    nHPSTimerStart = 0;
 
2963
    if (vnThreadsRunning[3] == 0)
 
2964
        dHashesPerSec = 0;
 
2965
    printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[3]);
 
2966
}
 
2967
 
 
2968
#if defined(__GNUC__) && defined(CRYPTOPP_X86_ASM_AVAILABLE)
 
2969
void CallCPUID(int in, int& aret, int& cret)
 
2970
{
 
2971
    int a, c;
 
2972
    asm (
 
2973
        "mov %2, %%eax; " // in into eax
 
2974
        "cpuid;"
 
2975
        "mov %%eax, %0;" // eax into a
 
2976
        "mov %%ecx, %1;" // ecx into c
 
2977
        :"=r"(a),"=r"(c) /* output */
 
2978
        :"r"(in) /* input */
 
2979
        :"%eax","%ecx" /* clobbered register */
 
2980
    );
 
2981
    aret = a;
 
2982
    cret = c;
 
2983
}
 
2984
 
 
2985
bool Detect128BitSSE2()
 
2986
{
 
2987
    int a, c, nBrand;
 
2988
    CallCPUID(0, a, nBrand);
 
2989
    bool fIntel = (nBrand == 0x6c65746e); // ntel
 
2990
    bool fAMD = (nBrand == 0x444d4163); // cAMD
 
2991
 
 
2992
    struct
 
2993
    {
 
2994
        unsigned int nStepping : 4;
 
2995
        unsigned int nModel : 4;
 
2996
        unsigned int nFamily : 4;
 
2997
        unsigned int nProcessorType : 2;
 
2998
        unsigned int nUnused : 2;
 
2999
        unsigned int nExtendedModel : 4;
 
3000
        unsigned int nExtendedFamily : 8;
 
3001
    }
 
3002
    cpu;
 
3003
    CallCPUID(1, a, c);
 
3004
    memcpy(&cpu, &a, sizeof(cpu));
 
3005
    int nFamily = cpu.nExtendedFamily + cpu.nFamily;
 
3006
    int nModel = cpu.nExtendedModel*16 + cpu.nModel;
 
3007
 
 
3008
    // We need Intel Nehalem or AMD K10 or better for 128bit SSE2
 
3009
    // Nehalem = i3/i5/i7 and some Xeon
 
3010
    // K10 = Opterons with 4 or more cores, Phenom, Phenom II, Athlon II
 
3011
    //  Intel Core i5  family 6, model 26 or 30
 
3012
    //  Intel Core i7  family 6, model 26 or 30
 
3013
    //  Intel Core i3  family 6, model 37
 
3014
    //  AMD Phenom    family 16, model 10
 
3015
    bool fUseSSE2 = ((fIntel && nFamily * 10000 + nModel >=  60026) ||
 
3016
                     (fAMD   && nFamily * 10000 + nModel >= 160010));
 
3017
 
 
3018
    // AMD reports a lower model number in 64-bit mode
 
3019
    if (fAMD && sizeof(void*) > 4 && nFamily * 10000 + nModel >= 160000)
 
3020
        fUseSSE2 = true;
 
3021
 
 
3022
    static bool fPrinted;
 
3023
    if (!fPrinted)
 
3024
    {
 
3025
        fPrinted = true;
 
3026
        printf("CPUID %08x family %d, model %d, stepping %d, fUseSSE2=%d\n", nBrand, nFamily, nModel, cpu.nStepping, fUseSSE2);
 
3027
    }
 
3028
    return fUseSSE2;
 
3029
}
 
3030
#else
 
3031
bool Detect128BitSSE2() { return false; }
 
3032
#endif
 
3033
 
 
3034
int FormatHashBlocks(void* pbuffer, unsigned int len)
 
3035
{
 
3036
    unsigned char* pdata = (unsigned char*)pbuffer;
 
3037
    unsigned int blocks = 1 + ((len + 8) / 64);
 
3038
    unsigned char* pend = pdata + 64 * blocks;
 
3039
    memset(pdata + len, 0, 64 * blocks - len);
 
3040
    pdata[len] = 0x80;
 
3041
    unsigned int bits = len * 8;
 
3042
    pend[-1] = (bits >> 0) & 0xff;
 
3043
    pend[-2] = (bits >> 8) & 0xff;
 
3044
    pend[-3] = (bits >> 16) & 0xff;
 
3045
    pend[-4] = (bits >> 24) & 0xff;
 
3046
    return blocks;
 
3047
}
 
3048
 
 
3049
using CryptoPP::ByteReverse;
 
3050
 
 
3051
static const unsigned int pSHA256InitState[8] =
 
3052
{0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
 
3053
 
 
3054
inline void SHA256Transform(void* pstate, void* pinput, const void* pinit)
 
3055
{
 
3056
    memcpy(pstate, pinit, 32);
 
3057
    CryptoPP::SHA256::Transform((CryptoPP::word32*)pstate, (CryptoPP::word32*)pinput);
 
3058
}
 
3059
 
 
3060
//
 
3061
// ScanHash scans nonces looking for a hash with at least some zero bits.
 
3062
// It operates on big endian data.  Caller does the byte reversing.
 
3063
// All input buffers are 16-byte aligned.  nNonce is usually preserved
 
3064
// between calls, but periodically or if nNonce is 0xffff0000 or above,
 
3065
// the block is rebuilt and nNonce starts over at zero.
 
3066
//
 
3067
unsigned int ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)
 
3068
{
 
3069
    unsigned int& nNonce = *(unsigned int*)(pdata + 12);
 
3070
    for (;;)
 
3071
    {
 
3072
        // Crypto++ SHA-256
 
3073
        // Hash pdata using pmidstate as the starting state into
 
3074
        // preformatted buffer phash1, then hash phash1 into phash
 
3075
        nNonce++;
 
3076
        SHA256Transform(phash1, pdata, pmidstate);
 
3077
        SHA256Transform(phash, phash1, pSHA256InitState);
 
3078
 
 
3079
        // Return the nonce if the hash has at least some zero bits,
 
3080
        // caller will check if it has enough to reach the target
 
3081
        if (((unsigned short*)phash)[14] == 0)
 
3082
            return nNonce;
 
3083
 
 
3084
        // If nothing found after trying for a while, return -1
 
3085
        if ((nNonce & 0xffff) == 0)
 
3086
        {
 
3087
            nHashesDone = 0xffff+1;
 
3088
            return -1;
 
3089
        }
 
3090
    }
 
3091
}
 
3092
 
 
3093
extern unsigned int ScanHash_4WaySSE2(char* pmidstate, char* pblock, char* phash1, char* phash, unsigned int& nHashesDone);
 
3094
 
 
3095
 
 
3096
 
 
3097
class COrphan
 
3098
{
 
3099
public:
 
3100
    CTransaction* ptx;
 
3101
    set<uint256> setDependsOn;
 
3102
    double dPriority;
 
3103
 
 
3104
    COrphan(CTransaction* ptxIn)
 
3105
    {
 
3106
        ptx = ptxIn;
 
3107
        dPriority = 0;
 
3108
    }
 
3109
 
 
3110
    void print() const
 
3111
    {
 
3112
        printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority);
 
3113
        foreach(uint256 hash, setDependsOn)
 
3114
            printf("   setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
 
3115
    }
 
3116
};
 
3117
 
 
3118
 
 
3119
CBlock* CreateNewBlock(CReserveKey& reservekey)
 
3120
{
 
3121
    CBlockIndex* pindexPrev = pindexBest;
 
3122
 
 
3123
    // Create new block
 
3124
    auto_ptr<CBlock> pblock(new CBlock());
 
3125
    if (!pblock.get())
 
3126
        return NULL;
 
3127
 
 
3128
    // Create coinbase tx
 
3129
    CTransaction txNew;
 
3130
    txNew.vin.resize(1);
 
3131
    txNew.vin[0].prevout.SetNull();
 
3132
    txNew.vout.resize(1);
 
3133
    txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
 
3134
 
 
3135
    // Add our coinbase tx as first transaction
 
3136
    pblock->vtx.push_back(txNew);
 
3137
 
 
3138
    // Collect memory pool transactions into the block
 
3139
    int64 nFees = 0;
 
3140
    CRITICAL_BLOCK(cs_main)
 
3141
    CRITICAL_BLOCK(cs_mapTransactions)
 
3142
    {
 
3143
        CTxDB txdb("r");
 
3144
 
 
3145
        // Priority order to process transactions
 
3146
        list<COrphan> vOrphan; // list memory doesn't move
 
3147
        map<uint256, vector<COrphan*> > mapDependers;
 
3148
        multimap<double, CTransaction*> mapPriority;
 
3149
        for (map<uint256, CTransaction>::iterator mi = mapTransactions.begin(); mi != mapTransactions.end(); ++mi)
 
3150
        {
 
3151
            CTransaction& tx = (*mi).second;
 
3152
            if (tx.IsCoinBase() || !tx.IsFinal())
 
3153
                continue;
 
3154
 
 
3155
            COrphan* porphan = NULL;
 
3156
            double dPriority = 0;
 
3157
            foreach(const CTxIn& txin, tx.vin)
 
3158
            {
 
3159
                // Read prev transaction
 
3160
                CTransaction txPrev;
 
3161
                CTxIndex txindex;
 
3162
                if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
 
3163
                {
 
3164
                    // Has to wait for dependencies
 
3165
                    if (!porphan)
 
3166
                    {
 
3167
                        // Use list for automatic deletion
 
3168
                        vOrphan.push_back(COrphan(&tx));
 
3169
                        porphan = &vOrphan.back();
 
3170
                    }
 
3171
                    mapDependers[txin.prevout.hash].push_back(porphan);
 
3172
                    porphan->setDependsOn.insert(txin.prevout.hash);
 
3173
                    continue;
 
3174
                }
 
3175
                int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
 
3176
 
 
3177
                // Read block header
 
3178
                int nConf = 0;
 
3179
                CBlock block;
 
3180
                if (block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
 
3181
                {
 
3182
                    map<uint256, CBlockIndex*>::iterator it = mapBlockIndex.find(block.GetHash());
 
3183
                    if (it != mapBlockIndex.end())
 
3184
                    {
 
3185
                        CBlockIndex* pindex = (*it).second;
 
3186
                        if (pindex->IsInMainChain())
 
3187
                            nConf = 1 + nBestHeight - pindex->nHeight;
 
3188
                    }
 
3189
                }
 
3190
 
 
3191
                dPriority += (double)nValueIn * nConf;
 
3192
 
 
3193
                if (fDebug && GetBoolArg("-printpriority"))
 
3194
                    printf("priority     nValueIn=%-12I64d nConf=%-5d dPriority=%-20.1f\n", nValueIn, nConf, dPriority);
 
3195
            }
 
3196
 
 
3197
            // Priority is sum(valuein * age) / txsize
 
3198
            dPriority /= ::GetSerializeSize(tx, SER_NETWORK);
 
3199
 
 
3200
            if (porphan)
 
3201
                porphan->dPriority = dPriority;
 
3202
            else
 
3203
                mapPriority.insert(make_pair(-dPriority, &(*mi).second));
 
3204
 
 
3205
            if (fDebug && GetBoolArg("-printpriority"))
 
3206
            {
 
3207
                printf("priority %-20.1f %s\n%s", dPriority, tx.GetHash().ToString().substr(0,10).c_str(), tx.ToString().c_str());
 
3208
                if (porphan)
 
3209
                    porphan->print();
 
3210
                printf("\n");
 
3211
            }
 
3212
        }
 
3213
 
 
3214
        // Collect transactions into block
 
3215
        map<uint256, CTxIndex> mapTestPool;
 
3216
        uint64 nBlockSize = 1000;
 
3217
        int nBlockSigOps = 100;
 
3218
        while (!mapPriority.empty())
 
3219
        {
 
3220
            // Take highest priority transaction off priority queue
 
3221
            double dPriority = -(*mapPriority.begin()).first;
 
3222
            CTransaction& tx = *(*mapPriority.begin()).second;
 
3223
            mapPriority.erase(mapPriority.begin());
 
3224
 
 
3225
            // Size limits
 
3226
            unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK);
 
3227
            if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN)
 
3228
                continue;
 
3229
            int nTxSigOps = tx.GetSigOpCount();
 
3230
            if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
 
3231
                continue;
 
3232
 
 
3233
            // Transaction fee required depends on block size
 
3234
            bool fAllowFree = (nBlockSize + nTxSize < 4000 || dPriority > COIN * 144 / 250);
 
3235
            int64 nMinFee = tx.GetMinFee(nBlockSize, fAllowFree);
 
3236
 
 
3237
            // Connecting shouldn't fail due to dependency on other memory pool transactions
 
3238
            // because we're already processing them in order of dependency
 
3239
            map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
 
3240
            if (!tx.ConnectInputs(txdb, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, nFees, false, true, nMinFee))
 
3241
                continue;
 
3242
            swap(mapTestPool, mapTestPoolTmp);
 
3243
 
 
3244
            // Added
 
3245
            pblock->vtx.push_back(tx);
 
3246
            nBlockSize += nTxSize;
 
3247
            nBlockSigOps += nTxSigOps;
 
3248
 
 
3249
            // Add transactions that depend on this one to the priority queue
 
3250
            uint256 hash = tx.GetHash();
 
3251
            if (mapDependers.count(hash))
 
3252
            {
 
3253
                foreach(COrphan* porphan, mapDependers[hash])
 
3254
                {
 
3255
                    if (!porphan->setDependsOn.empty())
 
3256
                    {
 
3257
                        porphan->setDependsOn.erase(hash);
 
3258
                        if (porphan->setDependsOn.empty())
 
3259
                            mapPriority.insert(make_pair(-porphan->dPriority, porphan->ptx));
 
3260
                    }
 
3261
                }
 
3262
            }
 
3263
        }
 
3264
    }
 
3265
    pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);
 
3266
 
 
3267
    // Fill in header
 
3268
    pblock->hashPrevBlock  = pindexPrev->GetBlockHash();
 
3269
    pblock->hashMerkleRoot = pblock->BuildMerkleTree();
 
3270
    pblock->nTime          = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
 
3271
    pblock->nBits          = GetNextWorkRequired(pindexPrev);
 
3272
    pblock->nNonce         = 0;
 
3273
 
 
3274
    return pblock.release();
 
3275
}
 
3276
 
 
3277
 
 
3278
void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce, int64& nPrevTime)
 
3279
{
 
3280
    // Update nExtraNonce
 
3281
    int64 nNow = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
 
3282
    if (++nExtraNonce >= 0x7f && nNow > nPrevTime+1)
 
3283
    {
 
3284
        nExtraNonce = 1;
 
3285
        nPrevTime = nNow;
 
3286
    }
 
3287
    pblock->vtx[0].vin[0].scriptSig = CScript() << pblock->nBits << CBigNum(nExtraNonce);
 
3288
    pblock->hashMerkleRoot = pblock->BuildMerkleTree();
 
3289
}
 
3290
 
 
3291
 
 
3292
void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
 
3293
{
 
3294
    //
 
3295
    // Prebuild hash buffers
 
3296
    //
 
3297
    struct
 
3298
    {
 
3299
        struct unnamed2
 
3300
        {
 
3301
            int nVersion;
 
3302
            uint256 hashPrevBlock;
 
3303
            uint256 hashMerkleRoot;
 
3304
            unsigned int nTime;
 
3305
            unsigned int nBits;
 
3306
            unsigned int nNonce;
 
3307
        }
 
3308
        block;
 
3309
        unsigned char pchPadding0[64];
 
3310
        uint256 hash1;
 
3311
        unsigned char pchPadding1[64];
 
3312
    }
 
3313
    tmp;
 
3314
    memset(&tmp, 0, sizeof(tmp));
 
3315
 
 
3316
    tmp.block.nVersion       = pblock->nVersion;
 
3317
    tmp.block.hashPrevBlock  = pblock->hashPrevBlock;
 
3318
    tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
 
3319
    tmp.block.nTime          = pblock->nTime;
 
3320
    tmp.block.nBits          = pblock->nBits;
 
3321
    tmp.block.nNonce         = pblock->nNonce;
 
3322
 
 
3323
    FormatHashBlocks(&tmp.block, sizeof(tmp.block));
 
3324
    FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
 
3325
 
 
3326
    // Byte swap all the input buffer
 
3327
    for (int i = 0; i < sizeof(tmp)/4; i++)
 
3328
        ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
 
3329
 
 
3330
    // Precalc the first half of the first hash, which stays constant
 
3331
    SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
 
3332
 
 
3333
    memcpy(pdata, &tmp.block, 128);
 
3334
    memcpy(phash1, &tmp.hash1, 64);
 
3335
}
 
3336
 
 
3337
 
 
3338
bool CheckWork(CBlock* pblock, CReserveKey& reservekey)
 
3339
{
 
3340
    uint256 hash = pblock->GetHash();
 
3341
    uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
 
3342
 
 
3343
    if (hash > hashTarget)
 
3344
        return false;
 
3345
 
 
3346
    //// debug print
 
3347
    printf("BitcoinMiner:\n");
 
3348
    printf("proof-of-work found  \n  hash: %s  \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
 
3349
    pblock->print();
 
3350
    printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
 
3351
    printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
 
3352
 
 
3353
    // Found a solution
 
3354
    CRITICAL_BLOCK(cs_main)
 
3355
    {
 
3356
        if (pblock->hashPrevBlock != hashBestChain)
 
3357
            return error("BitcoinMiner : generated block is stale");
 
3358
 
 
3359
        // Remove key from key pool
 
3360
        reservekey.KeepKey();
 
3361
 
 
3362
        // Track how many getdata requests this block gets
 
3363
        CRITICAL_BLOCK(cs_mapRequestCount)
 
3364
            mapRequestCount[pblock->GetHash()] = 0;
 
3365
 
 
3366
        // Process this block the same as if we had received it from another node
 
3367
        if (!ProcessBlock(NULL, pblock))
 
3368
            return error("BitcoinMiner : ProcessBlock, block not accepted");
 
3369
    }
 
3370
 
 
3371
    Sleep(2000);
 
3372
    return true;
 
3373
}
 
3374
 
 
3375
 
 
3376
void BitcoinMiner()
 
3377
{
 
3378
    printf("BitcoinMiner started\n");
 
3379
    SetThreadPriority(THREAD_PRIORITY_LOWEST);
 
3380
    bool f4WaySSE2 = Detect128BitSSE2();
 
3381
    if (mapArgs.count("-4way"))
 
3382
        f4WaySSE2 = GetBoolArg(mapArgs["-4way"]);
 
3383
 
 
3384
    // Each thread has its own key and counter
 
3385
    CReserveKey reservekey;
 
3386
    unsigned int nExtraNonce = 0;
 
3387
    int64 nPrevTime = 0;
 
3388
 
 
3389
    while (fGenerateBitcoins)
 
3390
    {
 
3391
        if (AffinityBugWorkaround(ThreadBitcoinMiner))
 
3392
            return;
 
3393
        if (fShutdown)
 
3394
            return;
 
3395
        while (vNodes.empty() || IsInitialBlockDownload())
 
3396
        {
 
3397
            Sleep(1000);
 
3398
            if (fShutdown)
 
3399
                return;
 
3400
            if (!fGenerateBitcoins)
 
3401
                return;
 
3402
        }
 
3403
 
 
3404
 
 
3405
        //
 
3406
        // Create new block
 
3407
        //
 
3408
        unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
 
3409
        CBlockIndex* pindexPrev = pindexBest;
 
3410
 
 
3411
        auto_ptr<CBlock> pblock(CreateNewBlock(reservekey));
 
3412
        if (!pblock.get())
 
3413
            return;
 
3414
        IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce, nPrevTime);
 
3415
 
 
3416
        printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());
 
3417
 
 
3418
 
 
3419
        //
 
3420
        // Prebuild hash buffers
 
3421
        //
 
3422
        char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
 
3423
        char pdatabuf[128+16];    char* pdata     = alignup<16>(pdatabuf);
 
3424
        char phash1buf[64+16];    char* phash1    = alignup<16>(phash1buf);
 
3425
 
 
3426
        FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1);
 
3427
 
 
3428
        unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
 
3429
        unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
 
3430
 
 
3431
 
 
3432
        //
 
3433
        // Search
 
3434
        //
 
3435
        int64 nStart = GetTime();
 
3436
        uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
 
3437
        uint256 hashbuf[2];
 
3438
        uint256& hash = *alignup<16>(hashbuf);
 
3439
        loop
 
3440
        {
 
3441
            unsigned int nHashesDone = 0;
 
3442
            unsigned int nNonceFound;
 
3443
 
 
3444
#ifdef FOURWAYSSE2
 
3445
            if (f4WaySSE2)
 
3446
                // tcatm's 4-way 128-bit SSE2 SHA-256
 
3447
                nNonceFound = ScanHash_4WaySSE2(pmidstate, pdata + 64, phash1, (char*)&hash, nHashesDone);
 
3448
            else
 
3449
#endif
 
3450
                // Crypto++ SHA-256
 
3451
                nNonceFound = ScanHash_CryptoPP(pmidstate, pdata + 64, phash1, (char*)&hash, nHashesDone);
 
3452
 
 
3453
            // Check if something found
 
3454
            if (nNonceFound != -1)
 
3455
            {
 
3456
                for (int i = 0; i < sizeof(hash)/4; i++)
 
3457
                    ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
 
3458
 
 
3459
                if (hash <= hashTarget)
 
3460
                {
 
3461
                    // Found a solution
 
3462
                    pblock->nNonce = ByteReverse(nNonceFound);
 
3463
                    assert(hash == pblock->GetHash());
 
3464
 
 
3465
                    SetThreadPriority(THREAD_PRIORITY_NORMAL);
 
3466
                    CheckWork(pblock.get(), reservekey);
 
3467
                    SetThreadPriority(THREAD_PRIORITY_LOWEST);
 
3468
                    break;
 
3469
                }
 
3470
            }
 
3471
 
 
3472
            // Meter hashes/sec
 
3473
            static int64 nHashCounter;
 
3474
            if (nHPSTimerStart == 0)
 
3475
            {
 
3476
                nHPSTimerStart = GetTimeMillis();
 
3477
                nHashCounter = 0;
 
3478
            }
 
3479
            else
 
3480
                nHashCounter += nHashesDone;
 
3481
            if (GetTimeMillis() - nHPSTimerStart > 4000)
 
3482
            {
 
3483
                static CCriticalSection cs;
 
3484
                CRITICAL_BLOCK(cs)
 
3485
                {
 
3486
                    if (GetTimeMillis() - nHPSTimerStart > 4000)
 
3487
                    {
 
3488
                        dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
 
3489
                        nHPSTimerStart = GetTimeMillis();
 
3490
                        nHashCounter = 0;
 
3491
                        string strStatus = strprintf("    %.0f khash/s", dHashesPerSec/1000.0);
 
3492
                        UIThreadCall(boost::bind(CalledSetStatusBar, strStatus, 0));
 
3493
                        static int64 nLogTime;
 
3494
                        if (GetTime() - nLogTime > 30 * 60)
 
3495
                        {
 
3496
                            nLogTime = GetTime();
 
3497
                            printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
 
3498
                            printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[3], dHashesPerSec/1000.0);
 
3499
                        }
 
3500
                    }
 
3501
                }
 
3502
            }
 
3503
 
 
3504
            // Check for stop or if block needs to be rebuilt
 
3505
            if (fShutdown)
 
3506
                return;
 
3507
            if (!fGenerateBitcoins)
 
3508
                return;
 
3509
            if (fLimitProcessors && vnThreadsRunning[3] > nLimitProcessors)
 
3510
                return;
 
3511
            if (vNodes.empty())
 
3512
                break;
 
3513
            if (nBlockNonce >= 0xffff0000)
 
3514
                break;
 
3515
            if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
 
3516
                break;
 
3517
            if (pindexPrev != pindexBest)
 
3518
                break;
 
3519
 
 
3520
            // Update nTime every few seconds
 
3521
            pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
 
3522
            nBlockTime = ByteReverse(pblock->nTime);
 
3523
        }
 
3524
    }
 
3525
}
 
3526
 
 
3527
 
 
3528
 
 
3529
 
 
3530
 
 
3531
 
 
3532
 
 
3533
 
 
3534
 
 
3535
 
 
3536
 
 
3537
 
 
3538
 
 
3539
 
 
3540
 
 
3541
 
 
3542
 
 
3543
 
 
3544
//////////////////////////////////////////////////////////////////////////////
 
3545
//
 
3546
// Actions
 
3547
//
 
3548
 
 
3549
 
 
3550
int64 GetBalance()
 
3551
{
 
3552
    int64 nStart = GetTimeMillis();
 
3553
 
 
3554
    int64 nTotal = 0;
 
3555
    CRITICAL_BLOCK(cs_mapWallet)
 
3556
    {
 
3557
        for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
 
3558
        {
 
3559
            CWalletTx* pcoin = &(*it).second;
 
3560
            if (!pcoin->IsFinal() || pcoin->fSpent || !pcoin->IsConfirmed())
 
3561
                continue;
 
3562
            nTotal += pcoin->GetCredit();
 
3563
        }
 
3564
    }
 
3565
 
 
3566
    //printf("GetBalance() %"PRI64d"ms\n", GetTimeMillis() - nStart);
 
3567
    return nTotal;
 
3568
}
 
3569
 
 
3570
 
 
3571
bool SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, set<CWalletTx*>& setCoinsRet)
 
3572
{
 
3573
    setCoinsRet.clear();
 
3574
 
 
3575
    // List of values less than target
 
3576
    int64 nLowestLarger = INT64_MAX;
 
3577
    CWalletTx* pcoinLowestLarger = NULL;
 
3578
    vector<pair<int64, CWalletTx*> > vValue;
 
3579
    int64 nTotalLower = 0;
 
3580
 
 
3581
    CRITICAL_BLOCK(cs_mapWallet)
 
3582
    {
 
3583
       vector<CWalletTx*> vCoins;
 
3584
       vCoins.reserve(mapWallet.size());
 
3585
       for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
 
3586
           vCoins.push_back(&(*it).second);
 
3587
       random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
 
3588
 
 
3589
       foreach(CWalletTx* pcoin, vCoins)
 
3590
       {
 
3591
            if (!pcoin->IsFinal() || pcoin->fSpent || !pcoin->IsConfirmed())
 
3592
                continue;
 
3593
 
 
3594
            int nDepth = pcoin->GetDepthInMainChain();
 
3595
            if (nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs))
 
3596
                continue;
 
3597
 
 
3598
            int64 n = pcoin->GetCredit();
 
3599
            if (n <= 0)
 
3600
                continue;
 
3601
            if (n < nTargetValue)
 
3602
            {
 
3603
                vValue.push_back(make_pair(n, pcoin));
 
3604
                nTotalLower += n;
 
3605
            }
 
3606
            else if (n == nTargetValue)
 
3607
            {
 
3608
                setCoinsRet.insert(pcoin);
 
3609
                return true;
 
3610
            }
 
3611
            else if (n < nLowestLarger)
 
3612
            {
 
3613
                nLowestLarger = n;
 
3614
                pcoinLowestLarger = pcoin;
 
3615
            }
 
3616
        }
 
3617
    }
 
3618
 
 
3619
    if (nTotalLower < nTargetValue)
 
3620
    {
 
3621
        if (pcoinLowestLarger == NULL)
 
3622
            return false;
 
3623
        setCoinsRet.insert(pcoinLowestLarger);
 
3624
        return true;
 
3625
    }
 
3626
 
 
3627
    // Solve subset sum by stochastic approximation
 
3628
    sort(vValue.rbegin(), vValue.rend());
 
3629
    vector<char> vfIncluded;
 
3630
    vector<char> vfBest(vValue.size(), true);
 
3631
    int64 nBest = nTotalLower;
 
3632
 
 
3633
    for (int nRep = 0; nRep < 1000 && nBest != nTargetValue; nRep++)
 
3634
    {
 
3635
        vfIncluded.assign(vValue.size(), false);
 
3636
        int64 nTotal = 0;
 
3637
        bool fReachedTarget = false;
 
3638
        for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
 
3639
        {
 
3640
            for (int i = 0; i < vValue.size(); i++)
 
3641
            {
 
3642
                if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
 
3643
                {
 
3644
                    nTotal += vValue[i].first;
 
3645
                    vfIncluded[i] = true;
 
3646
                    if (nTotal >= nTargetValue)
 
3647
                    {
 
3648
                        fReachedTarget = true;
 
3649
                        if (nTotal < nBest)
 
3650
                        {
 
3651
                            nBest = nTotal;
 
3652
                            vfBest = vfIncluded;
 
3653
                        }
 
3654
                        nTotal -= vValue[i].first;
 
3655
                        vfIncluded[i] = false;
 
3656
                    }
 
3657
                }
 
3658
            }
 
3659
        }
 
3660
    }
 
3661
 
 
3662
    // If the next larger is still closer, return it
 
3663
    if (pcoinLowestLarger && nLowestLarger - nTargetValue <= nBest - nTargetValue)
 
3664
        setCoinsRet.insert(pcoinLowestLarger);
 
3665
    else
 
3666
    {
 
3667
        for (int i = 0; i < vValue.size(); i++)
 
3668
            if (vfBest[i])
 
3669
                setCoinsRet.insert(vValue[i].second);
 
3670
 
 
3671
        //// debug print
 
3672
        printf("SelectCoins() best subset: ");
 
3673
        for (int i = 0; i < vValue.size(); i++)
 
3674
            if (vfBest[i])
 
3675
                printf("%s ", FormatMoney(vValue[i].first).c_str());
 
3676
        printf("total %s\n", FormatMoney(nBest).c_str());
 
3677
    }
 
3678
 
 
3679
    return true;
 
3680
}
 
3681
 
 
3682
bool SelectCoins(int64 nTargetValue, set<CWalletTx*>& setCoinsRet)
 
3683
{
 
3684
    return (SelectCoinsMinConf(nTargetValue, 1, 6, setCoinsRet) ||
 
3685
            SelectCoinsMinConf(nTargetValue, 1, 1, setCoinsRet) ||
 
3686
            SelectCoinsMinConf(nTargetValue, 0, 1, setCoinsRet));
 
3687
}
 
3688
 
 
3689
 
 
3690
 
 
3691
 
 
3692
bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
 
3693
{
 
3694
    CRITICAL_BLOCK(cs_main)
 
3695
    {
 
3696
        // txdb must be opened before the mapWallet lock
 
3697
        CTxDB txdb("r");
 
3698
        CRITICAL_BLOCK(cs_mapWallet)
 
3699
        {
 
3700
            nFeeRet = nTransactionFee;
 
3701
            loop
 
3702
            {
 
3703
                wtxNew.vin.clear();
 
3704
                wtxNew.vout.clear();
 
3705
                wtxNew.fFromMe = true;
 
3706
                if (nValue < 0)
 
3707
                    return false;
 
3708
                int64 nValueOut = nValue;
 
3709
                int64 nTotalValue = nValue + nFeeRet;
 
3710
 
 
3711
                // Choose coins to use
 
3712
                set<CWalletTx*> setCoins;
 
3713
                if (!SelectCoins(nTotalValue, setCoins))
 
3714
                    return false;
 
3715
                int64 nValueIn = 0;
 
3716
                foreach(CWalletTx* pcoin, setCoins)
 
3717
                    nValueIn += pcoin->GetCredit();
 
3718
 
 
3719
                // Fill a vout to the payee
 
3720
                bool fChangeFirst = GetRand(2);
 
3721
                if (!fChangeFirst)
 
3722
                    wtxNew.vout.push_back(CTxOut(nValueOut, scriptPubKey));
 
3723
 
 
3724
                // Fill a vout back to self with any change
 
3725
                int64 nChange = nValueIn - nTotalValue;
 
3726
                if (nChange >= CENT)
 
3727
                {
 
3728
                    // Note: We use a new key here to keep it from being obvious which side is the change.
 
3729
                    //  The drawback is that by not reusing a previous key, the change may be lost if a
 
3730
                    //  backup is restored, if the backup doesn't have the new private key for the change.
 
3731
                    //  If we reused the old key, it would be possible to add code to look for and
 
3732
                    //  rediscover unknown transactions that were written with keys of ours to recover
 
3733
                    //  post-backup change.
 
3734
 
 
3735
                    // Reserve a new key pair from key pool
 
3736
                    vector<unsigned char> vchPubKey = reservekey.GetReservedKey();
 
3737
                    assert(mapKeys.count(vchPubKey));
 
3738
 
 
3739
                    // Fill a vout to ourself, using same address type as the payment
 
3740
                    CScript scriptChange;
 
3741
                    if (scriptPubKey.GetBitcoinAddressHash160() != 0)
 
3742
                        scriptChange.SetBitcoinAddress(vchPubKey);
 
3743
                    else
 
3744
                        scriptChange << vchPubKey << OP_CHECKSIG;
 
3745
                    wtxNew.vout.push_back(CTxOut(nChange, scriptChange));
 
3746
                }
 
3747
                else
 
3748
                    reservekey.ReturnKey();
 
3749
 
 
3750
                // Fill a vout to the payee
 
3751
                if (fChangeFirst)
 
3752
                    wtxNew.vout.push_back(CTxOut(nValueOut, scriptPubKey));
 
3753
 
 
3754
                // Fill vin
 
3755
                foreach(CWalletTx* pcoin, setCoins)
 
3756
                    for (int nOut = 0; nOut < pcoin->vout.size(); nOut++)
 
3757
                        if (pcoin->vout[nOut].IsMine())
 
3758
                            wtxNew.vin.push_back(CTxIn(pcoin->GetHash(), nOut));
 
3759
 
 
3760
                // Sign
 
3761
                int nIn = 0;
 
3762
                foreach(CWalletTx* pcoin, setCoins)
 
3763
                    for (int nOut = 0; nOut < pcoin->vout.size(); nOut++)
 
3764
                        if (pcoin->vout[nOut].IsMine())
 
3765
                            if (!SignSignature(*pcoin, wtxNew, nIn++))
 
3766
                                return false;
 
3767
 
 
3768
                // Limit size
 
3769
                unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK);
 
3770
                if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
 
3771
                    return false;
 
3772
 
 
3773
                // Check that enough fee is included
 
3774
                int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
 
3775
                int64 nMinFee = wtxNew.GetMinFee();
 
3776
                if (nFeeRet < max(nPayFee, nMinFee))
 
3777
                {
 
3778
                    nFeeRet = max(nPayFee, nMinFee);
 
3779
                    continue;
 
3780
                }
 
3781
 
 
3782
                // Fill vtxPrev by copying from previous transactions vtxPrev
 
3783
                wtxNew.AddSupportingTransactions(txdb);
 
3784
                wtxNew.fTimeReceivedIsTxTime = true;
 
3785
 
 
3786
                break;
 
3787
            }
 
3788
        }
 
3789
    }
 
3790
    return true;
 
3791
}
 
3792
 
 
3793
// Call after CreateTransaction unless you want to abort
 
3794
bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
 
3795
{
 
3796
    CRITICAL_BLOCK(cs_main)
 
3797
    {
 
3798
        printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
 
3799
        CRITICAL_BLOCK(cs_mapWallet)
 
3800
        {
 
3801
            // This is only to keep the database open to defeat the auto-flush for the
 
3802
            // duration of this scope.  This is the only place where this optimization
 
3803
            // maybe makes sense; please don't do it anywhere else.
 
3804
            CWalletDB walletdb("r");
 
3805
 
 
3806
            // Take key pair from key pool so it won't be used again
 
3807
            reservekey.KeepKey();
 
3808
 
 
3809
            // Add tx to wallet, because if it has change it's also ours,
 
3810
            // otherwise just for transaction history.
 
3811
            AddToWallet(wtxNew);
 
3812
 
 
3813
            // Mark old coins as spent
 
3814
            set<CWalletTx*> setCoins;
 
3815
            foreach(const CTxIn& txin, wtxNew.vin)
 
3816
                setCoins.insert(&mapWallet[txin.prevout.hash]);
 
3817
            foreach(CWalletTx* pcoin, setCoins)
 
3818
            {
 
3819
                pcoin->fSpent = true;
 
3820
                pcoin->WriteToDisk();
 
3821
                vWalletUpdated.push_back(pcoin->GetHash());
 
3822
            }
 
3823
        }
 
3824
 
 
3825
        // Track how many getdata requests our transaction gets
 
3826
        CRITICAL_BLOCK(cs_mapRequestCount)
 
3827
            mapRequestCount[wtxNew.GetHash()] = 0;
 
3828
 
 
3829
        // Broadcast
 
3830
        if (!wtxNew.AcceptToMemoryPool())
 
3831
        {
 
3832
            // This must not fail. The transaction has already been signed and recorded.
 
3833
            printf("CommitTransaction() : Error: Transaction not valid");
 
3834
            return false;
 
3835
        }
 
3836
        wtxNew.RelayWalletTransaction();
 
3837
    }
 
3838
    MainFrameRepaint();
 
3839
    return true;
 
3840
}
 
3841
 
 
3842
 
 
3843
 
 
3844
 
 
3845
string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
 
3846
{
 
3847
    CRITICAL_BLOCK(cs_main)
 
3848
    {
 
3849
        CReserveKey reservekey;
 
3850
        int64 nFeeRequired;
 
3851
        if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
 
3852
        {
 
3853
            string strError;
 
3854
            if (nValue + nFeeRequired > GetBalance())
 
3855
                strError = strprintf(_("Error: This is an oversized transaction that requires a transaction fee of %s  "), FormatMoney(nFeeRequired).c_str());
 
3856
            else
 
3857
                strError = _("Error: Transaction creation failed  ");
 
3858
            printf("SendMoney() : %s", strError.c_str());
 
3859
            return strError;
 
3860
        }
 
3861
 
 
3862
        if (fAskFee && !ThreadSafeAskFee(nFeeRequired, _("Sending..."), NULL))
 
3863
            return "ABORTED";
 
3864
 
 
3865
        if (!CommitTransaction(wtxNew, reservekey))
 
3866
            return _("Error: The transaction was rejected.  This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.");
 
3867
    }
 
3868
    MainFrameRepaint();
 
3869
    return "";
 
3870
}
 
3871
 
 
3872
 
 
3873
 
 
3874
string SendMoneyToBitcoinAddress(string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
 
3875
{
 
3876
    // Check amount
 
3877
    if (nValue <= 0)
 
3878
        return _("Invalid amount");
 
3879
    if (nValue + nTransactionFee > GetBalance())
 
3880
        return _("Insufficient funds");
 
3881
 
 
3882
    // Parse bitcoin address
 
3883
    CScript scriptPubKey;
 
3884
    if (!scriptPubKey.SetBitcoinAddress(strAddress))
 
3885
        return _("Invalid bitcoin address");
 
3886
 
 
3887
    return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
 
3888
}