Feathercoin  0.5.0
P2P Digital Currency
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros
main.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Copyright (c) 2011-2013 PPCoin developers
4 // Copyright (c) 2013 Primecoin developers
5 // Copyright (c) 2013 Feathercoin developers
6 // Distributed under the MIT/X11 software license, see the accompanying
7 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
8 
9 #include "alert.h"
10 #include "checkpoints.h"
11 #include "db.h"
12 #include "txdb.h"
13 #include "net.h"
14 #include "init.h"
15 #include "ui_interface.h"
16 #include "checkqueue.h"
17 #include "checkpointsync.h"
18 #include <boost/algorithm/string/replace.hpp>
19 #include <boost/filesystem.hpp>
20 #include <boost/filesystem/fstream.hpp>
21 
22 using namespace std;
23 using namespace boost;
24 
25 //
26 // Global state
27 //
28 
30 set<CWallet*> setpwalletRegistered;
31 
33 
35 unsigned int nTransactionsUpdated = 0;
36 
37 map<uint256, CBlockIndex*> mapBlockIndex;
38 uint256 hashGenesisBlock("0x12a765e31ffd4059bada1e25190f6e98c99d9714d334efa41a195a7e7e04bfe2");
39 static CBigNum bnProofOfWorkLimit(~uint256(0) >> 20); // Feathercoin: starting difficulty is 1 / 2^12
41 int nBestHeight = -1;
46 set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexValid; // may contain all CBlockIndex*'s that have validness >=BLOCK_VALID_TRANSACTIONS, and must contain those who aren't failed
49 bool fImporting = false;
50 bool fReindex = false;
51 bool fBenchmark = false;
52 bool fTxIndex = false;
53 unsigned int nCoinCacheSize = 5000;
54 
55 // The 1st hard fork
56 const int nForkOne = 33000;
57 // The 2nd hard fork
58 const int nForkTwo = 87948;
59 // The 3rd hard fork
60 const int nForkThree = 204639;
61 
66 
67 CMedianFilter<int> cPeerBlockCounts(8, 0); // Amount of blocks that other nodes claim to have
68 
69 map<uint256, CBlock*> mapOrphanBlocks;
70 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
71 
72 map<uint256, CTransaction> mapOrphanTransactions;
73 map<uint256, set<uint256> > mapOrphanTransactionsByPrev;
74 
75 // Constant stuff for coinbase transactions we create:
77 
78 const string strMessageMagic = "Feathercoin Signed Message:\n";
79 
80 double dHashesPerSec = 0.0;
82 
83 // Settings
85 int64 nMinimumInputValue = DUST_HARD_LIMIT;
86 
87 
89 //
90 // dispatching functions
91 //
92 
93 // These functions dispatch to one or all registered wallets
94 
95 
96 void RegisterWallet(CWallet* pwalletIn)
97 {
98  {
99  LOCK(cs_setpwalletRegistered);
100  setpwalletRegistered.insert(pwalletIn);
101  }
102 }
103 
104 void UnregisterWallet(CWallet* pwalletIn)
105 {
106  {
107  LOCK(cs_setpwalletRegistered);
108  setpwalletRegistered.erase(pwalletIn);
109  }
110 }
111 
112 // get the wallet transaction with the given hash (if it exists)
113 bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
114 {
115  BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
116  if (pwallet->GetTransaction(hashTx,wtx))
117  return true;
118  return false;
119 }
120 
121 // erases transaction with the given hash from all wallets
122 void static EraseFromWallets(uint256 hash)
123 {
124  BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
125  pwallet->EraseFromWallet(hash);
126 }
127 
128 // make sure all wallets know about the given transaction, in the given block
129 void SyncWithWallets(const uint256 &hash, const CTransaction& tx, const CBlock* pblock, bool fUpdate)
130 {
131  BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
132  pwallet->AddToWalletIfInvolvingMe(hash, tx, pblock, fUpdate);
133 }
134 
135 // notify wallets about a new best chain
136 void static SetBestChain(const CBlockLocator& loc)
137 {
138  BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
139  pwallet->SetBestChain(loc);
140 }
141 
142 // notify wallets about an updated transaction
143 void static UpdatedTransaction(const uint256& hashTx)
144 {
145  BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
146  pwallet->UpdatedTransaction(hashTx);
147 }
148 
149 // dump all wallets
150 void static PrintWallets(const CBlock& block)
151 {
152  BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
153  pwallet->PrintWallet(block);
154 }
155 
156 // notify wallets about an incoming inventory (for request counts)
157 void static Inventory(const uint256& hash)
158 {
159  BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
160  pwallet->Inventory(hash);
161 }
162 
163 // ask wallets to resend their transactions
164 void static ResendWalletTransactions()
165 {
166  BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
167  pwallet->ResendWalletTransactions();
168 }
169 
170 
171 
172 
173 
174 
175 
177 //
178 // CCoinsView implementations
179 //
180 
181 bool CCoinsView::GetCoins(const uint256 &txid, CCoins &coins) { return false; }
182 bool CCoinsView::SetCoins(const uint256 &txid, const CCoins &coins) { return false; }
183 bool CCoinsView::HaveCoins(const uint256 &txid) { return false; }
185 bool CCoinsView::SetBestBlock(CBlockIndex *pindex) { return false; }
186 bool CCoinsView::BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex) { return false; }
187 bool CCoinsView::GetStats(CCoinsStats &stats) { return false; }
188 
189 
191 bool CCoinsViewBacked::GetCoins(const uint256 &txid, CCoins &coins) { return base->GetCoins(txid, coins); }
192 bool CCoinsViewBacked::SetCoins(const uint256 &txid, const CCoins &coins) { return base->SetCoins(txid, coins); }
193 bool CCoinsViewBacked::HaveCoins(const uint256 &txid) { return base->HaveCoins(txid); }
196 void CCoinsViewBacked::SetBackend(CCoinsView &viewIn) { base = &viewIn; }
197 bool CCoinsViewBacked::BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex) { return base->BatchWrite(mapCoins, pindex); }
199 
200 CCoinsViewCache::CCoinsViewCache(CCoinsView &baseIn, bool fDummy) : CCoinsViewBacked(baseIn), pindexTip(NULL) { }
201 
202 bool CCoinsViewCache::GetCoins(const uint256 &txid, CCoins &coins) {
203  if (cacheCoins.count(txid)) {
204  coins = cacheCoins[txid];
205  return true;
206  }
207  if (base->GetCoins(txid, coins)) {
208  cacheCoins[txid] = coins;
209  return true;
210  }
211  return false;
212 }
213 
214 std::map<uint256,CCoins>::iterator CCoinsViewCache::FetchCoins(const uint256 &txid) {
215  std::map<uint256,CCoins>::iterator it = cacheCoins.lower_bound(txid);
216  if (it != cacheCoins.end() && it->first == txid)
217  return it;
218  CCoins tmp;
219  if (!base->GetCoins(txid,tmp))
220  return cacheCoins.end();
221  std::map<uint256,CCoins>::iterator ret = cacheCoins.insert(it, std::make_pair(txid, CCoins()));
222  tmp.swap(ret->second);
223  return ret;
224 }
225 
227  std::map<uint256,CCoins>::iterator it = FetchCoins(txid);
228  assert(it != cacheCoins.end());
229  return it->second;
230 }
231 
232 bool CCoinsViewCache::SetCoins(const uint256 &txid, const CCoins &coins) {
233  cacheCoins[txid] = coins;
234  return true;
235 }
236 
238  return FetchCoins(txid) != cacheCoins.end();
239 }
240 
242  if (pindexTip == NULL)
244  return pindexTip;
245 }
246 
248  pindexTip = pindex;
249  return true;
250 }
251 
252 bool CCoinsViewCache::BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex) {
253  for (std::map<uint256, CCoins>::const_iterator it = mapCoins.begin(); it != mapCoins.end(); it++)
254  cacheCoins[it->first] = it->second;
255  pindexTip = pindex;
256  return true;
257 }
258 
260  bool fOk = base->BatchWrite(cacheCoins, pindexTip);
261  if (fOk)
262  cacheCoins.clear();
263  return fOk;
264 }
265 
267  return cacheCoins.size();
268 }
269 
272 CCoinsViewMemPool::CCoinsViewMemPool(CCoinsView &baseIn, CTxMemPool &mempoolIn) : CCoinsViewBacked(baseIn), mempool(mempoolIn) { }
273 
274 bool CCoinsViewMemPool::GetCoins(const uint256 &txid, CCoins &coins) {
275  if (base->GetCoins(txid, coins))
276  return true;
277  if (mempool.exists(txid)) {
278  const CTransaction &tx = mempool.lookup(txid);
279  coins = CCoins(tx, MEMPOOL_HEIGHT);
280  return true;
281  }
282  return false;
283 }
284 
286  return mempool.exists(txid) || base->HaveCoins(txid);
287 }
288 
291 
293 //
294 // mapOrphanTransactions
295 //
296 
297 bool AddOrphanTx(const CTransaction& tx)
298 {
299  uint256 hash = tx.GetHash();
300  if (mapOrphanTransactions.count(hash))
301  return false;
302 
303  // Ignore big transactions, to avoid a
304  // send-big-orphans memory exhaustion attack. If a peer has a legitimate
305  // large transaction with a missing parent then we assume
306  // it will rebroadcast it later, after the parent transaction(s)
307  // have been mined or received.
308  // 10,000 orphans, each of which is at most 5,000 bytes big is
309  // at most 500 megabytes of orphans:
310  unsigned int sz = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
311  if (sz > 5000)
312  {
313  printf("ignoring large orphan tx (size: %u, hash: %s)\n", sz, hash.ToString().c_str());
314  return false;
315  }
316 
317  mapOrphanTransactions[hash] = tx;
318  BOOST_FOREACH(const CTxIn& txin, tx.vin)
319  mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash);
320 
321  printf("stored orphan tx %s (mapsz %"PRIszu")\n", hash.ToString().c_str(),
322  mapOrphanTransactions.size());
323  return true;
324 }
325 
326 void static EraseOrphanTx(uint256 hash)
327 {
328  if (!mapOrphanTransactions.count(hash))
329  return;
330  const CTransaction& tx = mapOrphanTransactions[hash];
331  BOOST_FOREACH(const CTxIn& txin, tx.vin)
332  {
333  mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash);
334  if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty())
335  mapOrphanTransactionsByPrev.erase(txin.prevout.hash);
336  }
337  mapOrphanTransactions.erase(hash);
338 }
339 
340 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
341 {
342  unsigned int nEvicted = 0;
343  while (mapOrphanTransactions.size() > nMaxOrphans)
344  {
345  // Evict a random orphan:
346  uint256 randomhash = GetRandHash();
347  map<uint256, CTransaction>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
348  if (it == mapOrphanTransactions.end())
349  it = mapOrphanTransactions.begin();
350  EraseOrphanTx(it->first);
351  ++nEvicted;
352  }
353  return nEvicted;
354 }
355 
356 
357 
358 
359 
360 
361 
363 //
364 // CTransaction / CTxOut
365 //
366 
367 bool CTxOut::IsDust() const
368 {
369  // Feathercoin: IsDust() detection disabled, allows any valid dust to be relayed.
370  // The fees imposed on each dust txo is considered sufficient spam deterrant.
371  return false;
372 }
373 
374 bool CTransaction::IsStandard(string& strReason) const
375 {
377  strReason = "version";
378  return false;
379  }
380 
381  if (!IsFinal()) {
382  strReason = "not-final";
383  return false;
384  }
385 
386  // Extremely large transactions with lots of inputs can cost the network
387  // almost as much to process as they cost the sender in fees, because
388  // computing signature hashes is O(ninputs*txsize). Limiting transactions
389  // to MAX_STANDARD_TX_SIZE mitigates CPU exhaustion attacks.
391  if (sz >= MAX_STANDARD_TX_SIZE) {
392  strReason = "tx-size";
393  return false;
394  }
395 
396  BOOST_FOREACH(const CTxIn& txin, vin)
397  {
398  // Biggest 'standard' txin is a 3-signature 3-of-3 CHECKMULTISIG
399  // pay-to-script-hash, which is 3 ~80-byte signatures, 3
400  // ~65-byte public keys, plus a few script ops.
401  if (txin.scriptSig.size() > 500) {
402  strReason = "scriptsig-size";
403  return false;
404  }
405  if (!txin.scriptSig.IsPushOnly()) {
406  strReason = "scriptsig-not-pushonly";
407  return false;
408  }
409  }
410  BOOST_FOREACH(const CTxOut& txout, vout) {
411  if (!::IsStandard(txout.scriptPubKey)) {
412  strReason = "scriptpubkey";
413  return false;
414  }
415  if (txout.IsDust()) {
416  strReason = "dust";
417  return false;
418  }
419  }
420  return true;
421 }
422 
423 //
424 // Check transaction inputs, and make sure any
425 // pay-to-script-hash transactions are evaluating IsStandard scripts
426 //
427 // Why bother? To avoid denial-of-service attacks; an attacker
428 // can submit a standard HASH... OP_EQUAL transaction,
429 // which will get accepted into blocks. The redemption
430 // script can be anything; an attacker could use a very
431 // expensive-to-check-upon-redemption script like:
432 // DUP CHECKSIG DROP ... repeated 100 times... OP_1
433 //
435 {
436  if (IsCoinBase())
437  return true; // Coinbases don't use vin normally
438 
439  for (unsigned int i = 0; i < vin.size(); i++)
440  {
441  const CTxOut& prev = GetOutputFor(vin[i], mapInputs);
442 
443  vector<vector<unsigned char> > vSolutions;
444  txnouttype whichType;
445  // get the scriptPubKey corresponding to this input:
446  const CScript& prevScript = prev.scriptPubKey;
447  if (!Solver(prevScript, whichType, vSolutions))
448  return false;
449  int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
450  if (nArgsExpected < 0)
451  return false;
452 
453  // Transactions with extra stuff in their scriptSigs are
454  // non-standard. Note that this EvalScript() call will
455  // be quick, because if there are any operations
456  // beside "push data" in the scriptSig the
457  // IsStandard() call returns false
458  vector<vector<unsigned char> > stack;
459  if (!EvalScript(stack, vin[i].scriptSig, *this, i, false, 0))
460  return false;
461 
462  if (whichType == TX_SCRIPTHASH)
463  {
464  if (stack.empty())
465  return false;
466  CScript subscript(stack.back().begin(), stack.back().end());
467  vector<vector<unsigned char> > vSolutions2;
468  txnouttype whichType2;
469  if (!Solver(subscript, whichType2, vSolutions2))
470  return false;
471  if (whichType2 == TX_SCRIPTHASH)
472  return false;
473 
474  int tmpExpected;
475  tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
476  if (tmpExpected < 0)
477  return false;
478  nArgsExpected += tmpExpected;
479  }
480 
481  if (stack.size() != (unsigned int)nArgsExpected)
482  return false;
483  }
484 
485  return true;
486 }
487 
489 {
490  unsigned int nSigOps = 0;
491  BOOST_FOREACH(const CTxIn& txin, vin)
492  {
493  nSigOps += txin.scriptSig.GetSigOpCount(false);
494  }
495  BOOST_FOREACH(const CTxOut& txout, vout)
496  {
497  nSigOps += txout.scriptPubKey.GetSigOpCount(false);
498  }
499  return nSigOps;
500 }
501 
502 
503 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
504 {
505  CBlock blockTmp;
506 
507  if (pblock == NULL) {
508  CCoins coins;
509  if (pcoinsTip->GetCoins(GetHash(), coins)) {
510  CBlockIndex *pindex = FindBlockByHeight(coins.nHeight);
511  if (pindex) {
512  if (!blockTmp.ReadFromDisk(pindex))
513  return 0;
514  pblock = &blockTmp;
515  }
516  }
517  }
518 
519  if (pblock) {
520  // Update the tx's hashBlock
521  hashBlock = pblock->GetHash();
522 
523  // Locate the transaction
524  for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++)
525  if (pblock->vtx[nIndex] == *(CTransaction*)this)
526  break;
527  if (nIndex == (int)pblock->vtx.size())
528  {
529  vMerkleBranch.clear();
530  nIndex = -1;
531  printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
532  return 0;
533  }
534 
535  // Fill in merkle branch
537  }
538 
539  // Is the tx in a block that's in the main chain
540  map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
541  if (mi == mapBlockIndex.end())
542  return 0;
543  CBlockIndex* pindex = (*mi).second;
544  if (!pindex || !pindex->IsInMainChain())
545  return 0;
546 
547  return pindexBest->nHeight - pindex->nHeight + 1;
548 }
549 
550 
551 
552 
553 
554 
555 
557 {
558  // Basic checks that don't depend on any context
559  if (vin.empty())
560  return state.DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
561  if (vout.empty())
562  return state.DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
563  // Size limits
564  if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
565  return state.DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
566 
567  // Check for negative or overflow output values
568  int64 nValueOut = 0;
569  BOOST_FOREACH(const CTxOut& txout, vout)
570  {
571  if (txout.nValue < 0)
572  return state.DoS(100, error("CTransaction::CheckTransaction() : txout.nValue negative"));
573  if (txout.nValue > MAX_MONEY)
574  return state.DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
575  nValueOut += txout.nValue;
576  if (!MoneyRange(nValueOut))
577  return state.DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
578  }
579 
580  // Check for duplicate inputs
581  set<COutPoint> vInOutPoints;
582  BOOST_FOREACH(const CTxIn& txin, vin)
583  {
584  if (vInOutPoints.count(txin.prevout))
585  return state.DoS(100, error("CTransaction::CheckTransaction() : duplicate inputs"));
586  vInOutPoints.insert(txin.prevout);
587  }
588 
589  if (IsCoinBase())
590  {
591  if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
592  return state.DoS(100, error("CTransaction::CheckTransaction() : coinbase script size"));
593  }
594  else
595  {
596  BOOST_FOREACH(const CTxIn& txin, vin)
597  if (txin.prevout.IsNull())
598  return state.DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
599  }
600 
601  return true;
602 }
603 
604 int64 CTransaction::GetMinFee(unsigned int nBlockSize, bool fAllowFree,
605  enum GetMinFee_mode mode) const
606 {
607  // Base fee is either nMinTxFee or nMinRelayTxFee
608  int64 nBaseFee = (mode == GMF_RELAY) ? nMinRelayTxFee : nMinTxFee;
609 
610  unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION);
611  unsigned int nNewBlockSize = nBlockSize + nBytes;
612  int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
613 
614  if (fAllowFree)
615  {
616  // There is a free transaction area in blocks created by most miners,
617  // * If we are relaying we allow transactions up to DEFAULT_BLOCK_PRIORITY_SIZE - 1000
618  // to be considered to fall into this category. We don't want to encourage sending
619  // multiple transactions instead of one big transaction to avoid fees.
620  // * If we are creating a transaction we allow transactions up to 5,000 bytes
621  // to be considered safe and assume they can likely make it into this section.
622  if (nBytes < (mode == GMF_SEND ? 5000 : (DEFAULT_BLOCK_PRIORITY_SIZE - 1000)))
623  nMinFee = 0;
624  }
625 
626  // Feathercoin
627  // To limit dust spam, add nBaseFee for each output less than DUST_SOFT_LIMIT
628  BOOST_FOREACH(const CTxOut& txout, vout)
629  if (txout.nValue < DUST_SOFT_LIMIT)
630  nMinFee += nBaseFee;
631 
632  // Raise the price as the block approaches full
633  if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
634  {
635  if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
636  return MAX_MONEY;
637  nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
638  }
639 
640  if (!MoneyRange(nMinFee))
641  nMinFee = MAX_MONEY;
642  return nMinFee;
643 }
644 
645 void CTxMemPool::pruneSpent(const uint256 &hashTx, CCoins &coins)
646 {
647  LOCK(cs);
648 
649  std::map<COutPoint, CInPoint>::iterator it = mapNextTx.lower_bound(COutPoint(hashTx, 0));
650 
651  // iterate over all COutPoints in mapNextTx whose hash equals the provided hashTx
652  while (it != mapNextTx.end() && it->first.hash == hashTx) {
653  coins.Spend(it->first.n); // and remove those outputs from coins
654  it++;
655  }
656 }
657 
658 bool CTxMemPool::accept(CValidationState &state, CTransaction &tx, bool fCheckInputs, bool fLimitFree,
659  bool* pfMissingInputs)
660 {
661  if (pfMissingInputs)
662  *pfMissingInputs = false;
663 
664  if (!tx.CheckTransaction(state))
665  return error("CTxMemPool::accept() : CheckTransaction failed");
666 
667  // Coinbase is only valid in a block, not as a loose transaction
668  if (tx.IsCoinBase())
669  return state.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx"));
670 
671  // To help v0.1.5 clients who would see it as a negative number
672  if ((int64)tx.nLockTime > std::numeric_limits<int>::max())
673  return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet");
674 
675  // Rather not work on nonstandard transactions (unless -testnet)
676  string strNonStd;
677  if (!fTestNet && !tx.IsStandard(strNonStd))
678  return error("CTxMemPool::accept() : nonstandard transaction (%s)",
679  strNonStd.c_str());
680 
681  // is it already in the memory pool?
682  uint256 hash = tx.GetHash();
683  {
684  LOCK(cs);
685  if (mapTx.count(hash))
686  return false;
687  }
688 
689  // Check for conflicts with in-memory transactions
690  CTransaction* ptxOld = NULL;
691  for (unsigned int i = 0; i < tx.vin.size(); i++)
692  {
693  COutPoint outpoint = tx.vin[i].prevout;
694  if (mapNextTx.count(outpoint))
695  {
696  // Disable replacement feature for now
697  return false;
698 
699  // Allow replacing with a newer version of the same transaction
700  if (i != 0)
701  return false;
702  ptxOld = mapNextTx[outpoint].ptx;
703  if (ptxOld->IsFinal())
704  return false;
705  if (!tx.IsNewerThan(*ptxOld))
706  return false;
707  for (unsigned int i = 0; i < tx.vin.size(); i++)
708  {
709  COutPoint outpoint = tx.vin[i].prevout;
710  if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
711  return false;
712  }
713  break;
714  }
715  }
716 
717  if (fCheckInputs)
718  {
720  CCoinsViewCache view(dummy);
721 
722  {
723  LOCK(cs);
724  CCoinsViewMemPool viewMemPool(*pcoinsTip, *this);
725  view.SetBackend(viewMemPool);
726 
727  // do we already have it?
728  if (view.HaveCoins(hash))
729  return false;
730 
731  // do all inputs exist?
732  // Note that this does not check for the presence of actual outputs (see the next check for that),
733  // only helps filling in pfMissingInputs (to determine missing vs spent).
734  BOOST_FOREACH(const CTxIn txin, tx.vin) {
735  if (!view.HaveCoins(txin.prevout.hash)) {
736  if (pfMissingInputs)
737  *pfMissingInputs = true;
738  return false;
739  }
740  }
741 
742  // are the actual inputs available?
743  if (!tx.HaveInputs(view))
744  return state.Invalid(error("CTxMemPool::accept() : inputs already spent"));
745 
746  // Bring the best block into scope
747  view.GetBestBlock();
748 
749  // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
750  view.SetBackend(dummy);
751  }
752 
753  // Check for non-standard pay-to-script-hash in inputs
754  if (!tx.AreInputsStandard(view) && !fTestNet)
755  return error("CTxMemPool::accept() : nonstandard transaction input");
756 
757  // Note: if you modify this code to accept non-standard transactions, then
758  // you should add code here to check that the transaction does a
759  // reasonable number of ECDSA signature verifications.
760 
761  int64 nFees = tx.GetValueIn(view)-tx.GetValueOut();
762  unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
763 
764  // Don't accept it if it can't get into a block
765  int64 txMinFee = tx.GetMinFee(1000, true, GMF_RELAY);
766  if (fLimitFree && nFees < txMinFee)
767  return error("CTxMemPool::accept() : not enough fees %s, %"PRI64d" < %"PRI64d,
768  hash.ToString().c_str(),
769  nFees, txMinFee);
770 
771  // Continuously rate-limit free transactions
772  // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
773  // be annoying or make others' transactions take longer to confirm.
774  if (fLimitFree && nFees < CTransaction::nMinRelayTxFee)
775  {
776  static double dFreeCount;
777  static int64 nLastTime;
778  int64 nNow = GetTime();
779 
780  LOCK(cs);
781 
782  // Use an exponentially decaying ~10-minute window:
783  dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
784  nLastTime = nNow;
785  // -limitfreerelay unit is thousand-bytes-per-minute
786  // At default rate it would take over a month to fill 1GB
787  if (dFreeCount >= GetArg("-limitfreerelay", 15)*10*1000)
788  return error("CTxMemPool::accept() : free transaction rejected by rate limiter");
789  if (fDebug)
790  printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
791  dFreeCount += nSize;
792  }
793 
794  // Check against previous transactions
795  // This is done last to help prevent CPU exhaustion denial-of-service attacks.
796  if (!tx.CheckInputs(state, view, true, SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC))
797  {
798  return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().c_str());
799  }
800  }
801 
802  // Store transaction in memory
803  {
804  LOCK(cs);
805  if (ptxOld)
806  {
807  printf("CTxMemPool::accept() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
808  remove(*ptxOld);
809  }
810  addUnchecked(hash, tx);
811  }
812 
814  // If updated, erase old tx from wallet
815  if (ptxOld)
816  EraseFromWallets(ptxOld->GetHash());
817  SyncWithWallets(hash, tx, NULL, true);
818 
819  return true;
820 }
821 
822 bool CTransaction::AcceptToMemoryPool(CValidationState &state, bool fCheckInputs, bool fLimitFree, bool* pfMissingInputs)
823 {
824  try {
825  return mempool.accept(state, *this, fCheckInputs, fLimitFree, pfMissingInputs);
826  } catch(std::runtime_error &e) {
827  return state.Abort(_("System error: ") + e.what());
828  }
829 }
830 
831 bool CTxMemPool::addUnchecked(const uint256& hash, const CTransaction &tx)
832 {
833  // Add to memory pool without checking anything. Don't call this directly,
834  // call CTxMemPool::accept to properly check the transaction first.
835  {
836  mapTx[hash] = tx;
837  for (unsigned int i = 0; i < tx.vin.size(); i++)
838  mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i);
840  }
841  return true;
842 }
843 
844 
845 bool CTxMemPool::remove(const CTransaction &tx, bool fRecursive)
846 {
847  // Remove transaction from memory pool
848  {
849  LOCK(cs);
850  uint256 hash = tx.GetHash();
851  if (fRecursive) {
852  for (unsigned int i = 0; i < tx.vout.size(); i++) {
853  std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(COutPoint(hash, i));
854  if (it != mapNextTx.end())
855  remove(*it->second.ptx, true);
856  }
857  }
858  if (mapTx.count(hash))
859  {
860  BOOST_FOREACH(const CTxIn& txin, tx.vin)
861  mapNextTx.erase(txin.prevout);
862  mapTx.erase(hash);
864  }
865  }
866  return true;
867 }
868 
870 {
871  // Remove transactions which depend on inputs of tx, recursively
872  LOCK(cs);
873  BOOST_FOREACH(const CTxIn &txin, tx.vin) {
874  std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(txin.prevout);
875  if (it != mapNextTx.end()) {
876  const CTransaction &txConflict = *it->second.ptx;
877  if (txConflict != tx)
878  remove(txConflict, true);
879  }
880  }
881  return true;
882 }
883 
885 {
886  LOCK(cs);
887  mapTx.clear();
888  mapNextTx.clear();
890 }
891 
892 void CTxMemPool::queryHashes(std::vector<uint256>& vtxid)
893 {
894  vtxid.clear();
895 
896  LOCK(cs);
897  vtxid.reserve(mapTx.size());
898  for (map<uint256, CTransaction>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
899  vtxid.push_back((*mi).first);
900 }
901 
902 
903 
904 
906 {
907  if (hashBlock == 0 || nIndex == -1)
908  return 0;
909 
910  // Find the block it claims to be in
911  map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
912  if (mi == mapBlockIndex.end())
913  return 0;
914  CBlockIndex* pindex = (*mi).second;
915  if (!pindex || !pindex->IsInMainChain())
916  return 0;
917 
918  // Make sure the merkle branch connects to this block
919  if (!fMerkleVerified)
920  {
922  return 0;
923  fMerkleVerified = true;
924  }
925 
926  pindexRet = pindex;
927  return pindexBest->nHeight - pindex->nHeight + 1;
928 }
929 
930 
932 {
933  if (!IsCoinBase())
934  return 0;
935  return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
936 }
937 
938 
939 bool CMerkleTx::AcceptToMemoryPool(bool fCheckInputs, bool fLimitFree)
940 {
942  return CTransaction::AcceptToMemoryPool(state, fCheckInputs, fLimitFree);
943 }
944 
945 
946 
947 bool CWalletTx::AcceptWalletTransaction(bool fCheckInputs)
948 {
949  {
950  LOCK(mempool.cs);
951  // Add previous supporting transactions first
952  BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
953  {
954  if (!tx.IsCoinBase())
955  {
956  uint256 hash = tx.GetHash();
957  if (!mempool.exists(hash) && pcoinsTip->HaveCoins(hash))
958  tx.AcceptToMemoryPool(fCheckInputs, false);
959  }
960  }
961  return AcceptToMemoryPool(fCheckInputs, false);
962  }
963  return false;
964 }
965 
966 
967 // Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock
968 bool GetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock, bool fAllowSlow)
969 {
970  CBlockIndex *pindexSlow = NULL;
971  {
972  LOCK(cs_main);
973  {
974  LOCK(mempool.cs);
975  if (mempool.exists(hash))
976  {
977  txOut = mempool.lookup(hash);
978  return true;
979  }
980  }
981 
982  if (fTxIndex) {
983  CDiskTxPos postx;
984  if (pblocktree->ReadTxIndex(hash, postx)) {
985  CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);
986  CBlockHeader header;
987  try {
988  file >> header;
989  fseek(file, postx.nTxOffset, SEEK_CUR);
990  file >> txOut;
991  } catch (std::exception &e) {
992  return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
993  }
994  hashBlock = header.GetHash();
995  if (txOut.GetHash() != hash)
996  return error("%s() : txid mismatch", __PRETTY_FUNCTION__);
997  return true;
998  }
999  }
1000 
1001  if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
1002  int nHeight = -1;
1003  {
1004  CCoinsViewCache &view = *pcoinsTip;
1005  CCoins coins;
1006  if (view.GetCoins(hash, coins))
1007  nHeight = coins.nHeight;
1008  }
1009  if (nHeight > 0)
1010  pindexSlow = FindBlockByHeight(nHeight);
1011  }
1012  }
1013 
1014  if (pindexSlow) {
1015  CBlock block;
1016  if (block.ReadFromDisk(pindexSlow)) {
1017  BOOST_FOREACH(const CTransaction &tx, block.vtx) {
1018  if (tx.GetHash() == hash) {
1019  txOut = tx;
1020  hashBlock = pindexSlow->GetBlockHash();
1021  return true;
1022  }
1023  }
1024  }
1025  }
1026 
1027  return false;
1028 }
1029 
1030 
1031 
1032 
1033 
1034 
1036 //
1037 // CBlock and CBlockIndex
1038 //
1039 
1040 static CBlockIndex* pblockindexFBBHLast;
1042 {
1043  CBlockIndex *pblockindex;
1044  if (nHeight < nBestHeight / 2)
1045  pblockindex = pindexGenesisBlock;
1046  else
1047  pblockindex = pindexBest;
1048  if (pblockindexFBBHLast && abs(nHeight - pblockindex->nHeight) > abs(nHeight - pblockindexFBBHLast->nHeight))
1049  pblockindex = pblockindexFBBHLast;
1050  while (pblockindex->nHeight > nHeight)
1051  pblockindex = pblockindex->pprev;
1052  while (pblockindex->nHeight < nHeight)
1053  pblockindex = pblockindex->pnext;
1054  pblockindexFBBHLast = pblockindex;
1055  return pblockindex;
1056 }
1057 
1059 {
1060  if (!ReadFromDisk(pindex->GetBlockPos()))
1061  return false;
1062  if (GetHash() != pindex->GetBlockHash())
1063  return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
1064  return true;
1065 }
1066 
1067 uint256 static GetOrphanRoot(const CBlockHeader* pblock)
1068 {
1069  // Work back to the first block in the orphan chain
1070  while (mapOrphanBlocks.count(pblock->hashPrevBlock))
1071  pblock = mapOrphanBlocks[pblock->hashPrevBlock];
1072  return pblock->GetHash();
1073 }
1074 
1075 int64 static GetBlockValue(int nHeight, int64 nFees)
1076 {
1077  int64 nSubsidy = 200 * COIN;
1078 
1079  if(nHeight >= nForkThree || (fTestNet))
1080  nSubsidy = 80 * COIN;
1081 
1082  // Halving subsidy happens every 2,100,000 blocks. The code below takes account for the
1083  // fact that the first 204,639 blocks took 2.5 minutes and after changed to 1 minute.
1084  nSubsidy >>= (nHeight + 306960) / 2100000;
1085 
1086  return nSubsidy + nFees;
1087 }
1088 
1089 int nTargetTimespan = 3.5 * 24 * 60 * 60; // 3.5 days
1090 int nTargetSpacing = 2.5 * 60; // 2.5 minutes
1091 
1092 unsigned int static GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock)
1093 {
1094  unsigned int nProofOfWorkLimit = bnProofOfWorkLimit.GetCompact();
1095 
1096  // Genesis block
1097  if (pindexLast == NULL)
1098  return nProofOfWorkLimit;
1099 
1100  // The next block
1101  int nHeight = pindexLast->nHeight + 1;
1102 
1103  if (nHeight >= nForkOne)
1104  nTargetTimespan = (7 * 24 * 60 * 60) / 8; // 7/8 days
1105 
1106  if (nHeight >= nForkTwo)
1107  nTargetTimespan = (7 * 24 * 60 * 60) / 32; // 7/32 days
1108 
1109  if (nHeight >= nForkThree || fTestNet) {
1110  nTargetTimespan = 60; // 1 minute timespan
1111  nTargetSpacing = 60; // 1 minute block
1112  }
1113 
1114  // 2016 blocks initial, 504 after the 1st, 126 after the 2nd hard fork, 15 after the 3rd hard fork
1115  int nInterval = nTargetTimespan / nTargetSpacing;
1116 
1117  bool fHardFork = (nHeight == nForkOne) || (nHeight == nForkTwo) || (nHeight == nForkThree);
1118  if(fTestNet) fHardFork = false;
1119 
1120  // Difficulty rules regular blocks
1121  if((nHeight % nInterval != 0) && !(fHardFork) && (nHeight < nForkThree)) {
1122 
1123  // Special difficulty rule for testnet:
1124  if (fTestNet)
1125  {
1126  // If the new block's timestamp is more than 2* 2.5 minutes
1127  // then allow mining of a min-difficulty block.
1128  if (pblock->nTime > pindexLast->nTime + nTargetSpacing*2)
1129  return nProofOfWorkLimit;
1130  else
1131  {
1132  // Return the last non-special-min-difficulty-rules-block
1133  const CBlockIndex* pindex = pindexLast;
1134  while (pindex->pprev && pindex->nHeight % nInterval != 0 && pindex->nBits == nProofOfWorkLimit)
1135  pindex = pindex->pprev;
1136  return pindex->nBits;
1137  }
1138  }
1139 
1140  return pindexLast->nBits;
1141  }
1142 
1143  // The 1st retarget after genesis
1144  if(nInterval >= nHeight) nInterval = nHeight - 1;
1145 
1146  // Go back by nInterval
1147  const CBlockIndex* pindexFirst = pindexLast;
1148  for(int i = 0; pindexFirst && i < nInterval; i++)
1149  pindexFirst = pindexFirst->pprev;
1150  assert(pindexFirst);
1151 
1152  int nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();
1153 
1154  printf("RETARGET: nActualTimespan = %d before bounds\n", nActualTimespan);
1155 
1156  // Additional averaging over 4x nInterval window
1157  if((nHeight >= nForkTwo) && (nHeight < nForkThree)) {
1158  nInterval *= 4;
1159 
1160  const CBlockIndex* pindexFirst = pindexLast;
1161  for(int i = 0; pindexFirst && i < nInterval; i++)
1162  pindexFirst = pindexFirst->pprev;
1163 
1164  int nActualTimespanLong =
1165  (pindexLast->GetBlockTime() - pindexFirst->GetBlockTime())/4;
1166 
1167  // Average between short and long windows
1168  int nActualTimespanAvg = (nActualTimespan + nActualTimespanLong)/2;
1169 
1170  // Apply .25 damping
1171  nActualTimespan = nActualTimespanAvg + 3*nTargetTimespan;
1172  nActualTimespan /= 4;
1173 
1174  printf("RETARGET: nActualTimespanLong = %d, nActualTimeSpanAvg = %d, nActualTimespan (damped) = %d\n",
1175  nActualTimespanLong, nActualTimespanAvg, nActualTimespan);
1176  }
1177 
1178  // Additional averaging over 15, 120 and 480 block window
1179  if((nHeight >= nForkThree) || fTestNet) {
1180 
1181  nInterval *= 480;
1182 
1183  int pindexFirstShortTime = 0;
1184  int pindexFirstMediumTime = 0;
1185  const CBlockIndex* pindexFirstLong = pindexLast;
1186  for(int i = 0; pindexFirstLong && i < nInterval && i < nHeight - 1; i++) { // i < nHeight - 1 special rule for testnet
1187  pindexFirstLong = pindexFirstLong->pprev;
1188  if (i == 14) {
1189  pindexFirstShortTime = pindexFirstLong->GetBlockTime();
1190  }
1191  if (i == 119) {
1192  pindexFirstMediumTime = pindexFirstLong->GetBlockTime();
1193  }
1194  }
1195 
1196  int nActualTimespanShort =
1197  (pindexLast->GetBlockTime() - pindexFirstShortTime)/15;
1198 
1199  int nActualTimespanMedium =
1200  (pindexLast->GetBlockTime() - pindexFirstMediumTime)/120;
1201 
1202  int nActualTimespanLong =
1203  (pindexLast->GetBlockTime() - pindexFirstLong->GetBlockTime())/480;
1204 
1205  int nActualTimespanAvg = 0;
1206  nActualTimespanAvg = (nActualTimespanShort + nActualTimespanMedium + nActualTimespanLong)/3;
1207 
1208  // Apply .25 damping
1209  nActualTimespan = nActualTimespanAvg + 3*nTargetTimespan;
1210  nActualTimespan /= 4;
1211 
1212  printf("RETARGET: nActualTimespanShort = %d, nActualTimespanMedium = %d, nActualTimespanLong = %d, nActualTimeSpanAvg = %d, nActualTimespan (damped) = %d\n",
1213  nActualTimespanShort, nActualTimespanMedium, nActualTimespanLong, nActualTimespanAvg, nActualTimespan);
1214  }
1215 
1216  // The initial settings (4.0 difficulty limiter)
1217  int nActualTimespanMax = nTargetTimespan*4;
1218  int nActualTimespanMin = nTargetTimespan/4;
1219 
1220  // The 1st hard fork (1.4142857 aka 41% difficulty limiter)
1221  if(nHeight >= nForkOne) {
1222  nActualTimespanMax = nTargetTimespan*99/70;
1223  nActualTimespanMin = nTargetTimespan*70/99;
1224  }
1225 
1226  // The 2nd hard fork (1.0905077 aka 9% difficulty limiter)
1227  if(nHeight >= nForkTwo || fTestNet) {
1228  nActualTimespanMax = nTargetTimespan*494/453;
1229  nActualTimespanMin = nTargetTimespan*453/494;
1230  }
1231 
1232  if(nActualTimespan < nActualTimespanMin) nActualTimespan = nActualTimespanMin;
1233  if(nActualTimespan > nActualTimespanMax) nActualTimespan = nActualTimespanMax;
1234 
1235  printf("RETARGET: nActualTimespan = %d after bounds\n", nActualTimespan);
1236  printf("RETARGET: nTargetTimespan = %d, nTargetTimespan/nActualTimespan = %.4f\n", nTargetTimespan, (float) nTargetTimespan/nActualTimespan);
1237 
1238  // Retarget
1239  CBigNum bnNew;
1240  bnNew.SetCompact(pindexLast->nBits);
1241  bnNew *= nActualTimespan;
1242  bnNew /= nTargetTimespan;
1243 
1244  if (bnNew > bnProofOfWorkLimit)
1245  bnNew = bnProofOfWorkLimit;
1246 
1247  printf("GetNextWorkRequired RETARGET\n");
1248  printf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());
1249  printf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());
1250 
1251  return bnNew.GetCompact();
1252 }
1253 
1254 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
1255 {
1256  CBigNum bnTarget;
1257  bnTarget.SetCompact(nBits);
1258 
1259  // Check range
1260  if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
1261  return error("CheckProofOfWork() : nBits below minimum work");
1262 
1263  // Check proof of work matches claimed amount
1264  if (hash > bnTarget.getuint256())
1265  return error("CheckProofOfWork() : hash doesn't match nBits");
1266 
1267  return true;
1268 }
1269 
1270 // Return maximum amount of blocks that other nodes claim to have
1272 {
1273  return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
1274 }
1275 
1277 {
1278  if (pindexBest == NULL || fImporting || fReindex || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
1279  return true;
1280  static int64 nLastUpdate;
1281  static CBlockIndex* pindexLastBest;
1282  if (pindexBest != pindexLastBest)
1283  {
1284  pindexLastBest = pindexBest;
1285  nLastUpdate = GetTime();
1286  }
1287  return (GetTime() - nLastUpdate < 10 &&
1288  pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
1289 }
1290 
1291 void static InvalidChainFound(CBlockIndex* pindexNew)
1292 {
1293  if (pindexNew->nChainWork > nBestInvalidWork)
1294  {
1295  nBestInvalidWork = pindexNew->nChainWork;
1296  pblocktree->WriteBestInvalidWork(CBigNum(nBestInvalidWork));
1298  }
1299  printf("InvalidChainFound: invalid block=%s height=%d log2_work=%.8g date=%s\n",
1300  pindexNew->GetBlockHash().ToString().c_str(), pindexNew->nHeight,
1301  log(pindexNew->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
1302  pindexNew->GetBlockTime()).c_str());
1303  printf("InvalidChainFound: current best=%s height=%d log2_work=%.8g date=%s\n",
1304  hashBestChain.ToString().c_str(), nBestHeight, log(nBestChainWork.getdouble())/log(2.0),
1305  DateTimeStrFormat("%Y-%m-%d %H:%M:%S", pindexBest->GetBlockTime()).c_str());
1306  if (pindexBest && nBestInvalidWork > nBestChainWork + (pindexBest->GetBlockWork() * 6).getuint256())
1307  printf("InvalidChainFound: Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.\n");
1308 }
1309 
1310 void static InvalidBlockFound(CBlockIndex *pindex) {
1311  pindex->nStatus |= BLOCK_FAILED_VALID;
1312  pblocktree->WriteBlockIndex(CDiskBlockIndex(pindex));
1313  setBlockIndexValid.erase(pindex);
1314  InvalidChainFound(pindex);
1315  if (pindex->pnext) {
1316  CValidationState stateDummy;
1317  ConnectBestBlock(stateDummy); // reorganise away from the failed block
1318  }
1319 }
1320 
1322  do {
1323  CBlockIndex *pindexNewBest;
1324 
1325  {
1326  std::set<CBlockIndex*,CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexValid.rbegin();
1327  if (it == setBlockIndexValid.rend())
1328  return true;
1329  pindexNewBest = *it;
1330  }
1331 
1332  if (pindexNewBest == pindexBest || (pindexBest && pindexNewBest->nChainWork == pindexBest->nChainWork))
1333  return true; // nothing to do
1334 
1335  // check ancestry
1336  CBlockIndex *pindexTest = pindexNewBest;
1337  std::vector<CBlockIndex*> vAttach;
1338  do {
1339  if (pindexTest->nStatus & BLOCK_FAILED_MASK) {
1340  // mark descendants failed
1341  CBlockIndex *pindexFailed = pindexNewBest;
1342  while (pindexTest != pindexFailed) {
1343  pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
1344  setBlockIndexValid.erase(pindexFailed);
1345  pblocktree->WriteBlockIndex(CDiskBlockIndex(pindexFailed));
1346  pindexFailed = pindexFailed->pprev;
1347  }
1348  InvalidChainFound(pindexNewBest);
1349  break;
1350  }
1351 
1352  if (pindexBest == NULL || pindexTest->nChainWork > pindexBest->nChainWork)
1353  vAttach.push_back(pindexTest);
1354 
1355  if (pindexTest->pprev == NULL || pindexTest->pnext != NULL) {
1356  reverse(vAttach.begin(), vAttach.end());
1357  BOOST_FOREACH(CBlockIndex *pindexSwitch, vAttach) {
1358  boost::this_thread::interruption_point();
1359  try {
1360  if (!SetBestChain(state, pindexSwitch))
1361  return false;
1362  } catch(std::runtime_error &e) {
1363  return state.Abort(_("System error: ") + e.what());
1364  }
1365  }
1366  return true;
1367  }
1368  pindexTest = pindexTest->pprev;
1369  } while(true);
1370  } while(true);
1371 }
1372 
1373 void CBlockHeader::UpdateTime(const CBlockIndex* pindexPrev)
1374 {
1375  nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
1376 
1377  // Updating time can change work required on testnet:
1378  if (fTestNet)
1379  nBits = GetNextWorkRequired(pindexPrev, this);
1380 }
1381 
1382 
1383 
1384 
1385 
1386 
1387 
1388 
1389 
1390 
1391 
1393 {
1394  const CCoins &coins = view.GetCoins(input.prevout.hash);
1395  assert(coins.IsAvailable(input.prevout.n));
1396  return coins.vout[input.prevout.n];
1397 }
1398 
1400 {
1401  if (IsCoinBase())
1402  return 0;
1403 
1404  int64 nResult = 0;
1405  for (unsigned int i = 0; i < vin.size(); i++)
1406  nResult += GetOutputFor(vin[i], inputs).nValue;
1407 
1408  return nResult;
1409 }
1410 
1412 {
1413  if (IsCoinBase())
1414  return 0;
1415 
1416  unsigned int nSigOps = 0;
1417  for (unsigned int i = 0; i < vin.size(); i++)
1418  {
1419  const CTxOut &prevout = GetOutputFor(vin[i], inputs);
1420  if (prevout.scriptPubKey.IsPayToScriptHash())
1421  nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig);
1422  }
1423  return nSigOps;
1424 }
1425 
1426 void CTransaction::UpdateCoins(CValidationState &state, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight, const uint256 &txhash) const
1427 {
1428  // mark inputs spent
1429  if (!IsCoinBase()) {
1430  BOOST_FOREACH(const CTxIn &txin, vin) {
1431  CCoins &coins = inputs.GetCoins(txin.prevout.hash);
1432  CTxInUndo undo;
1433  assert(coins.Spend(txin.prevout, undo));
1434  txundo.vprevout.push_back(undo);
1435  }
1436  }
1437 
1438  // add outputs
1439  assert(inputs.SetCoins(txhash, CCoins(*this, nHeight)));
1440 }
1441 
1443 {
1444  if (!IsCoinBase()) {
1445  // first check whether information about the prevout hash is available
1446  for (unsigned int i = 0; i < vin.size(); i++) {
1447  const COutPoint &prevout = vin[i].prevout;
1448  if (!inputs.HaveCoins(prevout.hash))
1449  return false;
1450  }
1451 
1452  // then check whether the actual outputs are available
1453  for (unsigned int i = 0; i < vin.size(); i++) {
1454  const COutPoint &prevout = vin[i].prevout;
1455  const CCoins &coins = inputs.GetCoins(prevout.hash);
1456  if (!coins.IsAvailable(prevout.n))
1457  return false;
1458  }
1459  }
1460  return true;
1461 }
1462 
1464  const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1465  if (!VerifyScript(scriptSig, scriptPubKey, *ptxTo, nIn, nFlags, nHashType))
1466  return error("CScriptCheck() : %s VerifySignature failed", ptxTo->GetHash().ToString().c_str());
1467  return true;
1468 }
1469 
1470 bool VerifySignature(const CCoins& txFrom, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType)
1471 {
1472  return CScriptCheck(txFrom, txTo, nIn, flags, nHashType)();
1473 }
1474 
1475 bool CTransaction::CheckInputs(CValidationState &state, CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, std::vector<CScriptCheck> *pvChecks) const
1476 {
1477  if (!IsCoinBase())
1478  {
1479  if (pvChecks)
1480  pvChecks->reserve(vin.size());
1481 
1482  // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1483  // for an attacker to attempt to split the network.
1484  if (!HaveInputs(inputs))
1485  return state.Invalid(error("CheckInputs() : %s inputs unavailable", GetHash().ToString().c_str()));
1486 
1487  // While checking, GetBestBlock() refers to the parent block.
1488  // This is also true for mempool checks.
1489  int nSpendHeight = inputs.GetBestBlock()->nHeight + 1;
1490  int64 nValueIn = 0;
1491  int64 nFees = 0;
1492  for (unsigned int i = 0; i < vin.size(); i++)
1493  {
1494  const COutPoint &prevout = vin[i].prevout;
1495  const CCoins &coins = inputs.GetCoins(prevout.hash);
1496 
1497  // If prev is coinbase, check that it's matured
1498  if (coins.IsCoinBase()) {
1499  if (nSpendHeight - coins.nHeight < COINBASE_MATURITY)
1500  return state.Invalid(error("CheckInputs() : tried to spend coinbase at depth %d", nSpendHeight - coins.nHeight));
1501  }
1502 
1503  // Check for negative or overflow input values
1504  nValueIn += coins.vout[prevout.n].nValue;
1505  if (!MoneyRange(coins.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1506  return state.DoS(100, error("CheckInputs() : txin values out of range"));
1507 
1508  }
1509 
1510  if (nValueIn < GetValueOut())
1511  return state.DoS(100, error("CheckInputs() : %s value in < value out", GetHash().ToString().c_str()));
1512 
1513  // Tally transaction fees
1514  int64 nTxFee = nValueIn - GetValueOut();
1515  if (nTxFee < 0)
1516  return state.DoS(100, error("CheckInputs() : %s nTxFee < 0", GetHash().ToString().c_str()));
1517  nFees += nTxFee;
1518  if (!MoneyRange(nFees))
1519  return state.DoS(100, error("CheckInputs() : nFees out of range"));
1520 
1521  // The first loop above does all the inexpensive checks.
1522  // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1523  // Helps prevent CPU exhaustion attacks.
1524 
1525  // Skip ECDSA signature verification when connecting blocks
1526  // before the last block chain checkpoint. This is safe because block merkle hashes are
1527  // still computed and checked, and any change will be caught at the next checkpoint.
1528  if (fScriptChecks) {
1529  for (unsigned int i = 0; i < vin.size(); i++) {
1530  const COutPoint &prevout = vin[i].prevout;
1531  const CCoins &coins = inputs.GetCoins(prevout.hash);
1532 
1533  // Verify signature
1534  CScriptCheck check(coins, *this, i, flags, 0);
1535  if (pvChecks) {
1536  pvChecks->push_back(CScriptCheck());
1537  check.swap(pvChecks->back());
1538  } else if (!check()) {
1539  if (flags & SCRIPT_VERIFY_STRICTENC) {
1540  // For now, check whether the failure was caused by non-canonical
1541  // encodings or not; if so, don't trigger DoS protection.
1542  CScriptCheck check(coins, *this, i, flags & (~SCRIPT_VERIFY_STRICTENC), 0);
1543  if (check())
1544  return state.Invalid();
1545  }
1546  return state.DoS(100,false);
1547  }
1548  }
1549  }
1550  }
1551 
1552  return true;
1553 }
1554 
1555 
1556 
1557 
1559 {
1560  assert(pindex == view.GetBestBlock());
1561 
1562  if (pfClean)
1563  *pfClean = false;
1564 
1565  bool fClean = true;
1566 
1567  CBlockUndo blockUndo;
1568  CDiskBlockPos pos = pindex->GetUndoPos();
1569  if (pos.IsNull())
1570  return error("DisconnectBlock() : no undo data available");
1571  if (!blockUndo.ReadFromDisk(pos, pindex->pprev->GetBlockHash()))
1572  return error("DisconnectBlock() : failure reading undo data");
1573 
1574  if (blockUndo.vtxundo.size() + 1 != vtx.size())
1575  return error("DisconnectBlock() : block and undo data inconsistent");
1576 
1577  // undo transactions in reverse order
1578  for (int i = vtx.size() - 1; i >= 0; i--) {
1579  const CTransaction &tx = vtx[i];
1580  uint256 hash = tx.GetHash();
1581 
1582  // check that all outputs are available
1583  if (!view.HaveCoins(hash)) {
1584  fClean = fClean && error("DisconnectBlock() : outputs still spent? database corrupted");
1585  view.SetCoins(hash, CCoins());
1586  }
1587  CCoins &outs = view.GetCoins(hash);
1588 
1589  CCoins outsBlock = CCoins(tx, pindex->nHeight);
1590  // The CCoins serialization does not serialize negative numbers.
1591  // No network rules currently depend on the version here, so an inconsistency is harmless
1592  // but it must be corrected before txout nversion ever influences a network rule.
1593  if (outsBlock.nVersion < 0)
1594  outs.nVersion = outsBlock.nVersion;
1595  if (outs != outsBlock)
1596  fClean = fClean && error("DisconnectBlock() : added transaction mismatch? database corrupted");
1597 
1598  // remove outputs
1599  outs = CCoins();
1600 
1601  // restore inputs
1602  if (i > 0) { // not coinbases
1603  const CTxUndo &txundo = blockUndo.vtxundo[i-1];
1604  if (txundo.vprevout.size() != tx.vin.size())
1605  return error("DisconnectBlock() : transaction and undo data inconsistent");
1606  for (unsigned int j = tx.vin.size(); j-- > 0;) {
1607  const COutPoint &out = tx.vin[j].prevout;
1608  const CTxInUndo &undo = txundo.vprevout[j];
1609  CCoins coins;
1610  view.GetCoins(out.hash, coins); // this can fail if the prevout was already entirely spent
1611  if (undo.nHeight != 0) {
1612  // undo data contains height: this is the last output of the prevout tx being spent
1613  if (!coins.IsPruned())
1614  fClean = fClean && error("DisconnectBlock() : undo data overwriting existing transaction");
1615  coins = CCoins();
1616  coins.fCoinBase = undo.fCoinBase;
1617  coins.nHeight = undo.nHeight;
1618  coins.nVersion = undo.nVersion;
1619  } else {
1620  if (coins.IsPruned())
1621  fClean = fClean && error("DisconnectBlock() : undo data adding output to missing transaction");
1622  }
1623  if (coins.IsAvailable(out.n))
1624  fClean = fClean && error("DisconnectBlock() : undo data overwriting existing output");
1625  if (coins.vout.size() < out.n+1)
1626  coins.vout.resize(out.n+1);
1627  coins.vout[out.n] = undo.txout;
1628  if (!view.SetCoins(out.hash, coins))
1629  return error("DisconnectBlock() : cannot restore coin inputs");
1630  }
1631  }
1632  }
1633 
1634  // move best block pointer to prevout block
1635  view.SetBestBlock(pindex->pprev);
1636 
1637  if (pfClean) {
1638  *pfClean = fClean;
1639  return true;
1640  } else {
1641  return fClean;
1642  }
1643 }
1644 
1645 void static FlushBlockFile(bool fFinalize = false)
1646 {
1648 
1649  CDiskBlockPos posOld(nLastBlockFile, 0);
1650 
1651  FILE *fileOld = OpenBlockFile(posOld);
1652  if (fileOld) {
1653  if (fFinalize)
1655  FileCommit(fileOld);
1656  fclose(fileOld);
1657  }
1658 
1659  fileOld = OpenUndoFile(posOld);
1660  if (fileOld) {
1661  if (fFinalize)
1663  FileCommit(fileOld);
1664  fclose(fileOld);
1665  }
1666 }
1667 
1668 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
1669 
1670 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
1671 
1673  RenameThread("bitcoin-scriptch");
1674  scriptcheckqueue.Thread();
1675 }
1676 
1678 {
1679  // Check it again in case a previous version let a bad block in
1680  if (!CheckBlock(state, !fJustCheck, !fJustCheck))
1681  return false;
1682 
1683  // verify that the view's current state corresponds to the previous block
1684  assert(pindex->pprev == view.GetBestBlock());
1685 
1686  // Special case for the genesis block, skipping connection of its transactions
1687  // (its coinbase is unspendable)
1688  if (GetHash() == hashGenesisBlock) {
1689  view.SetBestBlock(pindex);
1690  pindexGenesisBlock = pindex;
1691  return true;
1692  }
1693 
1694  bool fScriptChecks = pindex->nHeight >= Checkpoints::GetTotalBlocksEstimate();
1695 
1696  // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1697  // unless those are already completely spent.
1698  // If such overwrites are allowed, coinbases and transactions depending upon those
1699  // can be duplicated to remove the ability to spend the first instance -- even after
1700  // being sent to another address.
1701  // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1702  // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1703  // already refuses previously-known transaction ids entirely.
1704  // This rule was originally applied all blocks whose timestamp was after October 1, 2012, 0:00 UTC.
1705  // Now that the whole chain is irreversibly beyond that time it is applied to all blocks,
1706  // this prevents exploiting the issue against nodes in their initial block download.
1707  bool fEnforceBIP30 = true;
1708 
1709  if (fEnforceBIP30) {
1710  for (unsigned int i=0; i<vtx.size(); i++) {
1711  uint256 hash = GetTxHash(i);
1712  if (view.HaveCoins(hash) && !view.GetCoins(hash).IsPruned())
1713  return state.DoS(100, error("ConnectBlock() : tried to overwrite transaction"));
1714  }
1715  }
1716 
1717  // BIP16 didn't become active until Oct 1 2012
1718  int64 nBIP16SwitchTime = 1349049600;
1719  bool fStrictPayToScriptHash = (pindex->nTime >= nBIP16SwitchTime);
1720 
1721  unsigned int flags = SCRIPT_VERIFY_NOCACHE |
1722  (fStrictPayToScriptHash ? SCRIPT_VERIFY_P2SH : SCRIPT_VERIFY_NONE);
1723 
1724  CBlockUndo blockundo;
1725 
1726  CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
1727 
1728  int64 nStart = GetTimeMicros();
1729  int64 nFees = 0;
1730  int nInputs = 0;
1731  unsigned int nSigOps = 0;
1732  CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(vtx.size()));
1733  std::vector<std::pair<uint256, CDiskTxPos> > vPos;
1734  vPos.reserve(vtx.size());
1735  for (unsigned int i=0; i<vtx.size(); i++)
1736  {
1737  const CTransaction &tx = vtx[i];
1738 
1739  nInputs += tx.vin.size();
1740  nSigOps += tx.GetLegacySigOpCount();
1741  if (nSigOps > MAX_BLOCK_SIGOPS)
1742  return state.DoS(100, error("ConnectBlock() : too many sigops"));
1743 
1744  if (!tx.IsCoinBase())
1745  {
1746  if (!tx.HaveInputs(view))
1747  return state.DoS(100, error("ConnectBlock() : inputs missing/spent"));
1748 
1749  if (fStrictPayToScriptHash)
1750  {
1751  // Add in sigops done by pay-to-script-hash inputs;
1752  // this is to prevent a "rogue miner" from creating
1753  // an incredibly-expensive-to-validate block.
1754  nSigOps += tx.GetP2SHSigOpCount(view);
1755  if (nSigOps > MAX_BLOCK_SIGOPS)
1756  return state.DoS(100, error("ConnectBlock() : too many sigops"));
1757  }
1758 
1759  nFees += tx.GetValueIn(view)-tx.GetValueOut();
1760 
1761  std::vector<CScriptCheck> vChecks;
1762  if (!tx.CheckInputs(state, view, fScriptChecks, flags, nScriptCheckThreads ? &vChecks : NULL))
1763  return false;
1764  control.Add(vChecks);
1765  }
1766 
1767  CTxUndo txundo;
1768  tx.UpdateCoins(state, view, txundo, pindex->nHeight, GetTxHash(i));
1769  if (!tx.IsCoinBase())
1770  blockundo.vtxundo.push_back(txundo);
1771 
1772  vPos.push_back(std::make_pair(GetTxHash(i), pos));
1773  pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
1774  }
1775  int64 nTime = GetTimeMicros() - nStart;
1776  if (fBenchmark)
1777  printf("- Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin)\n", (unsigned)vtx.size(), 0.001 * nTime, 0.001 * nTime / vtx.size(), nInputs <= 1 ? 0 : 0.001 * nTime / (nInputs-1));
1778 
1779  if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))
1780  return state.DoS(100, error("ConnectBlock() : coinbase pays too much (actual=%"PRI64d" vs limit=%"PRI64d")", vtx[0].GetValueOut(), GetBlockValue(pindex->nHeight, nFees)));
1781 
1782  // No more blocks with bogus reward accepted
1783  if((fTestNet || (pindex->nHeight >= nForkThree)) &&
1784  (vtx[0].GetValueOut() != GetBlockValue(pindex->nHeight, nFees)))
1785  return false;
1786 
1787  if (!control.Wait())
1788  return state.DoS(100, false);
1789  int64 nTime2 = GetTimeMicros() - nStart;
1790  if (fBenchmark)
1791  printf("- Verify %u txins: %.2fms (%.3fms/txin)\n", nInputs - 1, 0.001 * nTime2, nInputs <= 1 ? 0 : 0.001 * nTime2 / (nInputs-1));
1792 
1793  if (fJustCheck)
1794  return true;
1795 
1796  // Write undo information to disk
1797  if (pindex->GetUndoPos().IsNull() || (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS)
1798  {
1799  if (pindex->GetUndoPos().IsNull()) {
1800  CDiskBlockPos pos;
1801  if (!FindUndoPos(state, pindex->nFile, pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40))
1802  return error("ConnectBlock() : FindUndoPos failed");
1803  if (!blockundo.WriteToDisk(pos, pindex->pprev->GetBlockHash()))
1804  return state.Abort(_("Failed to write undo data"));
1805 
1806  // update nUndoPos in block index
1807  pindex->nUndoPos = pos.nPos;
1808  pindex->nStatus |= BLOCK_HAVE_UNDO;
1809  }
1810 
1811  pindex->nStatus = (pindex->nStatus & ~BLOCK_VALID_MASK) | BLOCK_VALID_SCRIPTS;
1812 
1813  CDiskBlockIndex blockindex(pindex);
1814  if (!pblocktree->WriteBlockIndex(blockindex))
1815  return state.Abort(_("Failed to write block index"));
1816  }
1817 
1818  if (fTxIndex)
1819  if (!pblocktree->WriteTxIndex(vPos))
1820  return state.Abort(_("Failed to write transaction index"));
1821 
1822  // add this block to the view's block chain
1823  assert(view.SetBestBlock(pindex));
1824 
1825  // Watch for transactions paying to me
1826  for (unsigned int i=0; i<vtx.size(); i++)
1827  SyncWithWallets(GetTxHash(i), vtx[i], this, true);
1828 
1829  return true;
1830 }
1831 
1833 {
1834  // All modifications to the coin state will be done in this cache.
1835  // Only when all have succeeded, we push it to pcoinsTip.
1836  CCoinsViewCache view(*pcoinsTip, true);
1837 
1838  // Find the fork (typically, there is none)
1839  CBlockIndex* pfork = view.GetBestBlock();
1840  CBlockIndex* plonger = pindexNew;
1841  while (pfork && pfork != plonger)
1842  {
1843  while (plonger->nHeight > pfork->nHeight) {
1844  plonger = plonger->pprev;
1845  assert(plonger != NULL);
1846  }
1847  if (pfork == plonger)
1848  break;
1849  pfork = pfork->pprev;
1850  assert(pfork != NULL);
1851  }
1852 
1853  // List of what to disconnect (typically nothing)
1854  vector<CBlockIndex*> vDisconnect;
1855  for (CBlockIndex* pindex = view.GetBestBlock(); pindex != pfork; pindex = pindex->pprev)
1856  vDisconnect.push_back(pindex);
1857 
1858  // List of what to connect (typically only pindexNew)
1859  vector<CBlockIndex*> vConnect;
1860  for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1861  vConnect.push_back(pindex);
1862  reverse(vConnect.begin(), vConnect.end());
1863 
1864  if (vDisconnect.size() > 0) {
1865  printf("REORGANIZE: Disconnect %"PRIszu" blocks; %s..\n", vDisconnect.size(), pfork->GetBlockHash().ToString().c_str());
1866  printf("REORGANIZE: Connect %"PRIszu" blocks; ..%s\n", vConnect.size(), pindexNew->GetBlockHash().ToString().c_str());
1867  }
1868 
1869  // Disconnect shorter branch
1870  vector<CTransaction> vResurrect;
1871  BOOST_FOREACH(CBlockIndex* pindex, vDisconnect) {
1872  CBlock block;
1873  if (!block.ReadFromDisk(pindex))
1874  return state.Abort(_("Failed to read block"));
1875  int64 nStart = GetTimeMicros();
1876  if (!block.DisconnectBlock(state, pindex, view))
1877  return error("SetBestBlock() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().c_str());
1878  if (fBenchmark)
1879  printf("- Disconnect: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
1880 
1881  // Queue memory transactions to resurrect.
1882  // We only do this for blocks after the last checkpoint (reorganisation before that
1883  // point should only happen with -reindex/-loadblock, or a misbehaving peer.
1884  BOOST_FOREACH(const CTransaction& tx, block.vtx)
1885  if (!tx.IsCoinBase() && pindex->nHeight > Checkpoints::GetTotalBlocksEstimate())
1886  vResurrect.push_back(tx);
1887  }
1888 
1889  // Connect longer branch
1890  vector<CTransaction> vDelete;
1891  BOOST_FOREACH(CBlockIndex *pindex, vConnect) {
1892  CBlock block;
1893  if (!block.ReadFromDisk(pindex))
1894  return state.Abort(_("Failed to read block"));
1895  int64 nStart = GetTimeMicros();
1896  if (!block.ConnectBlock(state, pindex, view)) {
1897  if (state.IsInvalid()) {
1898  InvalidChainFound(pindexNew);
1899  InvalidBlockFound(pindex);
1900  }
1901  return error("SetBestBlock() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().c_str());
1902  }
1903  if (fBenchmark)
1904  printf("- Connect: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
1905 
1906  // Queue memory transactions to delete
1907  BOOST_FOREACH(const CTransaction& tx, block.vtx)
1908  vDelete.push_back(tx);
1909  }
1910 
1911  // Flush changes to global coin state
1912  int64 nStart = GetTimeMicros();
1913  int nModified = view.GetCacheSize();
1914  assert(view.Flush());
1915  int64 nTime = GetTimeMicros() - nStart;
1916  if (fBenchmark)
1917  printf("- Flush %i transactions: %.2fms (%.4fms/tx)\n", nModified, 0.001 * nTime, 0.001 * nTime / nModified);
1918 
1919  // Make sure it's successfully written to disk before changing memory structure
1920  bool fIsInitialDownload = IsInitialBlockDownload();
1921  if (!fIsInitialDownload || pcoinsTip->GetCacheSize() > nCoinCacheSize) {
1922  // Typical CCoins structures on disk are around 100 bytes in size.
1923  // Pushing a new one to the database can cause it to be written
1924  // twice (once in the log, and once in the tables). This is already
1925  // an overestimation, as most will delete an existing entry or
1926  // overwrite one. Still, use a conservative safety factor of 2.
1927  if (!CheckDiskSpace(100 * 2 * 2 * pcoinsTip->GetCacheSize()))
1928  return state.Error();
1929  FlushBlockFile();
1930  pblocktree->Sync();
1931  if (!pcoinsTip->Flush())
1932  return state.Abort(_("Failed to write to coin database"));
1933  }
1934 
1935  // At this point, all changes have been done to the database.
1936  // Proceed by updating the memory structures.
1937 
1938  // Disconnect shorter branch
1939  BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1940  if (pindex->pprev)
1941  pindex->pprev->pnext = NULL;
1942 
1943  // Connect longer branch
1944  BOOST_FOREACH(CBlockIndex* pindex, vConnect)
1945  if (pindex->pprev)
1946  pindex->pprev->pnext = pindex;
1947 
1948  // Resurrect memory transactions that were in the disconnected branch
1949  BOOST_FOREACH(CTransaction& tx, vResurrect) {
1950  // ignore validation errors in resurrected transactions
1951  CValidationState stateDummy;
1952  if (!tx.AcceptToMemoryPool(stateDummy, true, false))
1953  mempool.remove(tx, true);
1954  }
1955 
1956  // Delete redundant memory transactions that are in the connected branch
1957  BOOST_FOREACH(CTransaction& tx, vDelete) {
1958  mempool.remove(tx);
1959  mempool.removeConflicts(tx);
1960  }
1961 
1962  // Update best block in wallet (so we can detect restored wallets)
1963  if ((pindexNew->nHeight % 20160) == 0 || (!fIsInitialDownload && (pindexNew->nHeight % 144) == 0))
1964  {
1965  const CBlockLocator locator(pindexNew);
1966  ::SetBestChain(locator);
1967  }
1968 
1969  // New best block
1970  hashBestChain = pindexNew->GetBlockHash();
1971  pindexBest = pindexNew;
1972  pblockindexFBBHLast = NULL;
1973  nBestHeight = pindexBest->nHeight;
1974  nBestChainWork = pindexNew->nChainWork;
1975  nTimeBestReceived = GetTime();
1977  printf("SetBestChain: new best=%s height=%d log2_work=%.8g tx=%lu date=%s progress=%f\n",
1978  hashBestChain.ToString().c_str(), nBestHeight, log(nBestChainWork.getdouble())/log(2.0), (unsigned long)pindexNew->nChainTx,
1979  DateTimeStrFormat("%Y-%m-%d %H:%M:%S", pindexBest->GetBlockTime()).c_str(),
1981 
1982  // Check the version of the last 100 blocks to see if we need to upgrade:
1983  if (!fIsInitialDownload)
1984  {
1985  int nUpgraded = 0;
1986  const CBlockIndex* pindex = pindexBest;
1987  for (int i = 0; i < 100 && pindex != NULL; i++)
1988  {
1989  if (pindex->nVersion > CBlock::CURRENT_VERSION)
1990  ++nUpgraded;
1991  pindex = pindex->pprev;
1992  }
1993  if (nUpgraded > 0)
1994  printf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, CBlock::CURRENT_VERSION);
1995  if (nUpgraded > 100/2)
1996  // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
1997  strMiscWarning = _("Warning: This version is obsolete, upgrade required!");
1998  }
1999 
2000  if (!IsSyncCheckpointEnforced()) // checkpoint advisory mode
2001  {
2002  if (pindexBest->pprev && !CheckSyncCheckpoint(pindexBest->GetBlockHash(), pindexBest->pprev))
2003  strCheckpointWarning = _("Warning: checkpoint on different blockchain fork, contact developers to resolve the issue");
2004  else
2005  strCheckpointWarning = "";
2006  }
2007 
2008  std::string strCmd = GetArg("-blocknotify", "");
2009 
2010  if (!fIsInitialDownload && !strCmd.empty())
2011  {
2012  boost::replace_all(strCmd, "%s", hashBestChain.GetHex());
2013  boost::thread t(runCommand, strCmd); // thread runs free
2014  }
2015 
2016  return true;
2017 }
2018 
2019 
2021 {
2022  // Check for duplicate
2023  uint256 hash = GetHash();
2024  if (mapBlockIndex.count(hash))
2025  return state.Invalid(error("AddToBlockIndex() : %s already exists", hash.ToString().c_str()));
2026 
2027  // Construct new block index object
2028  CBlockIndex* pindexNew = new CBlockIndex(*this);
2029  assert(pindexNew);
2030  map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2031  pindexNew->phashBlock = &((*mi).first);
2032  map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
2033  if (miPrev != mapBlockIndex.end())
2034  {
2035  pindexNew->pprev = (*miPrev).second;
2036  pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2037  }
2038  pindexNew->nTx = vtx.size();
2039  pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + pindexNew->GetBlockWork().getuint256();
2040  pindexNew->nChainTx = (pindexNew->pprev ? pindexNew->pprev->nChainTx : 0) + pindexNew->nTx;
2041  pindexNew->nFile = pos.nFile;
2042  pindexNew->nDataPos = pos.nPos;
2043  pindexNew->nUndoPos = 0;
2045  setBlockIndexValid.insert(pindexNew);
2046 
2047  if (!pblocktree->WriteBlockIndex(CDiskBlockIndex(pindexNew)))
2048  return state.Abort(_("Failed to write block index"));
2049 
2050  // New best?
2051  if (!ConnectBestBlock(state))
2052  return false;
2053 
2054  if (pindexNew == pindexBest)
2055  {
2056  // Notify UI to display prev block's coinbase if it was ours
2057  static uint256 hashPrevBestCoinBase;
2058  UpdatedTransaction(hashPrevBestCoinBase);
2059  hashPrevBestCoinBase = GetTxHash(0);
2060  }
2061 
2062  if (!pblocktree->Flush())
2063  return state.Abort(_("Failed to sync block index"));
2064 
2066  return true;
2067 }
2068 
2069 
2070 bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64 nTime, bool fKnown = false)
2071 {
2072  bool fUpdatedLast = false;
2073 
2075 
2076  if (fKnown) {
2077  if (nLastBlockFile != pos.nFile) {
2078  nLastBlockFile = pos.nFile;
2079  infoLastBlockFile.SetNull();
2081  fUpdatedLast = true;
2082  }
2083  } else {
2084  while (infoLastBlockFile.nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
2085  printf("Leaving block file %i: %s\n", nLastBlockFile, infoLastBlockFile.ToString().c_str());
2086  FlushBlockFile(true);
2087  nLastBlockFile++;
2088  infoLastBlockFile.SetNull();
2089  pblocktree->ReadBlockFileInfo(nLastBlockFile, infoLastBlockFile); // check whether data for the new file somehow already exist; can fail just fine
2090  fUpdatedLast = true;
2091  }
2092  pos.nFile = nLastBlockFile;
2094  }
2095 
2096  infoLastBlockFile.nSize += nAddSize;
2097  infoLastBlockFile.AddBlock(nHeight, nTime);
2098 
2099  if (!fKnown) {
2100  unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2101  unsigned int nNewChunks = (infoLastBlockFile.nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2102  if (nNewChunks > nOldChunks) {
2103  if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
2104  FILE *file = OpenBlockFile(pos);
2105  if (file) {
2106  printf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
2107  AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
2108  fclose(file);
2109  }
2110  }
2111  else
2112  return state.Error();
2113  }
2114  }
2115 
2117  return state.Abort(_("Failed to write file info"));
2118  if (fUpdatedLast)
2119  pblocktree->WriteLastBlockFile(nLastBlockFile);
2120 
2121  return true;
2122 }
2123 
2124 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
2125 {
2126  pos.nFile = nFile;
2127 
2129 
2130  unsigned int nNewSize;
2131  if (nFile == nLastBlockFile) {
2133  nNewSize = (infoLastBlockFile.nUndoSize += nAddSize);
2135  return state.Abort(_("Failed to write block info"));
2136  } else {
2137  CBlockFileInfo info;
2138  if (!pblocktree->ReadBlockFileInfo(nFile, info))
2139  return state.Abort(_("Failed to read block info"));
2140  pos.nPos = info.nUndoSize;
2141  nNewSize = (info.nUndoSize += nAddSize);
2142  if (!pblocktree->WriteBlockFileInfo(nFile, info))
2143  return state.Abort(_("Failed to write block info"));
2144  }
2145 
2146  unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2147  unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2148  if (nNewChunks > nOldChunks) {
2149  if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
2150  FILE *file = OpenUndoFile(pos);
2151  if (file) {
2152  printf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
2153  AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
2154  fclose(file);
2155  }
2156  }
2157  else
2158  return state.Error();
2159  }
2160 
2161  return true;
2162 }
2163 
2164 
2165 bool CBlock::CheckBlock(CValidationState &state, bool fCheckPOW, bool fCheckMerkleRoot) const
2166 {
2167  // These are checks that are independent of context
2168  // that can be verified before saving an orphan block.
2169 
2170  // Size limits
2171  if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
2172  return state.DoS(100, error("CheckBlock() : size limits failed"));
2173 
2174  // Check proof of work matches claimed amount
2175  if (fCheckPOW && !CheckProofOfWork(GetPoWHash(), nBits))
2176  return state.DoS(50, error("CheckBlock() : proof of work failed"));
2177 
2178  // First transaction must be coinbase, the rest must not be
2179  if (vtx.empty() || !vtx[0].IsCoinBase())
2180  return state.DoS(100, error("CheckBlock() : first tx is not coinbase"));
2181  for (unsigned int i = 1; i < vtx.size(); i++)
2182  if (vtx[i].IsCoinBase())
2183  return state.DoS(100, error("CheckBlock() : more than one coinbase"));
2184 
2185  // Check transactions
2186  BOOST_FOREACH(const CTransaction& tx, vtx)
2187  if (!tx.CheckTransaction(state))
2188  return error("CheckBlock() : CheckTransaction failed");
2189 
2190  // Build the merkle tree already. We need it anyway later, and it makes the
2191  // block cache the transaction hashes, which means they don't need to be
2192  // recalculated many times during this block's validation.
2193  BuildMerkleTree();
2194 
2195  // Check for duplicate txids. This is caught by ConnectInputs(),
2196  // but catching it earlier avoids a potential DoS attack:
2197  set<uint256> uniqueTx;
2198  for (unsigned int i=0; i<vtx.size(); i++) {
2199  uniqueTx.insert(GetTxHash(i));
2200  }
2201  if (uniqueTx.size() != vtx.size())
2202  return state.DoS(100, error("CheckBlock() : duplicate transaction"), true);
2203 
2204  unsigned int nSigOps = 0;
2205  BOOST_FOREACH(const CTransaction& tx, vtx)
2206  {
2207  nSigOps += tx.GetLegacySigOpCount();
2208  }
2209  if (nSigOps > MAX_BLOCK_SIGOPS)
2210  return state.DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
2211 
2212  // Check merkle root
2213  if (fCheckMerkleRoot && hashMerkleRoot != BuildMerkleTree())
2214  return state.DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
2215 
2216  return true;
2217 }
2218 
2220 {
2221  // Check for duplicate
2222  uint256 hash = GetHash();
2223  if (mapBlockIndex.count(hash))
2224  return state.Invalid(error("AcceptBlock() : block already in mapBlockIndex"));
2225 
2226  // Get prev block index
2227  CBlockIndex* pindexPrev = NULL;
2228  int nHeight = 0;
2229  if (hash != hashGenesisBlock) {
2230  map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
2231  if (mi == mapBlockIndex.end())
2232  return state.DoS(10, error("AcceptBlock() : prev block not found"));
2233  pindexPrev = (*mi).second;
2234  nHeight = pindexPrev->nHeight+1;
2235 
2236  // Check proof of work
2237  if (nBits != GetNextWorkRequired(pindexPrev, this))
2238  return state.DoS(100, error("AcceptBlock() : incorrect proof of work"));
2239 
2240  // Check timestamp against prev
2241  if (GetBlockTime() <= pindexPrev->GetMedianTimePast())
2242  return state.Invalid(error("AcceptBlock() : block's timestamp is too early"));
2243 
2244  // limit block in future accepted in chain to only a time window of 15 min
2245  if (GetBlockTime() > GetAdjustedTime() + 15 * 60)
2246  return error("AcceptBlock() : block's timestamp too far in the future");
2247 
2248 
2249  // Check timestamp against prev it should not be more then 2 times the window
2250  if (((nHeight > nForkTwo) && (GetBlockTime() <= pindexPrev->GetBlockTime() - 2 * 30 * 60)) ||
2251  ((nHeight >= nForkThree || fTestNet) && (GetBlockTime() <= pindexPrev->GetBlockTime() - 15 * 60))) // or 15 minutes
2252  return error("AcceptBlock() : block's timestamp is too early compare to last block");
2253 
2254  // Check that all transactions are finalized
2255  BOOST_FOREACH(const CTransaction& tx, vtx)
2256  if (!tx.IsFinal(nHeight, GetBlockTime()))
2257  return state.DoS(10, error("AcceptBlock() : contains a non-final transaction"));
2258 
2259  // Check that the block chain matches the known block chain up to a checkpoint
2260  if (!Checkpoints::CheckBlock(nHeight, hash))
2261  return state.DoS(100, error("AcceptBlock() : rejected by checkpoint lock-in at %d", nHeight));
2262 
2263  // ppcoin: check that the block satisfies synchronized checkpoint
2264  if (IsSyncCheckpointEnforced() // checkpoint enforce mode
2265  && !CheckSyncCheckpoint(hash, pindexPrev))
2266  return error("AcceptBlock() : rejected by synchronized checkpoint");
2267 
2268  // Reject block.nVersion=1 blocks when 95% (75% on testnet) of the network has upgraded:
2269  if (nVersion < 2)
2270  {
2271  if ((!fTestNet && CBlockIndex::IsSuperMajority(2, pindexPrev, 950, 1000)) ||
2272  (fTestNet && CBlockIndex::IsSuperMajority(2, pindexPrev, 75, 100)))
2273  {
2274  return state.Invalid(error("AcceptBlock() : rejected nVersion=1 block"));
2275  }
2276  }
2277  // Enforce block.nVersion=2 rule that the coinbase starts with serialized block height
2278  if (nVersion >= 2)
2279  {
2280  // if 750 of the last 1,000 blocks are version 2 or greater (51/100 if testnet):
2281  if ((!fTestNet && CBlockIndex::IsSuperMajority(2, pindexPrev, 750, 1000)) ||
2282  (fTestNet && CBlockIndex::IsSuperMajority(2, pindexPrev, 51, 100)))
2283  {
2284  CScript expect = CScript() << nHeight;
2285  if (vtx[0].vin[0].scriptSig.size() < expect.size() ||
2286  !std::equal(expect.begin(), expect.end(), vtx[0].vin[0].scriptSig.begin()))
2287  return state.DoS(100, error("AcceptBlock() : block height mismatch in coinbase"));
2288  }
2289  }
2290  }
2291 
2292  // Write block to history file
2293  try {
2294  unsigned int nBlockSize = ::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION);
2295  CDiskBlockPos blockPos;
2296  if (dbp != NULL)
2297  blockPos = *dbp;
2298  if (!FindBlockPos(state, blockPos, nBlockSize+8, nHeight, nTime, dbp != NULL))
2299  return error("AcceptBlock() : FindBlockPos failed");
2300  if (dbp == NULL)
2301  if (!WriteToDisk(blockPos))
2302  return state.Abort(_("Failed to write block"));
2303  if (!AddToBlockIndex(state, blockPos))
2304  return error("AcceptBlock() : AddToBlockIndex failed");
2305  } catch(std::runtime_error &e) {
2306  return state.Abort(_("System error: ") + e.what());
2307  }
2308 
2309  // Relay inventory, but don't relay old inventory during initial block download
2310  int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
2311  if (hashBestChain == hash)
2312  {
2313  LOCK(cs_vNodes);
2314  BOOST_FOREACH(CNode* pnode, vNodes)
2315  if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
2316  pnode->PushInventory(CInv(MSG_BLOCK, hash));
2317  }
2318 
2319  // ppcoin: check pending sync-checkpoint
2321 
2322  return true;
2323 }
2324 
2325 bool CBlockIndex::IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired, unsigned int nToCheck)
2326 {
2327  // Feathercoin: temporarily disable v2 block lockin until we are ready for v2 transition
2328  return false;
2329  unsigned int nFound = 0;
2330  for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++)
2331  {
2332  if (pstart->nVersion >= minVersion)
2333  ++nFound;
2334  pstart = pstart->pprev;
2335  }
2336  return (nFound >= nRequired);
2337 }
2338 
2340 {
2341  // Check for duplicate
2342  uint256 hash = pblock->GetHash();
2343  if (mapBlockIndex.count(hash))
2344  return state.Invalid(error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().c_str()));
2345  if (mapOrphanBlocks.count(hash))
2346  return state.Invalid(error("ProcessBlock() : already have block (orphan) %s", hash.ToString().c_str()));
2347 
2348  // Preliminary checks
2349  if (!pblock->CheckBlock(state))
2350  return error("ProcessBlock() : CheckBlock FAILED");
2351 
2353  if (pcheckpoint && pblock->hashPrevBlock != hashBestChain)
2354  {
2355 
2356  if((pblock->GetBlockTime() - pcheckpoint->nTime) < 0) {
2357  if(pfrom) pfrom->Misbehaving(100);
2358  return error("ProcessBlock() : block has a time stamp of %u before the last checkpoint of %u", pblock->GetBlockTime(), pcheckpoint->nTime);
2359  }
2360 
2361  // Here was some code to verify block difficulty upon block and checkpoint
2362  // time difference which had never worked well in general and was broken
2363  // across the hard forks for Feathercoin in particular
2364 
2365  }
2366 
2367  // ppcoin: ask for pending sync-checkpoint if any
2368  if (!IsInitialBlockDownload())
2370 
2371  // If we don't already have its previous block, shunt it off to holding area until we get it
2372  if (pblock->hashPrevBlock != 0 && !mapBlockIndex.count(pblock->hashPrevBlock))
2373  {
2374  printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().c_str());
2375 
2376  // Accept orphans as long as there is a node to request its parents from
2377  if (pfrom) {
2378  CBlock* pblock2 = new CBlock(*pblock);
2379  mapOrphanBlocks.insert(make_pair(hash, pblock2));
2380  mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
2381 
2382  // Ask this guy to fill in what we're missing
2383  pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
2384  }
2385  return true;
2386  }
2387 
2388  // Store to disk
2389  if (!pblock->AcceptBlock(state, dbp))
2390  return error("ProcessBlock() : AcceptBlock FAILED");
2391 
2392  // Recursively process any orphan blocks that depended on this one
2393  vector<uint256> vWorkQueue;
2394  vWorkQueue.push_back(hash);
2395  for (unsigned int i = 0; i < vWorkQueue.size(); i++)
2396  {
2397  uint256 hashPrev = vWorkQueue[i];
2398  for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
2399  mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
2400  ++mi)
2401  {
2402  CBlock* pblockOrphan = (*mi).second;
2403  // Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan resolution (that is, feeding people an invalid block based on LegitBlockX in order to get anyone relaying LegitBlockX banned)
2404  CValidationState stateDummy;
2405  if (pblockOrphan->AcceptBlock(stateDummy))
2406  vWorkQueue.push_back(pblockOrphan->GetHash());
2407  mapOrphanBlocks.erase(pblockOrphan->GetHash());
2408  delete pblockOrphan;
2409  }
2410  mapOrphanBlocksByPrev.erase(hashPrev);
2411  }
2412 
2413  printf("ProcessBlock: ACCEPTED\n");
2414 
2415  // ppcoin: if responsible for sync-checkpoint send it
2416  if (pfrom && !CSyncCheckpoint::strMasterPrivKey.empty() &&
2417  (int)GetArg("-checkpointdepth", -1) >= 0)
2419 
2420  return true;
2421 }
2422 
2423 
2424 
2425 
2426 
2427 
2428 
2429 
2431 {
2432  header = block.GetBlockHeader();
2433 
2434  vector<bool> vMatch;
2435  vector<uint256> vHashes;
2436 
2437  vMatch.reserve(block.vtx.size());
2438  vHashes.reserve(block.vtx.size());
2439 
2440  for (unsigned int i = 0; i < block.vtx.size(); i++)
2441  {
2442  uint256 hash = block.vtx[i].GetHash();
2443  if (filter.IsRelevantAndUpdate(block.vtx[i], hash))
2444  {
2445  vMatch.push_back(true);
2446  vMatchedTxn.push_back(make_pair(i, hash));
2447  }
2448  else
2449  vMatch.push_back(false);
2450  vHashes.push_back(hash);
2451  }
2452 
2453  txn = CPartialMerkleTree(vHashes, vMatch);
2454 }
2455 
2456 
2457 
2458 
2459 
2460 
2461 
2462 
2463 uint256 CPartialMerkleTree::CalcHash(int height, unsigned int pos, const std::vector<uint256> &vTxid) {
2464  if (height == 0) {
2465  // hash at height 0 is the txids themself
2466  return vTxid[pos];
2467  } else {
2468  // calculate left hash
2469  uint256 left = CalcHash(height-1, pos*2, vTxid), right;
2470  // calculate right hash if not beyong the end of the array - copy left hash otherwise1
2471  if (pos*2+1 < CalcTreeWidth(height-1))
2472  right = CalcHash(height-1, pos*2+1, vTxid);
2473  else
2474  right = left;
2475  // combine subhashes
2476  return Hash(BEGIN(left), END(left), BEGIN(right), END(right));
2477  }
2478 }
2479 
2480 void CPartialMerkleTree::TraverseAndBuild(int height, unsigned int pos, const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch) {
2481  // determine whether this node is the parent of at least one matched txid
2482  bool fParentOfMatch = false;
2483  for (unsigned int p = pos << height; p < (pos+1) << height && p < nTransactions; p++)
2484  fParentOfMatch |= vMatch[p];
2485  // store as flag bit
2486  vBits.push_back(fParentOfMatch);
2487  if (height==0 || !fParentOfMatch) {
2488  // if at height 0, or nothing interesting below, store hash and stop
2489  vHash.push_back(CalcHash(height, pos, vTxid));
2490  } else {
2491  // otherwise, don't store any hash, but descend into the subtrees
2492  TraverseAndBuild(height-1, pos*2, vTxid, vMatch);
2493  if (pos*2+1 < CalcTreeWidth(height-1))
2494  TraverseAndBuild(height-1, pos*2+1, vTxid, vMatch);
2495  }
2496 }
2497 
2498 uint256 CPartialMerkleTree::TraverseAndExtract(int height, unsigned int pos, unsigned int &nBitsUsed, unsigned int &nHashUsed, std::vector<uint256> &vMatch) {
2499  if (nBitsUsed >= vBits.size()) {
2500  // overflowed the bits array - failure
2501  fBad = true;
2502  return 0;
2503  }
2504  bool fParentOfMatch = vBits[nBitsUsed++];
2505  if (height==0 || !fParentOfMatch) {
2506  // if at height 0, or nothing interesting below, use stored hash and do not descend
2507  if (nHashUsed >= vHash.size()) {
2508  // overflowed the hash array - failure
2509  fBad = true;
2510  return 0;
2511  }
2512  const uint256 &hash = vHash[nHashUsed++];
2513  if (height==0 && fParentOfMatch) // in case of height 0, we have a matched txid
2514  vMatch.push_back(hash);
2515  return hash;
2516  } else {
2517  // otherwise, descend into the subtrees to extract matched txids and hashes
2518  uint256 left = TraverseAndExtract(height-1, pos*2, nBitsUsed, nHashUsed, vMatch), right;
2519  if (pos*2+1 < CalcTreeWidth(height-1))
2520  right = TraverseAndExtract(height-1, pos*2+1, nBitsUsed, nHashUsed, vMatch);
2521  else
2522  right = left;
2523  // and combine them before returning
2524  return Hash(BEGIN(left), END(left), BEGIN(right), END(right));
2525  }
2526 }
2527 
2528 CPartialMerkleTree::CPartialMerkleTree(const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch) : nTransactions(vTxid.size()), fBad(false) {
2529  // reset state
2530  vBits.clear();
2531  vHash.clear();
2532 
2533  // calculate height of tree
2534  int nHeight = 0;
2535  while (CalcTreeWidth(nHeight) > 1)
2536  nHeight++;
2537 
2538  // traverse the partial tree
2539  TraverseAndBuild(nHeight, 0, vTxid, vMatch);
2540 }
2541 
2542 CPartialMerkleTree::CPartialMerkleTree() : nTransactions(0), fBad(true) {}
2543 
2544 uint256 CPartialMerkleTree::ExtractMatches(std::vector<uint256> &vMatch) {
2545  vMatch.clear();
2546  // An empty set will not work
2547  if (nTransactions == 0)
2548  return 0;
2549  // check for excessively high numbers of transactions
2550  if (nTransactions > MAX_BLOCK_SIZE / 60) // 60 is the lower bound for the size of a serialized CTransaction
2551  return 0;
2552  // there can never be more hashes provided than one for every txid
2553  if (vHash.size() > nTransactions)
2554  return 0;
2555  // there must be at least one bit per node in the partial tree, and at least one node per hash
2556  if (vBits.size() < vHash.size())
2557  return 0;
2558  // calculate height of tree
2559  int nHeight = 0;
2560  while (CalcTreeWidth(nHeight) > 1)
2561  nHeight++;
2562  // traverse the partial tree
2563  unsigned int nBitsUsed = 0, nHashUsed = 0;
2564  uint256 hashMerkleRoot = TraverseAndExtract(nHeight, 0, nBitsUsed, nHashUsed, vMatch);
2565  // verify that no problems occured during the tree traversal
2566  if (fBad)
2567  return 0;
2568  // verify that all bits were consumed (except for the padding caused by serializing it as a byte sequence)
2569  if ((nBitsUsed+7)/8 != (vBits.size()+7)/8)
2570  return 0;
2571  // verify that all hashes were consumed
2572  if (nHashUsed != vHash.size())
2573  return 0;
2574  return hashMerkleRoot;
2575 }
2576 
2577 
2578 
2579 
2580 
2581 
2582 
2583 bool AbortNode(const std::string &strMessage) {
2584  strMiscWarning = strMessage;
2585  printf("*** %s\n", strMessage.c_str());
2587  StartShutdown();
2588  return false;
2589 }
2590 
2591 bool CheckDiskSpace(uint64 nAdditionalBytes)
2592 {
2593  uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
2594 
2595  // Check for nMinDiskSpace bytes (currently 50MB)
2596  if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
2597  return AbortNode(_("Error: Disk space is low!"));
2598 
2599  return true;
2600 }
2601 
2605 
2606 FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
2607 {
2608  if (pos.IsNull())
2609  return NULL;
2610  boost::filesystem::path path = GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
2611  boost::filesystem::create_directories(path.parent_path());
2612  FILE* file = fopen(path.string().c_str(), "rb+");
2613  if (!file && !fReadOnly)
2614  file = fopen(path.string().c_str(), "wb+");
2615  if (!file) {
2616  printf("Unable to open file %s\n", path.string().c_str());
2617  return NULL;
2618  }
2619  if (pos.nPos) {
2620  if (fseek(file, pos.nPos, SEEK_SET)) {
2621  printf("Unable to seek to position %u of %s\n", pos.nPos, path.string().c_str());
2622  fclose(file);
2623  return NULL;
2624  }
2625  }
2626  return file;
2627 }
2628 
2629 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
2630  return OpenDiskFile(pos, "blk", fReadOnly);
2631 }
2632 
2633 FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
2634  return OpenDiskFile(pos, "rev", fReadOnly);
2635 }
2636 
2638 {
2639  if (hash == 0)
2640  return NULL;
2641 
2642  // Return existing
2643  map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
2644  if (mi != mapBlockIndex.end())
2645  return (*mi).second;
2646 
2647  // Create new
2648  CBlockIndex* pindexNew = new CBlockIndex();
2649  if (!pindexNew)
2650  throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
2651  mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2652  pindexNew->phashBlock = &((*mi).first);
2653 
2654  return pindexNew;
2655 }
2656 
2657 bool static LoadBlockIndexDB()
2658 {
2659  if (!pblocktree->LoadBlockIndexGuts())
2660  return false;
2661 
2662  boost::this_thread::interruption_point();
2663 
2664  // Calculate nChainWork
2665  vector<pair<int, CBlockIndex*> > vSortedByHeight;
2666  vSortedByHeight.reserve(mapBlockIndex.size());
2667  BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
2668  {
2669  CBlockIndex* pindex = item.second;
2670  vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
2671  }
2672  sort(vSortedByHeight.begin(), vSortedByHeight.end());
2673  BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
2674  {
2675  CBlockIndex* pindex = item.second;
2676  pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + pindex->GetBlockWork().getuint256();
2677  pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
2678  if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS && !(pindex->nStatus & BLOCK_FAILED_MASK))
2679  setBlockIndexValid.insert(pindex);
2680  }
2681 
2682  // Load block file info
2683  pblocktree->ReadLastBlockFile(nLastBlockFile);
2684  printf("LoadBlockIndexDB(): last block file = %i\n", nLastBlockFile);
2685  if (pblocktree->ReadBlockFileInfo(nLastBlockFile, infoLastBlockFile))
2686  printf("LoadBlockIndexDB(): last block file info: %s\n", infoLastBlockFile.ToString().c_str());
2687 
2688  // ppcoin: load hashSyncCheckpoint
2689  if (!pblocktree->ReadSyncCheckpoint(hashSyncCheckpoint))
2690  printf("LoadBlockIndexDB(): synchronized checkpoint not read\n");
2691  else
2692  printf("LoadBlockIndexDB(): synchronized checkpoint %s\n", hashSyncCheckpoint.ToString().c_str());
2693 
2694  // Load nBestInvalidWork, OK if it doesn't exist
2695  CBigNum bnBestInvalidWork;
2696  pblocktree->ReadBestInvalidWork(bnBestInvalidWork);
2697  nBestInvalidWork = bnBestInvalidWork.getuint256();
2698 
2699  // Check whether we need to continue reindexing
2700  bool fReindexing = false;
2701  pblocktree->ReadReindexing(fReindexing);
2702  fReindex |= fReindexing;
2703 
2704  // Check whether we have a transaction index
2705  pblocktree->ReadFlag("txindex", fTxIndex);
2706  printf("LoadBlockIndexDB(): transaction index %s\n", fTxIndex ? "enabled" : "disabled");
2707 
2708  // Load hashBestChain pointer to end of best chain
2709  pindexBest = pcoinsTip->GetBestBlock();
2710  if (pindexBest == NULL)
2711  return true;
2712  hashBestChain = pindexBest->GetBlockHash();
2713  nBestHeight = pindexBest->nHeight;
2714  nBestChainWork = pindexBest->nChainWork;
2715 
2716  // set 'next' pointers in best chain
2717  CBlockIndex *pindex = pindexBest;
2718  while(pindex != NULL && pindex->pprev != NULL) {
2719  CBlockIndex *pindexPrev = pindex->pprev;
2720  pindexPrev->pnext = pindex;
2721  pindex = pindexPrev;
2722  }
2723  printf("LoadBlockIndexDB(): hashBestChain=%s height=%d date=%s\n",
2724  hashBestChain.ToString().c_str(), nBestHeight,
2725  DateTimeStrFormat("%Y-%m-%d %H:%M:%S", pindexBest->GetBlockTime()).c_str());
2726 
2727  return true;
2728 }
2729 
2730 bool VerifyDB(int nCheckLevel, int nCheckDepth)
2731 {
2732  if (pindexBest == NULL || pindexBest->pprev == NULL)
2733  return true;
2734 
2735  // Verify blocks in the best chain
2736  if (nCheckDepth <= 0)
2737  nCheckDepth = 1000000000; // suffices until the year 19000
2738  if (nCheckDepth > nBestHeight)
2739  nCheckDepth = nBestHeight;
2740  nCheckLevel = std::max(0, std::min(4, nCheckLevel));
2741  printf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
2742  CCoinsViewCache coins(*pcoinsTip, true);
2743  CBlockIndex* pindexState = pindexBest;
2744  CBlockIndex* pindexFailure = NULL;
2745  int nGoodTransactions = 0;
2747  for (CBlockIndex* pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev)
2748  {
2749  boost::this_thread::interruption_point();
2750  if (pindex->nHeight < nBestHeight-nCheckDepth)
2751  break;
2752  CBlock block;
2753  // check level 0: read from disk
2754  if (!block.ReadFromDisk(pindex))
2755  return error("VerifyDB() : *** block.ReadFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
2756  // check level 1: verify block validity
2757  if (nCheckLevel >= 1 && !block.CheckBlock(state))
2758  return error("VerifyDB() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
2759  // check level 2: verify undo validity
2760  if (nCheckLevel >= 2 && pindex) {
2761  CBlockUndo undo;
2762  CDiskBlockPos pos = pindex->GetUndoPos();
2763  if (!pos.IsNull()) {
2764  if (!undo.ReadFromDisk(pos, pindex->pprev->GetBlockHash()))
2765  return error("VerifyDB() : *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
2766  }
2767  }
2768  // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
2769  if (nCheckLevel >= 3 && pindex == pindexState && (coins.GetCacheSize() + pcoinsTip->GetCacheSize()) <= 2*nCoinCacheSize + 32000) {
2770  bool fClean = true;
2771  if (!block.DisconnectBlock(state, pindex, coins, &fClean))
2772  return error("VerifyDB() : *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
2773  pindexState = pindex->pprev;
2774  if (!fClean) {
2775  nGoodTransactions = 0;
2776  pindexFailure = pindex;
2777  } else
2778  nGoodTransactions += block.vtx.size();
2779  }
2780  }
2781  if (pindexFailure)
2782  return error("VerifyDB() : *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", pindexBest->nHeight - pindexFailure->nHeight + 1, nGoodTransactions);
2783 
2784  // check level 4: try reconnecting blocks
2785  if (nCheckLevel >= 4) {
2786  CBlockIndex *pindex = pindexState;
2787  while (pindex != pindexBest) {
2788  boost::this_thread::interruption_point();
2789  pindex = pindex->pnext;
2790  CBlock block;
2791  if (!block.ReadFromDisk(pindex))
2792  return error("VerifyDB() : *** block.ReadFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
2793  if (!block.ConnectBlock(state, pindex, coins))
2794  return error("VerifyDB() : *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
2795  }
2796  }
2797 
2798  printf("No coin database inconsistencies in last %i blocks (%i transactions)\n", pindexBest->nHeight - pindexState->nHeight, nGoodTransactions);
2799 
2800  return true;
2801 }
2802 
2804 {
2805  mapBlockIndex.clear();
2806  setBlockIndexValid.clear();
2807  pindexGenesisBlock = NULL;
2808  nBestHeight = 0;
2809  nBestChainWork = 0;
2810  nBestInvalidWork = 0;
2811  hashBestChain = 0;
2812  pindexBest = NULL;
2813 }
2814 
2816 {
2817  if (fTestNet)
2818  {
2819  pchMessageStart[0] = 0xda;
2820  pchMessageStart[1] = 0xaf;
2821  pchMessageStart[2] = 0xa5;
2822  pchMessageStart[3] = 0xba;
2823  hashGenesisBlock = uint256("0x8e8b634d2f2800398261b7adcfbb6ace490e1746e62123ec2bf8010f9fc98b17");
2824  }
2825 
2826  //
2827  // Load block index from databases
2828  //
2829  if (!fReindex && !LoadBlockIndexDB())
2830  return false;
2831 
2832  return true;
2833 }
2834 
2835 
2837  // Check whether we're already initialized
2838  if (pindexGenesisBlock != NULL)
2839  return true;
2840 
2841  // Use the provided setting for -txindex in the new database
2842  fTxIndex = GetBoolArg("-txindex", false);
2843  pblocktree->WriteFlag("txindex", fTxIndex);
2844  printf("Initializing databases...\n");
2845 
2846  // Only add the genesis block if not reindexing (in which case we reuse the one already on disk)
2847  if (!fReindex) {
2848  // Genesis Block:
2849  // CBlock(hash=12a765e31ffd4059bada, PoW=0000050c34a64b415b6b, ver=1, hashPrevBlock=00000000000000000000, hashMerkleRoot=97ddfbbae6, nTime=1317972665, nBits=1e0ffff0, nNonce=2084524493, vtx=1)
2850  // CTransaction(hash=97ddfbbae6, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2851  // CTxIn(COutPoint(0000000000, -1), coinbase 04ffff001d0104404e592054696d65732030352f4f63742f32303131205374657665204a6f62732c204170706c65e280997320566973696f6e6172792c2044696573206174203536)
2852  // CTxOut(nValue=50.00000000, scriptPubKey=040184710fa689ad5023690c80f3a4)
2853  // vMerkleTree: 97ddfbbae6
2854 
2855  // Genesis block
2856  const char* pszTimestamp = "NY Times 05/Oct/2011 Steve Jobs, Apple’s Visionary, Dies at 56";
2857  CTransaction txNew;
2858  txNew.vin.resize(1);
2859  txNew.vout.resize(1);
2860  txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
2861  txNew.vout[0].nValue = 50 * COIN;
2862  txNew.vout[0].scriptPubKey = CScript() << ParseHex("040184710fa689ad5023690c80f3a49c8f13f8d45b8c857fbcbc8bc4a8e4d3eb4b10f4d4604fa08dce601aaf0f470216fe1b51850b4acf21b179c45070ac7b03a9") << OP_CHECKSIG;
2863  CBlock block;
2864  block.vtx.push_back(txNew);
2865  block.hashPrevBlock = 0;
2866  block.hashMerkleRoot = block.BuildMerkleTree();
2867  block.nVersion = 1;
2868  block.nTime = 1317972665;
2869  block.nBits = 0x1e0ffff0;
2870  block.nNonce = 2084524493;
2871 
2872  if (fTestNet)
2873  {
2874  block.nTime = 1396255061;
2875  block.nNonce = 3250989159;
2876  }
2877 
2879  uint256 hash = block.GetHash();
2880  printf("%s\n", hash.ToString().c_str());
2881  printf("%s\n", hashGenesisBlock.ToString().c_str());
2882  printf("%s\n", block.hashMerkleRoot.ToString().c_str());
2883  assert(block.hashMerkleRoot == uint256("0x97ddfbbae6be97fd6cdf3e7ca13232a3afff2353e29badfab7f73011edd4ced9"));
2884  block.print();
2885  assert(hash == hashGenesisBlock);
2886 
2887  // Start new block file
2888  try {
2889  unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
2890  CDiskBlockPos blockPos;
2892  if (!FindBlockPos(state, blockPos, nBlockSize+8, 0, block.nTime))
2893  return error("LoadBlockIndex() : FindBlockPos failed");
2894  if (!block.WriteToDisk(blockPos))
2895  return error("LoadBlockIndex() : writing genesis block to disk failed");
2896  if (!block.AddToBlockIndex(state, blockPos))
2897  return error("LoadBlockIndex() : genesis block not accepted");
2898 
2899  // ppcoin: initialize synchronized checkpoint
2901  return error("LoadBlockIndex() : failed to init sync checkpoint");
2902  } catch(std::runtime_error &e) {
2903  return error("LoadBlockIndex() : failed to initialize block database: %s", e.what());
2904  }
2905  }
2906 
2907  // ppcoin: if checkpoint master key changed must reset sync-checkpoint
2908  if (!CheckCheckpointPubKey())
2909  return error("LoadBlockIndex() : failed to reset checkpoint master pubkey");
2910 
2911  return true;
2912 }
2913 
2914 
2915 
2917 {
2918  // pre-compute tree structure
2919  map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
2920  for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
2921  {
2922  CBlockIndex* pindex = (*mi).second;
2923  mapNext[pindex->pprev].push_back(pindex);
2924  // test
2925  //while (rand() % 3 == 0)
2926  // mapNext[pindex->pprev].push_back(pindex);
2927  }
2928 
2929  vector<pair<int, CBlockIndex*> > vStack;
2930  vStack.push_back(make_pair(0, pindexGenesisBlock));
2931 
2932  int nPrevCol = 0;
2933  while (!vStack.empty())
2934  {
2935  int nCol = vStack.back().first;
2936  CBlockIndex* pindex = vStack.back().second;
2937  vStack.pop_back();
2938 
2939  // print split or gap
2940  if (nCol > nPrevCol)
2941  {
2942  for (int i = 0; i < nCol-1; i++)
2943  printf("| ");
2944  printf("|\\\n");
2945  }
2946  else if (nCol < nPrevCol)
2947  {
2948  for (int i = 0; i < nCol; i++)
2949  printf("| ");
2950  printf("|\n");
2951  }
2952  nPrevCol = nCol;
2953 
2954  // print columns
2955  for (int i = 0; i < nCol; i++)
2956  printf("| ");
2957 
2958  // print item
2959  CBlock block;
2960  block.ReadFromDisk(pindex);
2961  printf("%d (blk%05u.dat:0x%x) %s tx %"PRIszu"",
2962  pindex->nHeight,
2963  pindex->GetBlockPos().nFile, pindex->GetBlockPos().nPos,
2964  DateTimeStrFormat("%Y-%m-%d %H:%M:%S", block.GetBlockTime()).c_str(),
2965  block.vtx.size());
2966 
2967  PrintWallets(block);
2968 
2969  // put the main time-chain first
2970  vector<CBlockIndex*>& vNext = mapNext[pindex];
2971  for (unsigned int i = 0; i < vNext.size(); i++)
2972  {
2973  if (vNext[i]->pnext)
2974  {
2975  swap(vNext[0], vNext[i]);
2976  break;
2977  }
2978  }
2979 
2980  // iterate children
2981  for (unsigned int i = 0; i < vNext.size(); i++)
2982  vStack.push_back(make_pair(nCol+i, vNext[i]));
2983  }
2984 }
2985 
2986 bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp)
2987 {
2988  int64 nStart = GetTimeMillis();
2989 
2990  int nLoaded = 0;
2991  try {
2992  CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SIZE, MAX_BLOCK_SIZE+8, SER_DISK, CLIENT_VERSION);
2993  uint64 nStartByte = 0;
2994  if (dbp) {
2995  // (try to) skip already indexed part
2996  CBlockFileInfo info;
2997  if (pblocktree->ReadBlockFileInfo(dbp->nFile, info)) {
2998  nStartByte = info.nSize;
2999  blkdat.Seek(info.nSize);
3000  }
3001  }
3002  uint64 nRewind = blkdat.GetPos();
3003  while (blkdat.good() && !blkdat.eof()) {
3004  boost::this_thread::interruption_point();
3005 
3006  blkdat.SetPos(nRewind);
3007  nRewind++; // start one byte further next time, in case of failure
3008  blkdat.SetLimit(); // remove former limit
3009  unsigned int nSize = 0;
3010  try {
3011  // locate a header
3012  unsigned char buf[4];
3013  blkdat.FindByte(pchMessageStart[0]);
3014  nRewind = blkdat.GetPos()+1;
3015  blkdat >> FLATDATA(buf);
3016  if (memcmp(buf, pchMessageStart, 4))
3017  continue;
3018  // read size
3019  blkdat >> nSize;
3020  if (nSize < 80 || nSize > MAX_BLOCK_SIZE)
3021  continue;
3022  } catch (std::exception &e) {
3023  // no valid block header found; don't complain
3024  break;
3025  }
3026  try {
3027  // read block
3028  uint64 nBlockPos = blkdat.GetPos();
3029  blkdat.SetLimit(nBlockPos + nSize);
3030  CBlock block;
3031  blkdat >> block;
3032  nRewind = blkdat.GetPos();
3033 
3034  // process block
3035  if (nBlockPos >= nStartByte) {
3036  LOCK(cs_main);
3037  if (dbp)
3038  dbp->nPos = nBlockPos;
3040  if (ProcessBlock(state, NULL, &block, dbp))
3041  nLoaded++;
3042  if (state.IsError())
3043  break;
3044  }
3045  } catch (std::exception &e) {
3046  printf("%s() : Deserialize or I/O error caught during load\n", __PRETTY_FUNCTION__);
3047  }
3048  }
3049  fclose(fileIn);
3050  } catch(std::runtime_error &e) {
3051  AbortNode(_("Error: system error: ") + e.what());
3052  }
3053  if (nLoaded > 0)
3054  printf("Loaded %i blocks from external file in %"PRI64d"ms\n", nLoaded, GetTimeMillis() - nStart);
3055  return nLoaded > 0;
3056 }
3057 
3058 
3059 
3060 
3061 
3062 
3063 
3064 
3065 
3066 
3068 //
3069 // CAlert
3070 //
3071 
3072 extern map<uint256, CAlert> mapAlerts;
3074 
3075 string GetWarnings(string strFor)
3076 {
3077  int nPriority = 0;
3078  string strStatusBar;
3079  string strRPC;
3080 
3081  if (GetBoolArg("-testsafemode"))
3082  strRPC = "test";
3083 
3085  strStatusBar = _("This is a pre-release test build - use at your own risk - do not use for mining or merchant applications");
3086 
3087  // Checkpoint warning
3088  if (strCheckpointWarning != "")
3089  {
3090  nPriority = 900;
3091  strStatusBar = strCheckpointWarning;
3092  }
3093 
3094  // Misc warnings like out of disk space and clock is wrong
3095  if (strMiscWarning != "")
3096  {
3097  nPriority = 1000;
3098  strStatusBar = strMiscWarning;
3099  }
3100 
3101  // Longer invalid proof-of-work chain
3102  if (pindexBest && nBestInvalidWork > nBestChainWork + (pindexBest->GetBlockWork() * 6).getuint256())
3103  {
3104  nPriority = 2000;
3105  strStatusBar = strRPC = _("Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.");
3106  }
3107 
3108  // ppcoin: if detected invalid checkpoint enter safe mode
3109  if (hashInvalidCheckpoint != 0)
3110  {
3111  nPriority = 3000;
3112  strStatusBar = strRPC = "WARNING: Inconsistent checkpoint found! Stop enforcing checkpoints and notify developers to resolve the issue.";
3113  }
3114 
3115  // Alerts
3116  {
3117  LOCK(cs_mapAlerts);
3118  BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
3119  {
3120  const CAlert& alert = item.second;
3121  if (alert.AppliesToMe() && alert.nPriority > nPriority)
3122  {
3123  nPriority = alert.nPriority;
3124  strStatusBar = alert.strStatusBar;
3125  }
3126  }
3127  }
3128 
3129  if (strFor == "statusbar")
3130  return strStatusBar;
3131  else if (strFor == "rpc")
3132  return strRPC;
3133  assert(!"GetWarnings() : invalid parameter");
3134  return "error";
3135 }
3136 
3137 
3138 
3139 
3140 
3141 
3142 
3143 
3145 //
3146 // Messages
3147 //
3148 
3149 
3150 bool static AlreadyHave(const CInv& inv)
3151 {
3152  switch (inv.type)
3153  {
3154  case MSG_TX:
3155  {
3156  bool txInMap = false;
3157  {
3158  LOCK(mempool.cs);
3159  txInMap = mempool.exists(inv.hash);
3160  }
3161  return txInMap || mapOrphanTransactions.count(inv.hash) ||
3162  pcoinsTip->HaveCoins(inv.hash);
3163  }
3164  case MSG_BLOCK:
3165  return mapBlockIndex.count(inv.hash) ||
3166  mapOrphanBlocks.count(inv.hash);
3167  }
3168  // Don't know what it is, just say we already got one
3169  return true;
3170 }
3171 
3172 
3173 
3174 
3175 // The message start string is designed to be unlikely to occur in normal data.
3176 // The characters are rarely used upper ASCII, not valid as UTF-8, and produce
3177 // a large 4-byte int at any alignment.
3178 unsigned char pchMessageStart[4] = { 0xfb, 0xc0, 0xb6, 0xdb }; // Feathercoin: increase each by adding 2 to bitcoin's value.
3179 
3180 
3181 void static ProcessGetData(CNode* pfrom)
3182 {
3183  std::deque<CInv>::iterator it = pfrom->vRecvGetData.begin();
3184 
3185  vector<CInv> vNotFound;
3186 
3187  while (it != pfrom->vRecvGetData.end()) {
3188  // Don't bother if send buffer is too full to respond anyway
3189  if (pfrom->nSendSize >= SendBufferSize())
3190  break;
3191 
3192  // Don't waste work on slow peers until they catch up on the blocks we
3193  // give them. 80 bytes is just the size of a block header - obviously
3194  // the minimum we might return.
3195  if (pfrom->nBlocksRequested * 80 > pfrom->nSendBytes)
3196  break;
3197 
3198  const CInv &inv = *it;
3199  {
3200  boost::this_thread::interruption_point();
3201  it++;
3202 
3203  if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
3204  {
3205  // Send block from disk
3206  map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
3207  pfrom->nBlocksRequested++;
3208  if (mi != mapBlockIndex.end())
3209  {
3210  CBlock block;
3211  block.ReadFromDisk((*mi).second);
3212  if (inv.type == MSG_BLOCK)
3213  pfrom->PushMessage("block", block);
3214  else // MSG_FILTERED_BLOCK)
3215  {
3216  LOCK(pfrom->cs_filter);
3217  if (pfrom->pfilter)
3218  {
3219  CMerkleBlock merkleBlock(block, *pfrom->pfilter);
3220  pfrom->PushMessage("merkleblock", merkleBlock);
3221  // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
3222  // This avoids hurting performance by pointlessly requiring a round-trip
3223  // Note that there is currently no way for a node to request any single transactions we didnt send here -
3224  // they must either disconnect and retry or request the full block.
3225  // Thus, the protocol spec specified allows for us to provide duplicate txn here,
3226  // however we MUST always provide at least what the remote peer needs
3227  typedef std::pair<unsigned int, uint256> PairType;
3228  BOOST_FOREACH(PairType& pair, merkleBlock.vMatchedTxn)
3229  if (!pfrom->setInventoryKnown.count(CInv(MSG_TX, pair.second)))
3230  pfrom->PushMessage("tx", block.vtx[pair.first]);
3231  }
3232  // else
3233  // no response
3234  }
3235 
3236  // Trigger them to send a getblocks request for the next batch of inventory
3237  if (inv.hash == pfrom->hashContinue)
3238  {
3239  // Bypass PushInventory, this must send even if redundant,
3240  // and we want it right after the last block so they don't
3241  // wait for other stuff first.
3242  vector<CInv> vInv;
3243  vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
3244  pfrom->PushMessage("inv", vInv);
3245  pfrom->hashContinue = 0;
3246  }
3247  }
3248  }
3249  else if (inv.IsKnownType())
3250  {
3251  // Send stream from relay memory
3252  bool pushed = false;
3253  {
3254  LOCK(cs_mapRelay);
3255  map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
3256  if (mi != mapRelay.end()) {
3257  pfrom->PushMessage(inv.GetCommand(), (*mi).second);
3258  pushed = true;
3259  }
3260  }
3261  if (!pushed && inv.type == MSG_TX) {
3262  LOCK(mempool.cs);
3263  if (mempool.exists(inv.hash)) {
3264  CTransaction tx = mempool.lookup(inv.hash);
3265  CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
3266  ss.reserve(1000);
3267  ss << tx;
3268  pfrom->PushMessage("tx", ss);
3269  pushed = true;
3270  }
3271  }
3272  if (!pushed) {
3273  vNotFound.push_back(inv);
3274  }
3275  }
3276 
3277  // Track requests for our stuff.
3278  Inventory(inv.hash);
3279 
3280  if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
3281  break;
3282  }
3283  }
3284 
3285  pfrom->vRecvGetData.erase(pfrom->vRecvGetData.begin(), it);
3286 
3287  if (!vNotFound.empty()) {
3288  // Let the peer know that we didn't find what it asked for, so it doesn't
3289  // have to wait around forever. Currently only SPV clients actually care
3290  // about this message: it's needed when they are recursively walking the
3291  // dependencies of relevant unconfirmed transactions. SPV clients want to
3292  // do that because they want to know about (and store and rebroadcast and
3293  // risk analyze) the dependencies of transactions relevant to them, without
3294  // having to download the entire memory pool.
3295  pfrom->PushMessage("notfound", vNotFound);
3296  }
3297 }
3298 
3299 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
3300 {
3302  if (fDebug)
3303  printf("received: %s (%"PRIszu" bytes)\n", strCommand.c_str(), vRecv.size());
3304  if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
3305  {
3306  printf("dropmessagestest DROPPING RECV MESSAGE\n");
3307  return true;
3308  }
3309 
3310 
3311 
3312 
3313 
3314  if (strCommand == "version")
3315  {
3316  // Each connection can only send one version message
3317  if (pfrom->nVersion != 0)
3318  {
3319  pfrom->Misbehaving(1);
3320  return false;
3321  }
3322 
3323  int64 nTime;
3324  CAddress addrMe;
3325  CAddress addrFrom;
3326  uint64 nNonce = 1;
3327  vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
3328  if (pfrom->nVersion < MIN_PEER_PROTO_VERSION)
3329  {
3330  // disconnect from peers older than this proto version
3331  printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
3332  pfrom->fDisconnect = true;
3333  return false;
3334  }
3335 
3336  if (pfrom->nVersion == 10300)
3337  pfrom->nVersion = 300;
3338  if (!vRecv.empty())
3339  vRecv >> addrFrom >> nNonce;
3340  if (!vRecv.empty()) {
3341  vRecv >> pfrom->strSubVer;
3342  pfrom->cleanSubVer = SanitizeString(pfrom->strSubVer);
3343  }
3344  if (!vRecv.empty())
3345  vRecv >> pfrom->nStartingHeight;
3346  if (!vRecv.empty())
3347  vRecv >> pfrom->fRelayTxes; // set to true after we get the first filter* message
3348  else
3349  pfrom->fRelayTxes = true;
3350 
3351  if (pfrom->fInbound && addrMe.IsRoutable())
3352  {
3353  pfrom->addrLocal = addrMe;
3354  SeenLocal(addrMe);
3355  }
3356 
3357  // Disconnect if we connected to ourself
3358  if (nNonce == nLocalHostNonce && nNonce > 1)
3359  {
3360  printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
3361  pfrom->fDisconnect = true;
3362  return true;
3363  }
3364 
3365  // Be shy and don't send version until we hear
3366  if (pfrom->fInbound)
3367  pfrom->PushVersion();
3368 
3369  pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
3370 
3371  AddTimeData(pfrom->addr, nTime);
3372 
3373  // Change version
3374  pfrom->PushMessage("verack");
3375  pfrom->ssSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3376 
3377  if (!pfrom->fInbound)
3378  {
3379  // Advertise our address
3380  if (!fNoListen && !IsInitialBlockDownload())
3381  {
3382  CAddress addr = GetLocalAddress(&pfrom->addr);
3383  if (addr.IsRoutable())
3384  pfrom->PushAddress(addr);
3385  }
3386 
3387  // Get recent addresses
3388  if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
3389  {
3390  pfrom->PushMessage("getaddr");
3391  pfrom->fGetAddr = true;
3392  }
3393  addrman.Good(pfrom->addr);
3394  } else {
3395  if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
3396  {
3397  addrman.Add(addrFrom, addrFrom);
3398  addrman.Good(addrFrom);
3399  }
3400  }
3401 
3402  // Relay alerts
3403  {
3404  LOCK(cs_mapAlerts);
3405  BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
3406  item.second.RelayTo(pfrom);
3407  }
3408 
3409  // ppcoin: relay sync-checkpoint
3410  {
3412  if (!checkpointMessage.IsNull())
3413  checkpointMessage.RelayTo(pfrom);
3414  }
3415 
3416  pfrom->fSuccessfullyConnected = true;
3417 
3418  printf("receive version message: %s: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", pfrom->cleanSubVer.c_str(), pfrom->nVersion, pfrom->nStartingHeight, addrMe.ToString().c_str(), addrFrom.ToString().c_str(), pfrom->addr.ToString().c_str());
3419 
3420  cPeerBlockCounts.input(pfrom->nStartingHeight);
3421 
3422  // ppcoin: ask for pending sync-checkpoint if any
3423  if (!IsInitialBlockDownload())
3425  }
3426 
3427 
3428  else if (pfrom->nVersion == 0)
3429  {
3430  // Must have a version message before anything else
3431  pfrom->Misbehaving(1);
3432  return false;
3433  }
3434 
3435 
3436  else if (strCommand == "verack")
3437  {
3438  pfrom->SetRecvVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3439  }
3440 
3441 
3442  else if (strCommand == "addr")
3443  {
3444  vector<CAddress> vAddr;
3445  vRecv >> vAddr;
3446 
3447  // Don't want addr from older versions unless seeding
3448  if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
3449  return true;
3450  if (vAddr.size() > 1000)
3451  {
3452  pfrom->Misbehaving(20);
3453  return error("message addr size() = %"PRIszu"", vAddr.size());
3454  }
3455 
3456  // Store the new addresses
3457  vector<CAddress> vAddrOk;
3458  int64 nNow = GetAdjustedTime();
3459  int64 nSince = nNow - 10 * 60;
3460  BOOST_FOREACH(CAddress& addr, vAddr)
3461  {
3462  boost::this_thread::interruption_point();
3463 
3464  if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
3465  addr.nTime = nNow - 5 * 24 * 60 * 60;
3466  pfrom->AddAddressKnown(addr);
3467  bool fReachable = IsReachable(addr);
3468  if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
3469  {
3470  // Relay to a limited number of other nodes
3471  {
3472  LOCK(cs_vNodes);
3473  // Use deterministic randomness to send to the same nodes for 24 hours
3474  // at a time so the setAddrKnowns of the chosen nodes prevent repeats
3475  static uint256 hashSalt;
3476  if (hashSalt == 0)
3477  hashSalt = GetRandHash();
3478  uint64 hashAddr = addr.GetHash();
3479  uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60));
3480  hashRand = Hash(BEGIN(hashRand), END(hashRand));
3481  multimap<uint256, CNode*> mapMix;
3482  BOOST_FOREACH(CNode* pnode, vNodes)
3483  {
3484  if (pnode->nVersion < CADDR_TIME_VERSION)
3485  continue;
3486  unsigned int nPointer;
3487  memcpy(&nPointer, &pnode, sizeof(nPointer));
3488  uint256 hashKey = hashRand ^ nPointer;
3489  hashKey = Hash(BEGIN(hashKey), END(hashKey));
3490  mapMix.insert(make_pair(hashKey, pnode));
3491  }
3492  int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
3493  for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
3494  ((*mi).second)->PushAddress(addr);
3495  }
3496  }
3497  // Do not store addresses outside our network
3498  if (fReachable)
3499  vAddrOk.push_back(addr);
3500  }
3501  addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
3502  if (vAddr.size() < 1000)
3503  pfrom->fGetAddr = false;
3504  if (pfrom->fOneShot)
3505  pfrom->fDisconnect = true;
3506  }
3507 
3508 
3509  else if (strCommand == "inv")
3510  {
3511  vector<CInv> vInv;
3512  vRecv >> vInv;
3513  if (vInv.size() > MAX_INV_SZ)
3514  {
3515  pfrom->Misbehaving(20);
3516  return error("message inv size() = %"PRIszu"", vInv.size());
3517  }
3518 
3519  // find last block in inv vector
3520  unsigned int nLastBlock = (unsigned int)(-1);
3521  for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) {
3522  if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) {
3523  nLastBlock = vInv.size() - 1 - nInv;
3524  break;
3525  }
3526  }
3527  for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
3528  {
3529  const CInv &inv = vInv[nInv];
3530 
3531  boost::this_thread::interruption_point();
3532  pfrom->AddInventoryKnown(inv);
3533 
3534  bool fAlreadyHave = AlreadyHave(inv);
3535  if (fDebug)
3536  printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
3537 
3538  if (!fAlreadyHave) {
3539  if (!fImporting && !fReindex)
3540  pfrom->AskFor(inv);
3541  } else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) {
3542  pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
3543  } else if (nInv == nLastBlock) {
3544  // In case we are on a very long side-chain, it is possible that we already have
3545  // the last block in an inv bundle sent in response to getblocks. Try to detect
3546  // this situation and push another getblocks to continue.
3547  pfrom->PushGetBlocks(mapBlockIndex[inv.hash], uint256(0));
3548  if (fDebug)
3549  printf("force request: %s\n", inv.ToString().c_str());
3550  }
3551 
3552  // Track requests for our stuff
3553  Inventory(inv.hash);
3554  }
3555  }
3556 
3557 
3558  else if (strCommand == "getdata")
3559  {
3560  vector<CInv> vInv;
3561  vRecv >> vInv;
3562  if (vInv.size() > MAX_INV_SZ)
3563  {
3564  pfrom->Misbehaving(20);
3565  return error("message getdata size() = %"PRIszu"", vInv.size());
3566  }
3567 
3568  if (fDebugNet || (vInv.size() != 1))
3569  printf("received getdata (%"PRIszu" invsz)\n", vInv.size());
3570 
3571  if ((fDebugNet && vInv.size() > 0) || (vInv.size() == 1))
3572  printf("received getdata for: %s\n", vInv[0].ToString().c_str());
3573 
3574  pfrom->vRecvGetData.insert(pfrom->vRecvGetData.end(), vInv.begin(), vInv.end());
3575  ProcessGetData(pfrom);
3576  }
3577 
3578 
3579  else if (strCommand == "getblocks")
3580  {
3581  CBlockLocator locator;
3582  uint256 hashStop;
3583  vRecv >> locator >> hashStop;
3584 
3585  // Find the last block the caller has in the main chain
3586  CBlockIndex* pindex = locator.GetBlockIndex();
3587 
3588  // Send the rest of the chain
3589  if (pindex)
3590  pindex = pindex->pnext;
3591  int nLimit = 500;
3592  printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().c_str(), nLimit);
3593  for (; pindex; pindex = pindex->pnext)
3594  {
3595  if (pindex->GetBlockHash() == hashStop)
3596  {
3597  printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
3598  break;
3599  }
3600  pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
3601  if (--nLimit <= 0)
3602  {
3603  // When this block is requested, we'll send an inv that'll make them
3604  // getblocks the next batch of inventory.
3605  printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
3606  pfrom->hashContinue = pindex->GetBlockHash();
3607  break;
3608  }
3609  }
3610  }
3611 
3612 
3613  else if (strCommand == "getheaders")
3614  {
3615  CBlockLocator locator;
3616  uint256 hashStop;
3617  vRecv >> locator >> hashStop;
3618 
3619  CBlockIndex* pindex = NULL;
3620  if (locator.IsNull())
3621  {
3622  // If locator is null, return the hashStop block
3623  map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
3624  if (mi == mapBlockIndex.end())
3625  return true;
3626  pindex = (*mi).second;
3627  }
3628  else
3629  {
3630  // Find the last block the caller has in the main chain
3631  pindex = locator.GetBlockIndex();
3632  if (pindex)
3633  pindex = pindex->pnext;
3634  }
3635 
3636  // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
3637  vector<CBlock> vHeaders;
3638  int nLimit = 2000;
3639  printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().c_str());
3640  for (; pindex; pindex = pindex->pnext)
3641  {
3642  vHeaders.push_back(pindex->GetBlockHeader());
3643  if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
3644  break;
3645  }
3646  pfrom->PushMessage("headers", vHeaders);
3647  }
3648 
3649 
3650  else if (strCommand == "tx")
3651  {
3652  vector<uint256> vWorkQueue;
3653  vector<uint256> vEraseQueue;
3654  CDataStream vMsg(vRecv);
3655  CTransaction tx;
3656  vRecv >> tx;
3657 
3658  CInv inv(MSG_TX, tx.GetHash());
3659  pfrom->AddInventoryKnown(inv);
3660 
3661  bool fMissingInputs = false;
3663  if (tx.AcceptToMemoryPool(state, true, true, &fMissingInputs))
3664  {
3665  RelayTransaction(tx, inv.hash);
3666  mapAlreadyAskedFor.erase(inv);
3667  vWorkQueue.push_back(inv.hash);
3668  vEraseQueue.push_back(inv.hash);
3669 
3670  printf("AcceptToMemoryPool: %s %s : accepted %s (poolsz %"PRIszu")\n",
3671  pfrom->addr.ToString().c_str(), pfrom->cleanSubVer.c_str(),
3672  tx.GetHash().ToString().c_str(),
3673  mempool.mapTx.size());
3674 
3675  // Recursively process any orphan transactions that depended on this one
3676  for (unsigned int i = 0; i < vWorkQueue.size(); i++)
3677  {
3678  uint256 hashPrev = vWorkQueue[i];
3679  for (set<uint256>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin();
3680  mi != mapOrphanTransactionsByPrev[hashPrev].end();
3681  ++mi)
3682  {
3683  const uint256& orphanHash = *mi;
3684  const CTransaction& orphanTx = mapOrphanTransactions[orphanHash];
3685  bool fMissingInputs2 = false;
3686  // Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan
3687  // resolution (that is, feeding people an invalid transaction based on LegitTxX in order to get
3688  // anyone relaying LegitTxX banned)
3689  CValidationState stateDummy;
3690 
3691  if (tx.AcceptToMemoryPool(stateDummy, true, true, &fMissingInputs2))
3692  {
3693  printf(" accepted orphan tx %s\n", orphanHash.ToString().c_str());
3694  RelayTransaction(orphanTx, orphanHash);
3695  mapAlreadyAskedFor.erase(CInv(MSG_TX, orphanHash));
3696  vWorkQueue.push_back(orphanHash);
3697  vEraseQueue.push_back(orphanHash);
3698  }
3699  else if (!fMissingInputs2)
3700  {
3701  // invalid or too-little-fee orphan
3702  vEraseQueue.push_back(orphanHash);
3703  printf(" removed orphan tx %s\n", orphanHash.ToString().c_str());
3704  }
3705  }
3706  }
3707 
3708  BOOST_FOREACH(uint256 hash, vEraseQueue)
3709  EraseOrphanTx(hash);
3710  }
3711  else if (fMissingInputs)
3712  {
3713  AddOrphanTx(tx);
3714 
3715  // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
3716  unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
3717  if (nEvicted > 0)
3718  printf("mapOrphan overflow, removed %u tx\n", nEvicted);
3719  }
3720  int nDoS;
3721  if (state.IsInvalid(nDoS))
3722  {
3723  printf("%s from %s %s was not accepted into the memory pool\n", tx.GetHash().ToString().c_str(),
3724  pfrom->addr.ToString().c_str(), pfrom->cleanSubVer.c_str());
3725  if (nDoS > 0)
3726  pfrom->Misbehaving(nDoS);
3727  }
3728  }
3729 
3730 
3731  else if (strCommand == "block" && !fImporting && !fReindex) // Ignore blocks received while importing
3732  {
3733  CBlock block;
3734  vRecv >> block;
3735 
3736  printf("received block %s\n", block.GetHash().ToString().c_str());
3737  // block.print();
3738 
3739  CInv inv(MSG_BLOCK, block.GetHash());
3740  pfrom->AddInventoryKnown(inv);
3741 
3743  if (ProcessBlock(state, pfrom, &block) || state.CorruptionPossible())
3744  mapAlreadyAskedFor.erase(inv);
3745  int nDoS;
3746  if (state.IsInvalid(nDoS))
3747  pfrom->Misbehaving(nDoS);
3748  }
3749 
3750 
3751  else if (strCommand == "getaddr")
3752  {
3753  pfrom->vAddrToSend.clear();
3754  vector<CAddress> vAddr = addrman.GetAddr();
3755  BOOST_FOREACH(const CAddress &addr, vAddr)
3756  pfrom->PushAddress(addr);
3757  }
3758 
3759 
3760  else if (strCommand == "mempool")
3761  {
3762  std::vector<uint256> vtxid;
3763  LOCK2(mempool.cs, pfrom->cs_filter);
3764  mempool.queryHashes(vtxid);
3765  vector<CInv> vInv;
3766  BOOST_FOREACH(uint256& hash, vtxid) {
3767  CInv inv(MSG_TX, hash);
3768  if ((pfrom->pfilter && pfrom->pfilter->IsRelevantAndUpdate(mempool.lookup(hash), hash)) ||
3769  (!pfrom->pfilter))
3770  vInv.push_back(inv);
3771  if (vInv.size() == MAX_INV_SZ)
3772  break;
3773  }
3774  if (vInv.size() > 0)
3775  pfrom->PushMessage("inv", vInv);
3776  }
3777 
3778 
3779  else if (strCommand == "ping")
3780  {
3781  if (pfrom->nVersion > BIP0031_VERSION)
3782  {
3783  uint64 nonce = 0;
3784  vRecv >> nonce;
3785  // Echo the message back with the nonce. This allows for two useful features:
3786  //
3787  // 1) A remote node can quickly check if the connection is operational
3788  // 2) Remote nodes can measure the latency of the network thread. If this node
3789  // is overloaded it won't respond to pings quickly and the remote node can
3790  // avoid sending us more work, like chain download requests.
3791  //
3792  // The nonce stops the remote getting confused between different pings: without
3793  // it, if the remote node sends a ping once per second and this node takes 5
3794  // seconds to respond to each, the 5th ping the remote sends would appear to
3795  // return very quickly.
3796  pfrom->PushMessage("pong", nonce);
3797  }
3798  }
3799 
3800 
3801  else if (strCommand == "alert")
3802  {
3803  CAlert alert;
3804  vRecv >> alert;
3805 
3806  uint256 alertHash = alert.GetHash();
3807  if (pfrom->setKnown.count(alertHash) == 0)
3808  {
3809  if (alert.ProcessAlert())
3810  {
3811  // Relay
3812  pfrom->setKnown.insert(alertHash);
3813  {
3814  LOCK(cs_vNodes);
3815  BOOST_FOREACH(CNode* pnode, vNodes)
3816  alert.RelayTo(pnode);
3817  }
3818  }
3819  else {
3820  // Small DoS penalty so peers that send us lots of
3821  // duplicate/expired/invalid-signature/whatever alerts
3822  // eventually get banned.
3823  // This isn't a Misbehaving(100) (immediate ban) because the
3824  // peer might be an older or different implementation with
3825  // a different signature key, etc.
3826  pfrom->Misbehaving(10);
3827  }
3828  }
3829  }
3830 
3831 
3832  else if (!fBloomFilters &&
3833  (strCommand == "filterload" ||
3834  strCommand == "filteradd" ||
3835  strCommand == "filterclear"))
3836  {
3837  pfrom->CloseSocketDisconnect();
3838  return error("peer %s attempted to set a bloom filter even though we do not advertise that service",
3839  pfrom->addr.ToString().c_str());
3840  }
3841 
3842  else if (strCommand == "checkpoint") // ppcoin synchronized checkpoint
3843  {
3844  CSyncCheckpoint checkpoint;
3845  vRecv >> checkpoint;
3846 
3847  if (checkpoint.ProcessSyncCheckpoint(pfrom))
3848  {
3849  // Relay
3850  pfrom->hashCheckpointKnown = checkpoint.hashCheckpoint;
3851  LOCK(cs_vNodes);
3852  BOOST_FOREACH(CNode* pnode, vNodes)
3853  checkpoint.RelayTo(pnode);
3854  }
3855  }
3856 
3857  else if (strCommand == "filterload")
3858  {
3859  CBloomFilter filter;
3860  vRecv >> filter;
3861 
3862  if (!filter.IsWithinSizeConstraints())
3863  // There is no excuse for sending a too-large filter
3864  pfrom->Misbehaving(100);
3865  else
3866  {
3867  LOCK(pfrom->cs_filter);
3868  delete pfrom->pfilter;
3869  pfrom->pfilter = new CBloomFilter(filter);
3870  pfrom->pfilter->UpdateEmptyFull();
3871  }
3872  pfrom->fRelayTxes = true;
3873  }
3874 
3875 
3876  else if (strCommand == "filteradd")
3877  {
3878  vector<unsigned char> vData;
3879  vRecv >> vData;
3880 
3881  // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
3882  // and thus, the maximum size any matched object can have) in a filteradd message
3883  if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE)
3884  {
3885  pfrom->Misbehaving(100);
3886  } else {
3887  LOCK(pfrom->cs_filter);
3888  if (pfrom->pfilter)
3889  pfrom->pfilter->insert(vData);
3890  else
3891  pfrom->Misbehaving(100);
3892  }
3893  }
3894 
3895 
3896  else if (strCommand == "filterclear")
3897  {
3898  LOCK(pfrom->cs_filter);
3899  delete pfrom->pfilter;
3900  pfrom->pfilter = new CBloomFilter();
3901  pfrom->fRelayTxes = true;
3902  }
3903 
3904 
3905  else
3906  {
3907  // Ignore unknown commands for extensibility
3908  }
3909 
3910 
3911  // Update the last seen time for this node's address
3912  if (pfrom->fNetworkNode)
3913  if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
3914  AddressCurrentlyConnected(pfrom->addr);
3915 
3916 
3917  return true;
3918 }
3919 
3920 // requires LOCK(cs_vRecvMsg)
3922 {
3923  //if (fDebug)
3924  // printf("ProcessMessages(%zu messages)\n", pfrom->vRecvMsg.size());
3925 
3926  //
3927  // Message format
3928  // (4) message start
3929  // (12) command
3930  // (4) size
3931  // (4) checksum
3932  // (x) data
3933  //
3934  bool fOk = true;
3935 
3936  if (!pfrom->vRecvGetData.empty())
3937  ProcessGetData(pfrom);
3938 
3939  // this maintains the order of responses
3940  if (!pfrom->vRecvGetData.empty()) return fOk;
3941 
3942  std::deque<CNetMessage>::iterator it = pfrom->vRecvMsg.begin();
3943  while (!pfrom->fDisconnect && it != pfrom->vRecvMsg.end()) {
3944  // Don't bother if send buffer is too full to respond anyway
3945  if (pfrom->nSendSize >= SendBufferSize())
3946  break;
3947 
3948  // get next message
3949  CNetMessage& msg = *it;
3950 
3951  //if (fDebug)
3952  // printf("ProcessMessages(message %u msgsz, %zu bytes, complete:%s)\n",
3953  // msg.hdr.nMessageSize, msg.vRecv.size(),
3954  // msg.complete() ? "Y" : "N");
3955 
3956  // end, if an incomplete message is found
3957  if (!msg.complete())
3958  break;
3959 
3960  // at this point, any failure means we can delete the current message
3961  it++;
3962 
3963  // Scan for message start
3964  if (memcmp(msg.hdr.pchMessageStart, pchMessageStart, sizeof(pchMessageStart)) != 0) {
3965  printf("\n\nPROCESSMESSAGE: INVALID MESSAGESTART\n\n");
3966  fOk = false;
3967  break;
3968  }
3969 
3970  // Read header
3971  CMessageHeader& hdr = msg.hdr;
3972  if (!hdr.IsValid())
3973  {
3974  printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
3975  continue;
3976  }
3977  string strCommand = hdr.GetCommand();
3978 
3979  // Message size
3980  unsigned int nMessageSize = hdr.nMessageSize;
3981 
3982  // Checksum
3983  CDataStream& vRecv = msg.vRecv;
3984  uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
3985  unsigned int nChecksum = 0;
3986  memcpy(&nChecksum, &hash, sizeof(nChecksum));
3987  if (nChecksum != hdr.nChecksum)
3988  {
3989  printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
3990  strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
3991  continue;
3992  }
3993 
3994  // Process message
3995  bool fRet = false;
3996  try
3997  {
3998  {
3999  LOCK(cs_main);
4000  fRet = ProcessMessage(pfrom, strCommand, vRecv);
4001  }
4002  boost::this_thread::interruption_point();
4003  }
4004  catch (std::ios_base::failure& e)
4005  {
4006  if (strstr(e.what(), "end of data"))
4007  {
4008  // Allow exceptions from under-length message on vRecv
4009  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());
4010  }
4011  else if (strstr(e.what(), "size too large"))
4012  {
4013  // Allow exceptions from over-long size
4014  printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
4015  }
4016  else
4017  {
4018  PrintExceptionContinue(&e, "ProcessMessages()");
4019  }
4020  }
4021  catch (boost::thread_interrupted) {
4022  throw;
4023  }
4024  catch (std::exception& e) {
4025  PrintExceptionContinue(&e, "ProcessMessages()");
4026  } catch (...) {
4027  PrintExceptionContinue(NULL, "ProcessMessages()");
4028  }
4029 
4030  if (!fRet)
4031  printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
4032 
4033  break;
4034  }
4035 
4036  // In case the connection got shut down, its receive buffer was wiped
4037  if (!pfrom->fDisconnect)
4038  pfrom->vRecvMsg.erase(pfrom->vRecvMsg.begin(), it);
4039 
4040  return fOk;
4041 }
4042 
4043 
4044 bool SendMessages(CNode* pto, bool fSendTrickle)
4045 {
4046  TRY_LOCK(cs_main, lockMain);
4047  if (lockMain) {
4048  // Don't send anything until we get their version message
4049  if (pto->nVersion == 0)
4050  return true;
4051 
4052  // Keep-alive ping. We send a nonce of zero because we don't use it anywhere
4053  // right now.
4054  if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSendMsg.empty()) {
4055  uint64 nonce = 0;
4056  if (pto->nVersion > BIP0031_VERSION)
4057  pto->PushMessage("ping", nonce);
4058  else
4059  pto->PushMessage("ping");
4060  }
4061 
4062  // Start block sync
4063  if (pto->fStartSync && !fImporting && !fReindex) {
4064  pto->fStartSync = false;
4065  pto->PushGetBlocks(pindexBest, uint256(0));
4066  }
4067 
4068  // Resend wallet transactions that haven't gotten in a block yet
4069  // Except during reindex, importing and IBD, when old wallet
4070  // transactions become unconfirmed and spams other nodes.
4071  if (!fReindex && !fImporting && !IsInitialBlockDownload())
4072  {
4073  ResendWalletTransactions();
4074  }
4075 
4076  // Address refresh broadcast
4077  static int64 nLastRebroadcast;
4078  if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
4079  {
4080  {
4081  LOCK(cs_vNodes);
4082  BOOST_FOREACH(CNode* pnode, vNodes)
4083  {
4084  // Periodically clear setAddrKnown to allow refresh broadcasts
4085  if (nLastRebroadcast)
4086  pnode->setAddrKnown.clear();
4087 
4088  // Rebroadcast our address
4089  if (!fNoListen)
4090  {
4091  CAddress addr = GetLocalAddress(&pnode->addr);
4092  if (addr.IsRoutable())
4093  pnode->PushAddress(addr);
4094  }
4095  }
4096  }
4097  nLastRebroadcast = GetTime();
4098  }
4099 
4100  //
4101  // Message: addr
4102  //
4103  if (fSendTrickle)
4104  {
4105  vector<CAddress> vAddr;
4106  vAddr.reserve(pto->vAddrToSend.size());
4107  BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
4108  {
4109  // returns true if wasn't already contained in the set
4110  if (pto->setAddrKnown.insert(addr).second)
4111  {
4112  vAddr.push_back(addr);
4113  // receiver rejects addr messages larger than 1000
4114  if (vAddr.size() >= 1000)
4115  {
4116  pto->PushMessage("addr", vAddr);
4117  vAddr.clear();
4118  }
4119  }
4120  }
4121  pto->vAddrToSend.clear();
4122  if (!vAddr.empty())
4123  pto->PushMessage("addr", vAddr);
4124  }
4125 
4126 
4127  //
4128  // Message: inventory
4129  //
4130  vector<CInv> vInv;
4131  vector<CInv> vInvWait;
4132  {
4133  LOCK(pto->cs_inventory);
4134  vInv.reserve(pto->vInventoryToSend.size());
4135  vInvWait.reserve(pto->vInventoryToSend.size());
4136  BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
4137  {
4138  if (pto->setInventoryKnown.count(inv))
4139  continue;
4140 
4141  // trickle out tx inv to protect privacy
4142  if (inv.type == MSG_TX && !fSendTrickle)
4143  {
4144  // 1/4 of tx invs blast to all immediately
4145  static uint256 hashSalt;
4146  if (hashSalt == 0)
4147  hashSalt = GetRandHash();
4148  uint256 hashRand = inv.hash ^ hashSalt;
4149  hashRand = Hash(BEGIN(hashRand), END(hashRand));
4150  bool fTrickleWait = ((hashRand & 3) != 0);
4151 
4152  // always trickle our own transactions
4153  if (!fTrickleWait)
4154  {
4155  CWalletTx wtx;
4156  if (GetTransaction(inv.hash, wtx))
4157  if (wtx.fFromMe)
4158  fTrickleWait = true;
4159  }
4160 
4161  if (fTrickleWait)
4162  {
4163  vInvWait.push_back(inv);
4164  continue;
4165  }
4166  }
4167 
4168  // returns true if wasn't already contained in the set
4169  if (pto->setInventoryKnown.insert(inv).second)
4170  {
4171  vInv.push_back(inv);
4172  if (vInv.size() >= 1000)
4173  {
4174  pto->PushMessage("inv", vInv);
4175  vInv.clear();
4176  }
4177  }
4178  }
4179  pto->vInventoryToSend = vInvWait;
4180  }
4181  if (!vInv.empty())
4182  pto->PushMessage("inv", vInv);
4183 
4184 
4185  //
4186  // Message: getdata
4187  //
4188  vector<CInv> vGetData;
4189  int64 nNow = GetTime() * 1000000;
4190  while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
4191  {
4192  const CInv& inv = (*pto->mapAskFor.begin()).second;
4193  if (!AlreadyHave(inv))
4194  {
4195  if (fDebugNet)
4196  printf("sending getdata: %s\n", inv.ToString().c_str());
4197  vGetData.push_back(inv);
4198  if (vGetData.size() >= 1000)
4199  {
4200  pto->PushMessage("getdata", vGetData);
4201  vGetData.clear();
4202  }
4203  }
4204  pto->mapAskFor.erase(pto->mapAskFor.begin());
4205  }
4206  if (!vGetData.empty())
4207  pto->PushMessage("getdata", vGetData);
4208 
4209  }
4210  return true;
4211 }
4212 
4213 
4214 
4215 
4216 
4217 
4218 
4219 
4220 
4221 
4222 
4223 
4224 
4225 
4227 //
4228 // FeathercoinMiner
4229 //
4230 
4231 int static FormatHashBlocks(void* pbuffer, unsigned int len)
4232 {
4233  unsigned char* pdata = (unsigned char*)pbuffer;
4234  unsigned int blocks = 1 + ((len + 8) / 64);
4235  unsigned char* pend = pdata + 64 * blocks;
4236  memset(pdata + len, 0, 64 * blocks - len);
4237  pdata[len] = 0x80;
4238  unsigned int bits = len * 8;
4239  pend[-1] = (bits >> 0) & 0xff;
4240  pend[-2] = (bits >> 8) & 0xff;
4241  pend[-3] = (bits >> 16) & 0xff;
4242  pend[-4] = (bits >> 24) & 0xff;
4243  return blocks;
4244 }
4245 
4246 static const unsigned int pSHA256InitState[8] =
4247 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
4248 
4249 void SHA256Transform(void* pstate, void* pinput, const void* pinit)
4250 {
4251  SHA256_CTX ctx;
4252  unsigned char data[64];
4253 
4254  SHA256_Init(&ctx);
4255 
4256  for (int i = 0; i < 16; i++)
4257  ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);
4258 
4259  for (int i = 0; i < 8; i++)
4260  ctx.h[i] = ((uint32_t*)pinit)[i];
4261 
4262  SHA256_Update(&ctx, data, sizeof(data));
4263  for (int i = 0; i < 8; i++)
4264  ((uint32_t*)pstate)[i] = ctx.h[i];
4265 }
4266 
4267 // Some explaining would be appreciated
4268 class COrphan
4269 {
4270 public:
4272  set<uint256> setDependsOn;
4273  double dPriority;
4274  double dFeePerKb;
4275 
4277  {
4278  ptx = ptxIn;
4279  dPriority = dFeePerKb = 0;
4280  }
4281 
4282  void print() const
4283  {
4284  printf("COrphan(hash=%s, dPriority=%.1f, dFeePerKb=%.1f)\n",
4285  ptx->GetHash().ToString().c_str(), dPriority, dFeePerKb);
4286  BOOST_FOREACH(uint256 hash, setDependsOn)
4287  printf(" setDependsOn %s\n", hash.ToString().c_str());
4288  }
4289 };
4290 
4291 
4294 
4295 // We want to sort transactions by priority and fee, so:
4296 typedef boost::tuple<double, double, CTransaction*> TxPriority;
4298 {
4299  bool byFee;
4300 public:
4301  TxPriorityCompare(bool _byFee) : byFee(_byFee) { }
4302  bool operator()(const TxPriority& a, const TxPriority& b)
4303  {
4304  if (byFee)
4305  {
4306  if (a.get<1>() == b.get<1>())
4307  return a.get<0>() < b.get<0>();
4308  return a.get<1>() < b.get<1>();
4309  }
4310  else
4311  {
4312  if (a.get<0>() == b.get<0>())
4313  return a.get<1>() < b.get<1>();
4314  return a.get<0>() < b.get<0>();
4315  }
4316  }
4317 };
4318 
4319 CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn)
4320 {
4321  // Create new block
4322  auto_ptr<CBlockTemplate> pblocktemplate(new CBlockTemplate());
4323  if(!pblocktemplate.get())
4324  return NULL;
4325  CBlock *pblock = &pblocktemplate->block; // pointer for convenience
4326 
4327  // Create coinbase tx
4328  CTransaction txNew;
4329  txNew.vin.resize(1);
4330  txNew.vin[0].prevout.SetNull();
4331  txNew.vout.resize(1);
4332  txNew.vout[0].scriptPubKey = scriptPubKeyIn;
4333 
4334  // Add our coinbase tx as first transaction
4335  pblock->vtx.push_back(txNew);
4336  pblocktemplate->vTxFees.push_back(-1); // updated at end
4337  pblocktemplate->vTxSigOps.push_back(-1); // updated at end
4338 
4339  // Largest block you're willing to create:
4340  unsigned int nBlockMaxSize = GetArg("-blockmaxsize", DEFAULT_BLOCK_MAX_SIZE);
4341  // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity:
4342  nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize));
4343 
4344  // How much of the block should be dedicated to high-priority transactions,
4345  // included regardless of the fees they pay
4346  unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", DEFAULT_BLOCK_PRIORITY_SIZE);
4347  nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
4348 
4349  // Minimum block size you want to create; block will be filled with free transactions
4350  // until there are no more or the block reaches this size:
4351  unsigned int nBlockMinSize = GetArg("-blockminsize", 0);
4352  nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);
4353 
4354  // Collect memory pool transactions into the block
4355  int64 nFees = 0;
4356  {
4357  LOCK2(cs_main, mempool.cs);
4358  CBlockIndex* pindexPrev = pindexBest;
4359  CCoinsViewCache view(*pcoinsTip, true);
4360 
4361  // Priority order to process transactions
4362  list<COrphan> vOrphan; // list memory doesn't move
4363  map<uint256, vector<COrphan*> > mapDependers;
4364  bool fPrintPriority = GetBoolArg("-printpriority");
4365 
4366  // This vector will be sorted into a priority queue:
4367  vector<TxPriority> vecPriority;
4368  vecPriority.reserve(mempool.mapTx.size());
4369  for (map<uint256, CTransaction>::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi)
4370  {
4371  CTransaction& tx = (*mi).second;
4372  if (tx.IsCoinBase() || !tx.IsFinal())
4373  continue;
4374 
4375  COrphan* porphan = NULL;
4376  double dPriority = 0;
4377  int64 nTotalIn = 0;
4378  bool fMissingInputs = false;
4379  BOOST_FOREACH(const CTxIn& txin, tx.vin)
4380  {
4381  // Read prev transaction
4382  if (!view.HaveCoins(txin.prevout.hash))
4383  {
4384  // This should never happen; all transactions in the memory
4385  // pool should connect to either transactions in the chain
4386  // or other transactions in the memory pool.
4387  if (!mempool.mapTx.count(txin.prevout.hash))
4388  {
4389  printf("ERROR: mempool transaction missing input\n");
4390  if (fDebug) assert("mempool transaction missing input" == 0);
4391  fMissingInputs = true;
4392  if (porphan)
4393  vOrphan.pop_back();
4394  break;
4395  }
4396 
4397  // Has to wait for dependencies
4398  if (!porphan)
4399  {
4400  // Use list for automatic deletion
4401  vOrphan.push_back(COrphan(&tx));
4402  porphan = &vOrphan.back();
4403  }
4404  mapDependers[txin.prevout.hash].push_back(porphan);
4405  porphan->setDependsOn.insert(txin.prevout.hash);
4406  nTotalIn += mempool.mapTx[txin.prevout.hash].vout[txin.prevout.n].nValue;
4407  continue;
4408  }
4409  const CCoins &coins = view.GetCoins(txin.prevout.hash);
4410 
4411  int64 nValueIn = coins.vout[txin.prevout.n].nValue;
4412  nTotalIn += nValueIn;
4413 
4414  int nConf = pindexPrev->nHeight - coins.nHeight + 1;
4415 
4416  dPriority += (double)nValueIn * nConf;
4417  }
4418  if (fMissingInputs) continue;
4419 
4420  // Priority is sum(valuein * age) / txsize
4421  unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
4422  dPriority /= nTxSize;
4423 
4424  // This is a more accurate fee-per-kilobyte than is used by the client code, because the
4425  // client code rounds up the size to the nearest 1K. That's good, because it gives an
4426  // incentive to create smaller transactions.
4427  double dFeePerKb = double(nTotalIn-tx.GetValueOut()) / (double(nTxSize)/1000.0);
4428 
4429  if (porphan)
4430  {
4431  porphan->dPriority = dPriority;
4432  porphan->dFeePerKb = dFeePerKb;
4433  }
4434  else
4435  vecPriority.push_back(TxPriority(dPriority, dFeePerKb, &(*mi).second));
4436  }
4437 
4438  // Collect transactions into block
4439  uint64 nBlockSize = 1000;
4440  uint64 nBlockTx = 0;
4441  int nBlockSigOps = 100;
4442  bool fSortedByFee = (nBlockPrioritySize <= 0);
4443 
4444  TxPriorityCompare comparer(fSortedByFee);
4445  std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
4446 
4447  while (!vecPriority.empty())
4448  {
4449  // Take highest priority transaction off the priority queue:
4450  double dPriority = vecPriority.front().get<0>();
4451  double dFeePerKb = vecPriority.front().get<1>();
4452  CTransaction& tx = *(vecPriority.front().get<2>());
4453 
4454  std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
4455  vecPriority.pop_back();
4456 
4457  // Size limits
4458  unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
4459  if (nBlockSize + nTxSize >= nBlockMaxSize)
4460  continue;
4461 
4462  // Legacy limits on sigOps:
4463  unsigned int nTxSigOps = tx.GetLegacySigOpCount();
4464  if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
4465  continue;
4466 
4467  // Skip free transactions if we're past the minimum block size:
4468  if (fSortedByFee && (dFeePerKb < CTransaction::nMinTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))
4469  continue;
4470 
4471  // Prioritize by fee once past the priority size or we run out of high-priority
4472  // transactions:
4473  if (!fSortedByFee &&
4474  ((nBlockSize + nTxSize >= nBlockPrioritySize) || (dPriority < COIN * 576 / 250)))
4475  {
4476  fSortedByFee = true;
4477  comparer = TxPriorityCompare(fSortedByFee);
4478  std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
4479  }
4480 
4481  if (!tx.HaveInputs(view))
4482  continue;
4483 
4484  int64 nTxFees = tx.GetValueIn(view)-tx.GetValueOut();
4485 
4486  nTxSigOps += tx.GetP2SHSigOpCount(view);
4487  if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
4488  continue;
4489 
4491  if (!tx.CheckInputs(state, view, true, SCRIPT_VERIFY_P2SH))
4492  continue;
4493 
4494  CTxUndo txundo;
4495  uint256 hash = tx.GetHash();
4496  tx.UpdateCoins(state, view, txundo, pindexPrev->nHeight+1, hash);
4497 
4498  // Added
4499  pblock->vtx.push_back(tx);
4500  pblocktemplate->vTxFees.push_back(nTxFees);
4501  pblocktemplate->vTxSigOps.push_back(nTxSigOps);
4502  nBlockSize += nTxSize;
4503  ++nBlockTx;
4504  nBlockSigOps += nTxSigOps;
4505  nFees += nTxFees;
4506 
4507  if (fPrintPriority)
4508  {
4509  printf("priority %.1f feeperkb %.1f txid %s\n",
4510  dPriority, dFeePerKb, tx.GetHash().ToString().c_str());
4511  }
4512 
4513  // Add transactions that depend on this one to the priority queue
4514  if (mapDependers.count(hash))
4515  {
4516  BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
4517  {
4518  if (!porphan->setDependsOn.empty())
4519  {
4520  porphan->setDependsOn.erase(hash);
4521  if (porphan->setDependsOn.empty())
4522  {
4523  vecPriority.push_back(TxPriority(porphan->dPriority, porphan->dFeePerKb, porphan->ptx));
4524  std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
4525  }
4526  }
4527  }
4528  }
4529  }
4530 
4531  nLastBlockTx = nBlockTx;
4532  nLastBlockSize = nBlockSize;
4533  printf("CreateNewBlock(): total size %"PRI64u"\n", nBlockSize);
4534 
4535  pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);
4536  pblocktemplate->vTxFees[0] = -nFees;
4537 
4538  // Fill in header
4539  pblock->hashPrevBlock = pindexPrev->GetBlockHash();
4540  pblock->UpdateTime(pindexPrev);
4541  pblock->nBits = GetNextWorkRequired(pindexPrev, pblock);
4542  pblock->nNonce = 0;
4543  pblock->vtx[0].vin[0].scriptSig = CScript() << OP_0 << OP_0;
4544  pblocktemplate->vTxSigOps[0] = pblock->vtx[0].GetLegacySigOpCount();
4545 
4546  CBlockIndex indexDummy(*pblock);
4547  indexDummy.pprev = pindexPrev;
4548  indexDummy.nHeight = pindexPrev->nHeight + 1;
4549  CCoinsViewCache viewNew(*pcoinsTip, true);
4551  if (!pblock->ConnectBlock(state, &indexDummy, viewNew, true))
4552  throw std::runtime_error("CreateNewBlock() : ConnectBlock failed");
4553  }
4554 
4555  return pblocktemplate.release();
4556 }
4557 
4559 {
4560  CPubKey pubkey;
4561  if (!reservekey.GetReservedKey(pubkey))
4562  return NULL;
4563 
4564  CScript scriptPubKey = CScript() << pubkey << OP_CHECKSIG;
4565  return CreateNewBlock(scriptPubKey);
4566 }
4567 
4568 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
4569 {
4570  // Update nExtraNonce
4571  static uint256 hashPrevBlock;
4572  if (hashPrevBlock != pblock->hashPrevBlock)
4573  {
4574  nExtraNonce = 0;
4575  hashPrevBlock = pblock->hashPrevBlock;
4576  }
4577  ++nExtraNonce;
4578  unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
4579  pblock->vtx[0].vin[0].scriptSig = (CScript() << nHeight << CBigNum(nExtraNonce)) + COINBASE_FLAGS;
4580  assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100);
4581 
4582  pblock->hashMerkleRoot = pblock->BuildMerkleTree();
4583 }
4584 
4585 
4586 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
4587 {
4588  //
4589  // Pre-build hash buffers
4590  //
4591  struct
4592  {
4593  struct unnamed2
4594  {
4595  int nVersion;
4596  uint256 hashPrevBlock;
4597  uint256 hashMerkleRoot;
4598  unsigned int nTime;
4599  unsigned int nBits;
4600  unsigned int nNonce;
4601  }
4602  block;
4603  unsigned char pchPadding0[64];
4604  uint256 hash1;
4605  unsigned char pchPadding1[64];
4606  }
4607  tmp;
4608  memset(&tmp, 0, sizeof(tmp));
4609 
4610  tmp.block.nVersion = pblock->nVersion;
4611  tmp.block.hashPrevBlock = pblock->hashPrevBlock;
4612  tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
4613  tmp.block.nTime = pblock->nTime;
4614  tmp.block.nBits = pblock->nBits;
4615  tmp.block.nNonce = pblock->nNonce;
4616 
4617  FormatHashBlocks(&tmp.block, sizeof(tmp.block));
4618  FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
4619 
4620  // Byte swap all the input buffer
4621  for (unsigned int i = 0; i < sizeof(tmp)/4; i++)
4622  ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
4623 
4624  // Precalc the first half of the first hash, which stays constant
4625  SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
4626 
4627  memcpy(pdata, &tmp.block, 128);
4628  memcpy(phash1, &tmp.hash1, 64);
4629 }
4630 
4631 
4632 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
4633 {
4634  uint256 hash = pblock->GetPoWHash();
4635  uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
4636 
4637  if (hash > hashTarget)
4638  return false;
4639 
4641  printf("FeathercoinMiner:\n");
4642  printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
4643  pblock->print();
4644  printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
4645 
4646  // Found a solution
4647  {
4648  LOCK(cs_main);
4649  if (pblock->hashPrevBlock != hashBestChain)
4650  return error("FeathercoinMiner : generated block is stale");
4651 
4652  // Remove key from key pool
4653  reservekey.KeepKey();
4654 
4655  // Track how many getdata requests this block gets
4656  {
4657  LOCK(wallet.cs_wallet);
4658  wallet.mapRequestCount[pblock->GetHash()] = 0;
4659  }
4660 
4661  // Process this block the same as if we had received it from another node
4663  if (!ProcessBlock(state, NULL, pblock))
4664  return error("FeathercoinMiner : ProcessBlock, block not accepted");
4665  }
4666 
4667  return true;
4668 }
4669 
4670 void static FeathercoinMiner(CWallet *pwallet)
4671 {
4672  printf("FeathercoinMiner started\n");
4674  RenameThread("feathercoin-miner");
4675 
4676  // Each thread has its own key and counter
4677  CReserveKey reservekey(pwallet);
4678  unsigned int nExtraNonce = 0;
4679 
4680  try { loop {
4681  while (vNodes.empty())
4682  MilliSleep(1000);
4683 
4684  //
4685  // Create new block
4686  //
4687  unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
4688  CBlockIndex* pindexPrev = pindexBest;
4689 
4690  auto_ptr<CBlockTemplate> pblocktemplate(CreateNewBlockWithKey(reservekey));
4691  if (!pblocktemplate.get())
4692  return;
4693  CBlock *pblock = &pblocktemplate->block;
4694  IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
4695 
4696  printf("Running FeathercoinMiner with %"PRIszu" transactions in block (%u bytes)\n", pblock->vtx.size(),
4697  ::GetSerializeSize(*pblock, SER_NETWORK, PROTOCOL_VERSION));
4698 
4699  //
4700  // Pre-build hash buffers
4701  //
4702  char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
4703  char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf);
4704  char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf);
4705 
4706  FormatHashBuffers(pblock, pmidstate, pdata, phash1);
4707 
4708  unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
4709  unsigned int& nBlockBits = *(unsigned int*)(pdata + 64 + 8);
4710  //unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
4711 
4712 
4713  //
4714  // Search
4715  //
4716  int64 nStart = GetTime();
4717  uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
4718  loop
4719  {
4720  unsigned int nHashesDone = 0;
4721 
4722  uint256 thash;
4723  char scratchpad[SCRYPT_SCRATCHPAD_SIZE];
4724  loop
4725  {
4726  scrypt_1024_1_1_256_sp(BEGIN(pblock->nVersion), BEGIN(thash), scratchpad);
4727 
4728  if (thash <= hashTarget)
4729  {
4730  // Found a solution
4732  CheckWork(pblock, *pwallet, reservekey);
4734  break;
4735  }
4736  pblock->nNonce += 1;
4737  nHashesDone += 1;
4738  if ((pblock->nNonce & 0xFF) == 0)
4739  break;
4740  }
4741 
4742  // Meter hashes/sec
4743  static int64 nHashCounter;
4744  if (nHPSTimerStart == 0)
4745  {
4746  nHPSTimerStart = GetTimeMillis();
4747  nHashCounter = 0;
4748  }
4749  else
4750  nHashCounter += nHashesDone;
4751  if (GetTimeMillis() - nHPSTimerStart > 4000)
4752  {
4753  static CCriticalSection cs;
4754  {
4755  LOCK(cs);
4756  if (GetTimeMillis() - nHPSTimerStart > 4000)
4757  {
4758  dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
4759  nHPSTimerStart = GetTimeMillis();
4760  nHashCounter = 0;
4761  static int64 nLogTime;
4762  if (GetTime() - nLogTime > 30 * 60)
4763  {
4764  nLogTime = GetTime();
4765  printf("hashmeter %6.0f khash/s\n", dHashesPerSec/1000.0);
4766  }
4767  }
4768  }
4769  }
4770 
4771  // Check for stop or if block needs to be rebuilt
4772  boost::this_thread::interruption_point();
4773  if (vNodes.empty())
4774  break;
4775  if (pblock->nNonce >= 0xffff0000)
4776  break;
4777  if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
4778  break;
4779  if (pindexPrev != pindexBest)
4780  break;
4781 
4782  // Update nTime every few seconds
4783  pblock->UpdateTime(pindexPrev);
4784  nBlockTime = ByteReverse(pblock->nTime);
4785  if (fTestNet)
4786  {
4787  // Changing pblock->nTime can change work required on testnet:
4788  nBlockBits = ByteReverse(pblock->nBits);
4789  hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
4790  }
4791  }
4792  } }
4793  catch (boost::thread_interrupted)
4794  {
4795  printf("FeathercoinMiner terminated\n");
4796  throw;
4797  }
4798 }
4799 
4800 void GenerateBitcoins(bool fGenerate, CWallet* pwallet)
4801 {
4802  static boost::thread_group* minerThreads = NULL;
4803 
4804  int nThreads = GetArg("-genproclimit", -1);
4805  if (nThreads < 0)
4806  nThreads = boost::thread::hardware_concurrency();
4807 
4808  if (minerThreads != NULL)
4809  {
4810  minerThreads->interrupt_all();
4811  delete minerThreads;
4812  minerThreads = NULL;
4813  }
4814 
4815  if (nThreads == 0 || !fGenerate)
4816  return;
4817 
4818  minerThreads = new boost::thread_group();
4819  for (int i = 0; i < nThreads; i++)
4820  minerThreads->create_thread(boost::bind(&FeathercoinMiner, pwallet));
4821 }
4822 
4823 // Amount compression:
4824 // * If the amount is 0, output 0
4825 // * first, divide the amount (in base units) by the largest power of 10 possible; call the exponent e (e is max 9)
4826 // * if e<9, the last digit of the resulting number cannot be 0; store it as d, and drop it (divide by 10)
4827 // * call the result n
4828 // * output 1 + 10*(9*n + d - 1) + e
4829 // * if e==9, we only know the resulting number is not zero, so output 1 + 10*(n - 1) + 9
4830 // (this is decodable, as d is in [1-9] and e is in [0-9])
4831 
4833 {
4834  if (n == 0)
4835  return 0;
4836  int e = 0;
4837  while (((n % 10) == 0) && e < 9) {
4838  n /= 10;
4839  e++;
4840  }
4841  if (e < 9) {
4842  int d = (n % 10);
4843  assert(d >= 1 && d <= 9);
4844  n /= 10;
4845  return 1 + (n*9 + d - 1)*10 + e;
4846  } else {
4847  return 1 + (n - 1)*10 + 9;
4848  }
4849 }
4850 
4852 {
4853  // x = 0 OR x = 1+10*(9*n + d - 1) + e OR x = 1+10*(n - 1) + 9
4854  if (x == 0)
4855  return 0;
4856  x--;
4857  // x = 10*(9*n + d - 1) + e
4858  int e = x % 10;
4859  x /= 10;
4860  uint64 n = 0;
4861  if (e < 9) {
4862  // x = 9*n + d - 1
4863  int d = (x % 9) + 1;
4864  x /= 9;
4865  // x = n
4866  n = x*10 + d;
4867  } else {
4868  n = x+1;
4869  }
4870  while (e) {
4871  n *= 10;
4872  e--;
4873  }
4874  return n;
4875 }
4876 
4877 
4879 {
4880 public:
4883  // block headers
4884  std::map<uint256, CBlockIndex*>::iterator it1 = mapBlockIndex.begin();
4885  for (; it1 != mapBlockIndex.end(); it1++)
4886  delete (*it1).second;
4887  mapBlockIndex.clear();
4888 
4889  // orphan blocks
4890  std::map<uint256, CBlock*>::iterator it2 = mapOrphanBlocks.begin();
4891  for (; it2 != mapOrphanBlocks.end(); it2++)
4892  delete (*it2).second;
4893  mapOrphanBlocks.clear();
4894 
4895  // orphan transactions
4896  mapOrphanTransactions.clear();
4897  }
CBlockIndex * FindBlockByHeight(int nHeight)
Find a block by height in the currently-connected chain.
Definition: main.cpp:1041
bool error(const char *format,...)
Definition: util.cpp:358
const boost::filesystem::path & GetDataDir(bool fNetSpecific)
Definition: util.cpp:1060
std::multimap< int64, CInv > mapAskFor
Definition: net.h:228
bool Seek(uint64 nPos)
Definition: serialize.h:1320
void PushMessage(const char *pszCommand)
Definition: net.h:454
#define PRIszu
Definition: util.h:70
LRUHandle * prev
Definition: cache.cc:30
void GenerateBitcoins(bool fGenerate, CWallet *pwallet)
Run the miner threads.
Definition: main.cpp:4800
bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
Definition: main.h:520
bool good() const
Definition: serialize.h:1269
CCriticalSection cs_setpwalletRegistered
Definition: main.cpp:29
bool AddOrphanTx(const CTransaction &tx)
Definition: main.cpp:297
CDiskBlockPos GetBlockPos() const
Definition: main.h:1713
int nVersion
Definition: main.h:483
CBlockHeader header
Definition: main.h:2268
#define strprintf(format,...)
Definition: util.h:169
bool HaveCoins(const uint256 &txid)
Definition: main.cpp:285
#define PRI64d
Definition: util.h:51
int64 nHPSTimerStart
Definition: main.cpp:81
CBigNum GetBlockWork() const
Definition: main.h:1754
void TraverseAndBuild(int height, unsigned int pos, const std::vector< uint256 > &vTxid, const std::vector< bool > &vMatch)
Definition: main.cpp:2480
#define THREAD_PRIORITY_LOWEST
Definition: util.h:524
bool addUnchecked(const uint256 &hash, const CTransaction &tx)
Definition: main.cpp:831
bool fDisconnect
Definition: net.h:192
bool remove(const CTransaction &tx, bool fRecursive=false)
Definition: main.cpp:845
unsigned int nTxOffset
Definition: main.h:241
int nVersion
Definition: main.h:1283
void UpdateCoins(const CTransaction &tx, CValidationState &state, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight, const uint256 &txhash)
uint64 nBlocksRequested
Definition: net.h:177
#define THREAD_PRIORITY_NORMAL
Definition: util.h:526
CCriticalSection cs_filter
Definition: net.h:199
FILE * OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly)
Open a block file (blk?????.dat)
Definition: main.cpp:2629
const_iterator begin() const
Definition: serialize.h:884
void KeepKey()
Definition: wallet.cpp:1834
CScript scriptPubKey
Definition: main.h:404
bool AcceptBlock(CValidationState &state, CDiskBlockPos *dbp=NULL)
Definition: main.cpp:2219
bool CheckInputs(CValidationState &state, CCoinsViewCache &view, bool fScriptChecks=true, unsigned int flags=SCRIPT_VERIFY_P2SH|SCRIPT_VERIFY_STRICTENC, std::vector< CScriptCheck > *pvChecks=NULL) const
Definition: main.cpp:1475
CBlockIndex * pprev
Definition: main.h:1633
const char * GetCommand() const
Definition: protocol.cpp:136
int64 nLastSend
Definition: net.h:173
#define TRY_LOCK(cs, name)
Definition: sync.h:110
bool fImporting
Definition: main.cpp:49
Definition: util.cpp:28
unsigned int nonce
Definition: miner_tests.cpp:16
bool Flush()
Definition: main.cpp:259
void SetBackend(CCoinsView &viewIn)
Definition: main.cpp:196
char fFromMe
Definition: wallet.h:379
void FileCommit(FILE *fileout)
Definition: util.cpp:1158
string strMiscWarning
Definition: util.cpp:80
void swap(CScriptCheck &check)
Definition: main.h:1113
std::vector< CTxOut > vout
Definition: main.h:903
unsigned int nTransactions
Definition: main.h:1212
bool SetBestBlock(CBlockIndex *pindex)
Definition: main.cpp:247
uint256 getuint256() const
Definition: bignum.h:225
Definition: main.h:1334
uint64 nLocalHostNonce
Definition: net.cpp:51
bool CheckTransaction(CValidationState &state) const
Definition: main.cpp:556
bool fDebug
Definition: util.cpp:73
#define PAIRTYPE(t1, t2)
Definition: util.h:78
CAddress addr
Definition: net.h:178
static uint64 CompressAmount(uint64 nAmount)
Definition: main.cpp:4832
bool ConnectBlock(CValidationState &state, CBlockIndex *pindex, CCoinsViewCache &coins, bool fJustCheck=false)
Definition: main.cpp:1677
CCriticalSection cs_wallet
Definition: wallet.h:83
#define END(a)
Definition: util.h:40
bool AcceptToMemoryPool(CValidationState &state, bool fCheckInputs=true, bool fLimitFree=true, bool *pfMissingInputs=NULL)
Definition: main.cpp:822
bool ReadReindexing(bool &fReindex)
Definition: txdb.cpp:108
~CMainCleanup()
Definition: main.cpp:4882
GetMinFee_mode
Definition: main.h:467
unsigned int GetLegacySigOpCount() const
Count ECDSA signature operations the old-fashioned (pre-0.6) way.
Definition: main.cpp:488
unsigned int nFlags
Definition: main.h:1102
int nIndex
Definition: main.h:1128
bool IsPayToScriptHash() const
Definition: script.cpp:1734
inv message data
Definition: protocol.h:113
bool ReadLastBlockFile(int &nFile)
Definition: txdb.cpp:113
uint64 nLastBlockTx
Definition: main.cpp:4292
int64 GetBlockTime() const
Definition: main.h:1749
bool AddToWalletIfInvolvingMe(const uint256 &hash, const CTransaction &tx, const CBlock *pblock, bool fUpdate=false, bool fFindBlock=false)
Definition: wallet.cpp:507
void UnregisterWallet(CWallet *pwalletIn)
Unregister a wallet from core.
Definition: main.cpp:104
std::map< COutPoint, CInPoint > mapNextTx
Definition: main.h:2103
CCoinsViewMemPool(CCoinsView &baseIn, CTxMemPool &mempoolIn)
CCoinsView that brings transactions from a memorypool into view.
Definition: main.cpp:272
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
Definition: main.h:1968
bool VerifyScript(const CScript &scriptSig, const CScript &scriptPubKey, const CTransaction &txTo, unsigned int nIn, unsigned int flags, int nHashType)
Definition: script.cpp:1477
std::pair< iterator, bool > insert(const key_type &x)
Definition: mruset.h:36
map< uint256, CAlert > mapAlerts
Definition: alert.cpp:19
void StartShutdown()
Definition: init.cpp:82
uint256 hashBlock
Definition: main.h:1126
int nHeight
Definition: main.h:906
BloomFilter is a probabilistic filter which SPV clients provide so that we can filter the transaction...
Definition: bloom.h:41
bool IsKnownType() const
Definition: protocol.cpp:131
void ThreadScriptCheck()
Run an instance of the script checking thread.
Definition: main.cpp:1672
std::vector< CMerkleTx > vtxPrev
Definition: wallet.h:373
bool RelayTo(CNode *pnode) const
CScript scriptPubKey
Definition: main.h:1099
bool fDebugNet
Definition: util.cpp:74
bool Invalid(bool ret=false)
Definition: main.h:1926
bool SetLimit(uint64 nPos=(uint64)(-1))
Definition: serialize.h:1335
void clear()
Definition: main.cpp:884
CCriticalSection cs_main
Definition: main.cpp:32
int64 nMinimumInputValue
Definition: main.cpp:85
bool SetPos(uint64 nPos)
Definition: serialize.h:1307
void IncrementExtraNonce(CBlock *pblock, CBlockIndex *pindexPrev, unsigned int &nExtraNonce)
Modify the extranonce in a block.
Definition: main.cpp:4568
bool VerifyDB(int nCheckLevel, int nCheckDepth)
Verify consistency of the block and coin databases.
Definition: main.cpp:2730
string GetWarnings(string strFor)
Definition: main.cpp:3075
unsigned int nSize
Definition: main.h:1548
CBlockIndex * GetLastCheckpoint(const std::map< uint256, CBlockIndex * > &mapBlockIndex)
uint256 GetHash() const
Definition: main.h:515
Median filter over a stream of values.
Definition: util.h:462
bool AreInputsStandard(CCoinsViewCache &mapInputs) const
Check for standard transaction types.
Definition: main.cpp:434
bool Sync()
Definition: leveldb.h:142
void queryHashes(std::vector< uint256 > &vtxid)
Definition: main.cpp:892
bool Add(const CAddress &addr, const CNetAddr &source, int64 nTimePenalty=0)
Definition: addrman.h:412
bool WriteBlockIndex(const CDiskBlockIndex &blockindex)
Definition: txdb.cpp:74
double dPriority
Definition: main.cpp:4273
bool IsError()
Definition: main.h:1943
Double ended buffer combining vector and stream-like interfaces.
Definition: serialize.h:799
bool fMerkleVerified
Definition: main.h:1131
bool eof() const
Definition: serialize.h:1274
#define scrypt_1024_1_1_256_sp(input, output, scratchpad)
Definition: scrypt.h:23
Data structure that represents a partial merkle tree.
Definition: main.h:1208
int nFile
Definition: main.h:1642
int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=true, enum GetMinFee_mode mode=GMF_BLOCK) const
Definition: main.cpp:604
CCriticalSection cs_inventory
Definition: net.h:227
uint256 GetPoWHash() const
Definition: main.h:1367
bool SeenLocal(const CService &addr)
vote for a local address
Definition: net.cpp:268
std::vector< CAddress > vAddrToSend
Definition: net.h:218
unsigned long long uint64
Definition: serialize.h:26
pruned version of CTransaction: only retains metadata and unspent transaction outputs ...
Definition: main.h:896
map< uint256, CBlock * > mapOrphanBlocks
Definition: main.cpp:69
int64 GetMedianTimePast() const
Definition: main.h:1777
bool fReindex
Definition: main.cpp:50
unsigned int n
Definition: main.h:282
std::string cleanSubVer
Definition: net.h:186
bool IsDust() const
Definition: main.cpp:367
bool LoadBlockIndexGuts()
Definition: txdb.cpp:191
bool DisconnectBlock(CValidationState &state, CBlockIndex *pindex, CCoinsViewCache &coins, bool *pfClean=NULL)
Undo the effects of this block (with given index) on the UTXO set represented by coins.
Definition: main.cpp:1558
void RandAddSeedPerfmon()
Definition: util.cpp:148
std::string strStatusBar
Definition: alert.h:39
unsigned int GetSizeOfCompactSize(uint64 nSize)
Definition: serialize.h:164
CAddrMan addrman
Definition: net.cpp:53
uint256 nChainWork
Definition: main.h:1651
bool GetStats(CCoinsStats &stats)
Definition: main.cpp:198
COrphan(CTransaction *ptxIn)
Definition: main.cpp:4276
void RenameThread(const char *name)
Definition: util.cpp:1467
uint256 hashGenesisBlock("0x12a765e31ffd4059bada1e25190f6e98c99d9714d334efa41a195a7e7e04bfe2")
const string strMessageMagic
Definition: main.cpp:78
#define FLATDATA(obj)
Definition: serialize.h:304
CSyncCheckpoint checkpointMessage
Undo information for a CTxIn.
Definition: main.h:726
unsigned int nChainTx
Definition: main.h:1658
size_type count(const key_type &k) const
Definition: mruset.h:32
void PushInventory(const CInv &inv)
Definition: net.h:351
bool CheckDiskSpace(uint64 nAdditionalBytes)
Check whether enough disk space is available for an incoming block.
Definition: main.cpp:2591
bool GetCoins(const uint256 &txid, CCoins &coins)
Definition: main.cpp:202
bool IsNewerThan(const CTransaction &old) const
Definition: main.h:537
int64 nTransactionFee
Definition: main.cpp:84
bool BatchWrite(const std::map< uint256, CCoins > &mapCoins, CBlockIndex *pindex)
Definition: main.cpp:197
bool fBenchmark
Definition: main.cpp:51
limitedmap< CInv, int64 > mapAlreadyAskedFor(MAX_INV_SZ)
void PrintBlockTree()
Print the loaded block tree.
Definition: main.cpp:2916
unsigned int nUndoSize
Definition: main.h:1549
bool CheckCheckpointPubKey()
static std::string strMasterPrivKey
bool IsAvailable(unsigned int nPos) const
Definition: main.h:1080
std::deque< CInv > vRecvGetData
Definition: net.h:167
vector< CNode * > vNodes
Definition: net.cpp:56
unsigned int nChecksum
Definition: protocol.h:65
CBlockTemplate * CreateNewBlockWithKey(CReserveKey &reservekey)
Definition: main.cpp:4558
int64 GetTime()
Definition: util.cpp:1298
int ScriptSigArgsExpected(txnouttype t, const std::vector< std::vector< unsigned char > > &vSolutions)
Definition: script.cpp:1312
CDataStream vRecv
Definition: net.h:122
bool WriteSyncCheckpoint(const uint256 &hashCheckpoint)
bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
Definition: main.cpp:2124
static int64 nMinTxFee
Fees smaller than this (in satoshi) are considered zero fee (for transaction creation) ...
Definition: main.h:480
uint256 BuildMerkleTree() const
Definition: main.h:1386
int GetDepthInMainChain() const
Definition: main.h:1164
bool CheckSyncCheckpoint(const uint256 &hashBlock, const CBlockIndex *pindexPrev)
FILE * OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
Definition: main.cpp:2606
bool VerifySignature(const CCoins &txFrom, const CTransaction &txTo, unsigned int nIn, unsigned int flags, int nHashType)
Verify a signature.
Definition: main.cpp:1470
int64 GetTimeMillis()
Definition: util.h:340
unsigned int GetP2SHSigOpCount(CCoinsViewCache &mapInputs) const
Count ECDSA signature operations in pay-to-script-hash inputs.
Definition: main.cpp:1411
bool CheckWork(CBlock *pblock, CWallet &wallet, CReserveKey &reservekey)
Check mined block.
Definition: main.cpp:4632
int std::string int dummy
Definition: util.h:164
void MilliSleep(int64 n)
Definition: util.h:106
#define CLIENT_VERSION_IS_RELEASE
Definition: clientversion.h:15
bool BatchWrite(const std::map< uint256, CCoins > &mapCoins, CBlockIndex *pindex)
Definition: main.cpp:252
std::vector< CAddress > GetAddr()
Definition: addrman.h:479
#define loop
Definition: util.h:38
CCriticalSection cs_hashSyncCheckpoint
int nHashType
Definition: main.h:1103
class CMainCleanup instance_of_cmaincleanup
bool operator()() const
Definition: main.cpp:1463
int GetBlocksToMaturity() const
Definition: main.cpp:931
int nScriptCheckThreads
Definition: main.cpp:48
void AddBlock(unsigned int nHeightIn, uint64 nTimeIn)
Definition: main.h:1584
CBigNum & SetCompact(unsigned int nCompact)
Definition: bignum.h:289
#define LOCK2(cs1, cs2)
Definition: sync.h:109
std::deque< CNetMessage > vRecvMsg
Definition: net.h:168
uint256 hashInvalidCheckpoint
std::vector< uint256 > vHash
Definition: main.h:1218
int nStartingHeight
Definition: net.h:214
bool fClient
Definition: net.h:188
std::string strSubVer
Definition: net.h:186
Used to relay blocks as header + vector to filtered nodes.
Definition: main.h:2264
CBlockTreeDB * pblocktree
Global variable that points to the active block tree (protected by cs_main)
Definition: main.cpp:290
unsigned int nTime
Definition: main.h:1666
unsigned int CalcTreeWidth(int height)
Definition: main.h:1224
bool TruncateFile(FILE *file, unsigned int length)
Definition: util.cpp:1184
bool fNoListen
Definition: util.cpp:83
bool GetBoolArg(const std::string &strArg, bool fDefault)
Return boolean argument or default value.
Definition: util.cpp:600
bool fTestNet
Definition: util.cpp:81
unsigned int nStatus
Definition: main.h:1661
double getdouble() const
Definition: uint256.h:59
unsigned int nLockTime
Definition: main.h:486
void AskForPendingSyncCheckpoint(CNode *pfrom)
Access to the block database (blocks/index/)
Definition: txdb.h:32
CScript COINBASE_FLAGS
Definition: main.cpp:76
CBlockHeader GetBlockHeader() const
Definition: main.h:1731
int nVersion
Definition: main.h:910
uint256 hashMerkleRoot
Definition: main.h:1285
string SanitizeString(const string &str)
Definition: util.cpp:461
unsigned int GetSerializeSize(char a, int, int=0)
Definition: serialize.h:106
Abstract view on the open txout dataset.
Definition: main.h:2146
bool SetBestChain(CValidationState &state, CBlockIndex *pindexNew)
Connect/disconnect blocks until pindexNew is the new tip of the active block chain.
Definition: main.cpp:1832
bool fInbound
Definition: net.h:189
bool HaveCoins(const uint256 &txid)
Definition: main.cpp:237
unsigned int nDataPos
Definition: main.h:1645
bool IsInitialBlockDownload()
Check whether we are doing an initial block download (synchronizing from disk or network) ...
Definition: main.cpp:1276
#define printf
Definition: rpcdump.cpp:12
bool fOneShot
Definition: net.h:187
An input of a transaction.
Definition: main.h:323
An alert is a combination of a serialized CUnsignedAlert and a signature.
Definition: alert.h:68
virtual bool GetCoins(const uint256 &txid, CCoins &coins)
Definition: main.cpp:181
bool fCoinBase
Definition: main.h:730
unsigned int uint32_t
Definition: stdint.h:21
void AddressCurrentlyConnected(const CService &addr)
Definition: net.cpp:419
uint64 GetRand(uint64 nMax)
Definition: util.cpp:175
unsigned int GetSigOpCount(bool fAccurate) const
Definition: script.cpp:1686
CMainCleanup()
Definition: main.cpp:4881
#define LOCK(cs)
Definition: sync.h:108
CCoinsView * base
Definition: main.h:2179
std::vector< CTxOut > vout
Definition: main.h:485
std::map< uint256, CCoins >::iterator FetchCoins(const uint256 &txid)
Definition: main.cpp:214
size_type size() const
Definition: serialize.h:888
txnouttype
Definition: script.h:40
bool CorruptionPossible()
Definition: main.h:1953
void UnloadBlockIndex()
Unload database information.
Definition: main.cpp:2803
int type
Definition: protocol.h:135
bool fTxIndex
Definition: main.cpp:52
bool SendMessages(CNode *pto, bool fSendTrickle)
Send queued protocol messages to be sent to a give node.
Definition: main.cpp:4044
CBlockIndex * GetBlockIndex()
Definition: main.h:2050
int GetNumBlocksOfPeers()
Get the number of active peers.
Definition: main.cpp:1271
bool IsReachable(const CNetAddr &addr)
check whether a given address is in a network we can probably connect to
Definition: net.cpp:290
CBlockHeader GetBlockHeader() const
Definition: main.h:1374
An encapsulated public key.
Definition: key.h:40
uint256 AutoSelectSyncCheckpoint()
bool ReadBestInvalidWork(CBigNum &bnBestInvalidWork)
Definition: txdb.cpp:79
bool GetCoins(const uint256 &txid, CCoins &coins)
Definition: main.cpp:274
bool IsInMainChain() const
Definition: main.h:1763
std::vector< CTxIn > vin
Definition: main.h:484
bool DoS(int level, bool ret=false, bool corruptionIn=false)
Definition: main.h:1918
set< uint256 > setDependsOn
Definition: main.cpp:4272
uint256 hashPrevBlock
Definition: main.h:1284
int64 GetAdjustedTime()
Definition: util.cpp:1317
MTState * state
Definition: db_test.cc:1708
CClientUIInterface uiInterface
Definition: init.cpp:32
CMessageHeader hdr
Definition: net.h:119
bool IsPushOnly() const
Definition: script.h:537
const int nForkTwo
Definition: main.cpp:58
C++ wrapper for BIGNUM (OpenSSL bignum)
Definition: bignum.h:51
mruset< CInv > setInventoryKnown
Definition: net.h:225
void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length)
Definition: util.cpp:1216
int64 GetBlockTime() const
Definition: main.h:1326
bool AddToBlockIndex(CValidationState &state, const CDiskBlockPos &pos)
Definition: main.cpp:2020
std::vector< uint256 > vMerkleBranch
Definition: main.h:1127
A CService with information about it as peer.
Definition: protocol.h:76
unsigned int SendBufferSize()
Definition: net.h:32
unsigned int nBits
Definition: main.h:1667
uint256 hashSyncCheckpoint
bool Flush()
Definition: leveldb.h:138
bool SetBestBlock(CBlockIndex *pindex)
Definition: main.cpp:195
uint64 nLastBlockSize
Definition: main.cpp:4293
bool LoadBlockIndex()
Load the block tree and coins database from disk.
Definition: main.cpp:2815
uint256 hash
Definition: protocol.h:136
uint256 hashMerkleRoot
Definition: main.h:1665
void RelayTransaction(const CTransaction &tx, const uint256 &hash)
Definition: net.cpp:1871
std::map< uint256, CTransaction > mapTx
Definition: main.h:2102
virtual bool HaveCoins(const uint256 &txid)
Definition: main.cpp:183
bool Solver(const CScript &scriptPubKey, txnouttype &typeRet, vector< vector< unsigned char > > &vSolutionsRet)
Definition: script.cpp:1127
CTransaction * ptx
Definition: main.cpp:4271
int nTargetSpacing
Definition: main.cpp:1090
bool WriteBlockFileInfo(int nFile, const CBlockFileInfo &fileinfo)
Definition: txdb.cpp:89
bool AcceptToMemoryPool(bool fCheckInputs=true, bool fLimitFree=true)
Definition: main.cpp:939
std::string ToString() const
Definition: netbase.cpp:1126
CTxOut txout
Definition: main.h:729
unsigned int nNonce
Definition: main.h:1288
CCoinsViewCache(CCoinsView &baseIn, bool fDummy=false)
Definition: main.cpp:200
std::string strCheckpointWarning
bool IsNull()
Definition: main.h:2007
uint256 TraverseAndExtract(int height, unsigned int pos, unsigned int &nBitsUsed, unsigned int &nHashUsed, std::vector< uint256 > &vMatch)
Definition: main.cpp:2498
int64 GetValueIn(CCoinsViewCache &mapInputs) const
Amount of bitcoins coming in to this transaction Note that lightweight clients may not know anything ...
Definition: main.cpp:1399
int GetTotalBlocksEstimate()
void PrintExceptionContinue(std::exception *pex, const char *pszThread)
Definition: util.cpp:1023
uint256 Hash(const T1 pbegin, const T1 pend)
Definition: hash.h:16
void swap(CCoins &to)
Definition: main.h:926
uint64 nServices
Definition: net.h:158
An output of a transaction.
Definition: main.h:400
Used to marshal pointers into hashes for db storage.
Definition: main.h:1840
void SyncWithWallets(const uint256 &hash, const CTransaction &tx, const CBlock *pblock, bool fUpdate)
Push an updated transaction to all registered wallets.
Definition: main.cpp:129
bool GetReservedKey(CPubKey &pubkey)
Definition: wallet.cpp:1813
bool fGetAddr
Definition: net.h:220
std::string GetCommand() const
Definition: protocol.cpp:40
bool ReadSyncCheckpoint(uint256 &hashCheckpoint)
Definition: txdb.cpp:248
std::string DateTimeStrFormat(const char *pszFormat, int64 nTime)
Definition: util.h:352
int64 GetValueOut() const
Amount of bitcoins spent by this transaction.
Definition: main.h:602
bool EvalScript(vector< vector< unsigned char > > &stack, const CScript &script, const CTransaction &txTo, unsigned int nIn, unsigned int flags, int nHashType)
Definition: script.cpp:292
bool CheckProofOfWork(uint256 hash, unsigned int nBits)
Check whether a block hash satisfies the proof-of-work requirement specified by nBits.
Definition: main.cpp:1254
unsigned int nHeight
Definition: main.h:731
bool CheckBlock(int nHeight, const uint256 &hash)
Definition: checkpoints.cpp:61
bool WriteLastBlockFile(int nFile)
Definition: txdb.cpp:97
std::map< uint256, int > mapRequestCount
Definition: wallet.h:117
CPartialMerkleTree txn
Definition: main.h:2269
bool Error()
Definition: main.h:1929
Queue for verifications that have to be performed.
Definition: checkqueue.h:25
bool IsNull() const
Definition: main.h:236
CCoinsViewBacked(CCoinsView &viewIn)
Definition: main.cpp:190
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: main.h:278
CCoinsViewCache * pcoinsTip
Global variable that points to the active CCoinsView (protected by cs_main)
Definition: main.cpp:289
std::vector< CTxInUndo > vprevout
Definition: main.h:768
bool Abort(const std::string &msg)
Definition: main.h:1933
std::string GetHex() const
Definition: uint256.h:298
std::vector< uint256 > GetMerkleBranch(int nIndex) const
Definition: main.h:1411
bool IsRoutable() const
Definition: netbase.cpp:732
size_t nSendSize
Definition: net.h:161
bool ConnectBestBlock(CValidationState &state)
Find the best known block, and make it the tip of the block chain.
Definition: main.cpp:1321
const char * base
Definition: testharness.cc:17
bool ProcessMessages(CNode *pfrom)
Process protocol messages received from a given node.
Definition: main.cpp:3921
void PushVersion()
Definition: net.cpp:540
void print() const
Definition: main.h:1494
std::string ToString() const
Definition: main.h:649
CBlockTemplate * CreateNewBlock(const CScript &scriptPubKeyIn)
Generate a new block, without valid proof-of-work.
Definition: main.cpp:4319
bool IsStandard() const
Definition: main.h:575
multimap< uint256, CBlock * > mapOrphanBlocksByPrev
Definition: main.cpp:70
CCriticalSection cs
Definition: main.h:2101
CTxMemPool mempool
Definition: main.cpp:34
unsigned int nPos
Definition: main.h:211
bool ReadFlag(const std::string &name, bool &fValue)
Definition: txdb.cpp:183
static const int CURRENT_VERSION
Definition: main.h:1282
const int nForkThree
Definition: main.cpp:60
int nTargetTimespan
Definition: main.cpp:1089
bool ReadBlockFileInfo(int nFile, CBlockFileInfo &fileinfo)
Definition: txdb.cpp:93
CBlockIndex * InsertBlockIndex(uint256 hash)
Create a new block index entry for a given block hash.
Definition: main.cpp:2637
A transaction with a bunch of additional info that only the owner cares about.
Definition: wallet.h:367
bool ReadTxIndex(const uint256 &txid, CDiskTxPos &pos)
Definition: txdb.cpp:168
Closure representing one script verification Note that this stores references to the spending transac...
Definition: main.h:1096
bool WriteToDisk(CDiskBlockPos &pos)
Definition: main.h:1442
CTransaction & lookup(uint256 hash)
Definition: main.h:2124
bool HaveInputs(CCoinsViewCache &view) const
Definition: main.cpp:1442
bool IsSyncCheckpointEnforced()
bool fStartSync
Definition: net.h:215
void SetThreadPriority(int nPriority)
Definition: util.h:529
CBlockIndex * GetBestBlock()
Definition: main.cpp:241
int nVersion
Definition: main.h:1664
std::vector< bool > vBits
Definition: main.h:1215
const uint256 & GetTxHash(unsigned int nIndex) const
Definition: main.h:1405
virtual bool GetStats(CCoinsStats &stats)
Definition: main.cpp:187
double dHashesPerSec
Definition: main.cpp:80
unsigned int nUndoPos
Definition: main.h:1648
CScript scriptSig
Definition: main.h:327
int64 GetTimeMicros()
Definition: util.h:346
IMPLEMENT_SERIALIZE(READWRITE(FLATDATA(pchMessageStart));READWRITE(FLATDATA(pchCommand));READWRITE(nMessageSize);READWRITE(nChecksum);) public char pchMessageStart[MESSAGE_START_SIZE]
Definition: protocol.h:43
bool fCoinBase
Definition: main.h:900
virtual bool SetBestBlock(CBlockIndex *pindex)
Definition: main.cpp:185
IP address (IPv6, or IPv4 using mapped IPv6 range (::FFFF:0:0/96))
Definition: netbase.h:34
#define BEGIN(a)
Definition: util.h:39
int size()
Definition: addrman.h:393
CService addrLocal
Definition: net.h:180
Capture information about block/transaction validation.
Definition: main.h:1907
256-bit unsigned integer
Definition: uint256.h:537
uint64 GetHash() const
Definition: netbase.cpp:882
bool removeConflicts(const CTransaction &tx)
Definition: main.cpp:869
CBlockIndex * pindexGenesisBlock
Definition: main.cpp:40
uint256 hashBestChain
Definition: main.cpp:44
unsigned int nTime
Definition: protocol.h:106
const CTransaction * ptxTo
Definition: main.h:1100
bool SendSyncCheckpoint(uint256 hashCheckpoint)
static uint64 DecompressAmount(uint64 nAmount)
Definition: main.cpp:4851
void pruneSpent(const uint256 &hash, CCoins &coins)
Definition: main.cpp:645
CCriticalSection cs_mapAlerts
Definition: alert.cpp:20
uint256 ExtractMatches(std::vector< uint256 > &vMatch)
Definition: main.cpp:2544
unsigned int nTime
Definition: main.h:1286
void SHA256Transform(void *pstate, void *pinput, const void *pinit)
Definition: main.cpp:4249
CBlockFileInfo infoLastBlockFile
Definition: main.cpp:2603
CCriticalSection cs_mapRelay
Definition: net.cpp:60
uint256 GetHash() const
Definition: main.h:1321
CBlockIndex * pnext
Definition: main.h:1636
uint256 nBestInvalidWork
Definition: main.cpp:43
bool Spend(const COutPoint &out, CTxInUndo &undo)
Definition: main.h:1056
void AddTimeData(const CNetAddr &ip, int64 nTime)
Definition: util.cpp:1322
bool IsRelevantAndUpdate(const CTransaction &tx, const uint256 &hash)
Definition: bloom.cpp:102
bool ProcessBlock(CValidationState &state, CNode *pfrom, CBlock *pblock, CDiskBlockPos *dbp)
Process an incoming block.
Definition: main.cpp:2339
bool IsNull() const
bool SetCoins(const uint256 &txid, const CCoins &coins)
Definition: main.cpp:192
A key allocated from the key pool.
Definition: wallet.h:318
void FindByte(char ch)
Definition: serialize.h:1350
uint32_t ByteReverse(uint32_t value)
Definition: util.h:548
int64 nValue
Definition: main.h:403
std::vector< std::pair< unsigned int, uint256 > > vMatchedTxn
Definition: main.h:2274
The block chain is a tree shaped structure starting with the genesis block at the root...
Definition: main.h:1626
bool fBloomFilters
Definition: util.cpp:82
bool HaveCoins(const uint256 &txid)
Definition: main.cpp:193
Undo information for a CBlock.
Definition: main.h:776
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:244
std::vector< CInv > vInventoryToSend
Definition: net.h:226
uint256 hashContinue
Definition: net.h:211
Undo information for a CTransaction.
Definition: main.h:764
unsigned int nCoinCacheSize
Definition: main.cpp:53
std::string ToString() const
Definition: uint256.h:343
void print() const
Definition: main.cpp:4282
bool IsPruned() const
Definition: main.h:1086
string FormatMoney(int64 n, bool fPlus)
Definition: util.cpp:389
unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
Definition: main.cpp:340
std::string _(const char *psz)
Translation function: Call Translate signal on UI interface, which returns a boost::optional result...
Definition: ui_interface.h:104
boost::signals2::signal< void()> NotifyBlocksChanged
Block chain changed.
Definition: ui_interface.h:86
unsigned int nMessageSize
Definition: protocol.h:64
void Good(const CService &addr, int64 nTime=GetAdjustedTime())
Definition: addrman.h:443
Stats stats
Definition: db_bench.cc:291
bool exists(uint256 hash)
Definition: main.h:2119
bool AbortNode(const std::string &strMessage)
Abort with a message.
Definition: main.cpp:2583
An inpoint - a combination of a transaction and an index n into its vin.
Definition: main.h:263
void RegisterWallet(CWallet *pwalletIn)
Register a wallet to receive updates from core.
Definition: main.cpp:96
A CWallet is an extension of a keystore, which also maintains a set of transactions and balances...
Definition: wallet.h:69
bool WriteTxIndex(const std::vector< std::pair< uint256, CDiskTxPos > > &list)
Definition: txdb.cpp:172
bool GetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock, bool fAllowSlow)
Retrieve a transaction (from memory pool, or from disk, if possible)
Definition: main.cpp:968
unsigned int nTransactionsUpdated
Definition: main.cpp:35
CMerkleBlock(const CBlock &block, CBloomFilter &filter)
Definition: main.cpp:2430
bool AcceptPendingSyncCheckpoint()
set< CBlockIndex *, CBlockIndexWorkComparator > setBlockIndexValid
Definition: main.cpp:46
CAddress GetLocalAddress(const CNetAddr *paddrPeer)
Definition: net.cpp:122
CBlockIndex * GetBestBlock()
Definition: main.cpp:194
bool IsCoinBase() const
Definition: main.h:965
boost::tuple< double, double, CTransaction * > TxPriority
Definition: main.cpp:4296
std::string ToString() const
Definition: main.h:1579
bool fRelayTxes
Definition: net.h:197
bool GetCoins(const uint256 &txid, CCoins &coins)
Definition: main.cpp:191
boost::signals2::signal< bool(const std::string &message, const std::string &caption, unsigned int style), boost::signals2::last_value< bool > > ThreadSafeMessageBox
Show message box.
Definition: ui_interface.h:71
bool IsCoinBase() const
Definition: main.h:566
bool Misbehaving(int howmuch)
Definition: net.cpp:580
CBlockIndex * pindexTip
Definition: main.h:2197
bool operator()(const TxPriority &a, const TxPriority &b)
Definition: main.cpp:4302
virtual bool BatchWrite(const std::map< uint256, CCoins > &mapCoins, CBlockIndex *pindex)
Definition: main.cpp:186
bool WriteFlag(const std::string &name, bool fValue)
Definition: txdb.cpp:179
void UpdateTime(const CBlockIndex *pindexPrev)
Definition: main.cpp:1373
#define PRI64u
Definition: util.h:52
map< uint256, CTransaction > mapOrphanTransactions
Definition: main.cpp:72
bool IsInvalid()
Definition: main.h:1940
CBlockIndex * pindexBest
Definition: main.cpp:45
bool SetCoins(const uint256 &txid, const CCoins &coins)
Definition: main.cpp:232
bool IsNull() const
Definition: main.h:288
unsigned int nIn
Definition: main.h:1101
int nVersion
Definition: main.h:732
int nLastBlockFile
Definition: main.cpp:2604
int nVersion
Definition: net.h:181
bool complete() const
Definition: net.h:132
std::vector< CTransaction > vtx
Definition: main.h:1338
unsigned int GetCompact() const
Definition: bignum.h:308
std::string GetArg(const std::string &strArg, const std::string &strDefault)
Return string argument or default value.
Definition: util.cpp:586
unsigned int GetCacheSize()
Definition: main.cpp:266
void Add(std::vector< T > &vChecks)
Definition: checkqueue.h:181
std::string ToString() const
Definition: netbase.cpp:777
uint64 nSendBytes
Definition: net.h:163
CBloomFilter * pfilter
Definition: net.h:200
CDiskBlockPos GetUndoPos() const
Definition: main.h:1722
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: main.h:477
int nHeight
Definition: main.h:1639
CCoinsView backed by another CCoinsView.
Definition: main.h:2176
bool LoadExternalBlockFile(FILE *fileIn, CDiskBlockPos *dbp)
Import blocks from an external file.
Definition: main.cpp:2986
Information about a peer.
Definition: net.h:154
static const int CURRENT_VERSION
Definition: main.h:482
FILE * OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly)
Open an undo file (rev?????.dat)
Definition: main.cpp:2633
RAII-style controller object for a CCheckQueue that guarantees the passed queue is finished before co...
Definition: checkqueue.h:14
uint256 GetRandHash()
Definition: util.cpp:195
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: main.h:2194
unsigned int nBits
Definition: main.h:1287
int nBestHeight
Definition: main.cpp:41
bool IsStandard(std::string &strReason) const
Check for standard transaction types.
bool AcceptWalletTransaction(bool fCheckInputs=true)
Definition: main.cpp:947
std::string ToString() const
Definition: protocol.cpp:143
bool accept(CValidationState &state, CTransaction &tx, bool fCheckInputs, bool fLimitFree, bool *pfMissingInputs)
Definition: main.cpp:658
Wrapper around a FILE* that implements a ring buffer to deserialize from.
Definition: serialize.h:1220
void SetVersion(int n)
Definition: serialize.h:1000
uint64 GetPos()
Definition: serialize.h:1302
bool InitBlockIndex()
Initialize a new block tree database + block data on disk.
Definition: main.cpp:2836
bool AppliesToMe() const
Definition: alert.cpp:122
std::vector< CTxUndo > vtxundo
Definition: main.h:779
int nFile
Definition: main.h:210
bool CheckBlock(CValidationState &state, bool fCheckPOW=true, bool fCheckMerkleRoot=true) const
Definition: main.cpp:2165
COutPoint prevout
Definition: main.h:326
unsigned char pchMessageStart[4]
Definition: main.cpp:3178
CCriticalSection cs_LastBlockFile
Definition: main.cpp:2602
Definition: script.h:70
bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64 nTime, bool fKnown=false)
Definition: main.cpp:2070
bool ReadFromDisk(const CDiskBlockPos &pos)
Definition: main.h:1468
void PushGetBlocks(CBlockIndex *pindexBegin, uint256 hashEnd)
Definition: net.cpp:85
TxPriorityCompare(bool _byFee)
Definition: main.cpp:4301
CCoinsView that brings transactions from a memorypool into view.
Definition: main.h:2229
const int nForkOne
Definition: main.cpp:56
map< uint256, CBlockIndex * > mapBlockIndex
Definition: main.cpp:37
double GuessVerificationProgress(CBlockIndex *pindex)
Definition: checkpoints.cpp:75
vector< unsigned char > ParseHex(const char *psz)
Definition: util.cpp:500
uint32_t hash
Definition: cache.cc:34
static int64 nMinRelayTxFee
Fees smaller than this (in satoshi) are considered zero fee (for relaying)
Definition: main.h:481
int64 nTimeBestReceived
Definition: main.cpp:47
CCriticalSection cs_vNodes
Definition: net.cpp:57
double dFeePerKb
Definition: main.cpp:4274
bool MoneyRange(int64 nValue)
Definition: main.h:58
map< uint256, set< uint256 > > mapOrphanTransactionsByPrev
Definition: main.cpp:73
unsigned int nTx
Definition: main.h:1655
uint256 nBestChainWork
Definition: main.cpp:42
set< CWallet * > setpwalletRegistered
Definition: main.cpp:30
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: main.h:1278
Definition: main.h:471
virtual CBlockIndex * GetBestBlock()
Definition: main.cpp:184
RAII wrapper for FILE*.
Definition: serialize.h:1108
std::set< CAddress > setAddrKnown
Definition: net.h:219
map< string, string > mapArgs
Definition: util.cpp:71
bool IsValid() const
Definition: protocol.cpp:48
map< CInv, CDataStream > mapRelay
Definition: net.cpp:58
int atoi(const std::string &str)
Definition: util.h:271
bool empty() const
Definition: serialize.h:889
static uint256 CheckMerkleBranch(uint256 hash, const std::vector< uint256 > &vMerkleBranch, int nIndex)
Definition: main.h:1427
uint256 GetBlockHash() const
Definition: main.h:1744
A transaction with a merkle branch linking it to the block chain.
Definition: main.h:1123
std::deque< CSerializeData > vSendMsg
Definition: net.h:164
static const CTxOut & GetOutputFor(const CTxIn &input, CCoinsViewCache &mapInputs)
Definition: main.cpp:1392
void runCommand(std::string strCommand)
Definition: util.cpp:1460
uint256 CalcHash(int height, unsigned int pos, const std::vector< uint256 > &vTxid)
Definition: main.cpp:2463
CMedianFilter< int > cPeerBlockCounts(8, 0)
std::map< uint256, CCoins > cacheCoins
Definition: main.h:2198
static bool IsSuperMajority(int minVersion, const CBlockIndex *pstart, unsigned int nRequired, unsigned int nToCheck)
Returns true if there are nRequired or more blocks of minVersion or above in the last nToCheck blocks...
Definition: main.cpp:2325
void PushAddress(const CAddress &addr)
Definition: net.h:333
CDataStream ssSend
Definition: net.h:160
Message header.
Definition: protocol.h:33
void FormatHashBuffers(CBlock *pblock, char *pmidstate, char *pdata, char *phash1)
Do mining precalculation.
Definition: main.cpp:4586
uint256 hash
Definition: main.h:281
virtual bool SetCoins(const uint256 &txid, const CCoins &coins)
Definition: main.cpp:182
long long int64
Definition: serialize.h:25
const uint256 * phashBlock
Definition: main.h:1630
bool WriteBestInvalidWork(const CBigNum &bnBestInvalidWork)
Definition: txdb.cpp:84
int nPriority
Definition: alert.h:35