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