Anoncoin  0.9.4
P2P Digital Currency
main.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2014 The Bitcoin developers
3 // Copyright (c) 2013-2015 The Anoncoin Core developers
4 // Distributed under the MIT/X11 software license, see the accompanying
5 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 
7 #include "main.h"
8 
9 #include "addrman.h"
10 #include "alert.h"
11 #include "chainparams.h"
12 #include "checkpoints.h"
13 #include "checkqueue.h"
14 #include "init.h"
15 #include "net.h"
16 #include "txdb.h"
17 #include "txmempool.h"
18 #include "ui_interface.h"
19 #include "util.h"
20 
21 #include <sstream>
22 
23 #include <boost/algorithm/string/replace.hpp>
24 #include <boost/filesystem.hpp>
25 #include <boost/filesystem/fstream.hpp>
26 
27 using namespace std;
28 using namespace boost;
29 
30 #if defined(NDEBUG)
31 # error "Anoncoin cannot be compiled without assertions."
32 #endif
33 
34 //
35 // Global state
36 //
37 
39 
41 
42 map<uint256, CBlockIndex*> mapBlockIndex;
45 int64_t nTimeBestReceived = 0;
47 bool fImporting = false;
48 bool fReindex = false;
49 bool fBenchmark = false;
50 bool fTxIndex = false;
51 unsigned int nCoinCacheSize = 5000;
52 
54 int64_t CTransaction::nMinTxFee = 100000; // Override with -mintxfee
56 int64_t CTransaction::nMinRelayTxFee = 100000;
57 
58 struct COrphanBlock {
61  vector<unsigned char> vchBlock;
62 };
63 map<uint256, COrphanBlock*> mapOrphanBlocks;
64 multimap<uint256, COrphanBlock*> mapOrphanBlocksByPrev;
65 
66 struct COrphanTx {
69 };
70 map<uint256, COrphanTx> mapOrphanTransactions;
71 map<uint256, set<uint256> > mapOrphanTransactionsByPrev;
72 void EraseOrphansFor(NodeId peer);
73 
74 // Constant stuff for coinbase transactions we create:
76 
77 const string strMessageMagic = "Anoncoin Signed Message:\n";
78 
79 // Internal stuff
80 namespace {
81  struct CBlockIndexWorkComparator
82  {
83  bool operator()(CBlockIndex *pa, CBlockIndex *pb) {
84  // First sort by most total work, ...
85  if (pa->nChainWork > pb->nChainWork) return false;
86  if (pa->nChainWork < pb->nChainWork) return true;
87 
88  // ... then by earliest time received, ...
89  if (pa->nSequenceId < pb->nSequenceId) return false;
90  if (pa->nSequenceId > pb->nSequenceId) return true;
91 
92  // Use pointer address as tie breaker (should only happen with blocks
93  // loaded from disk, as those all have id 0).
94  if (pa < pb) return false;
95  if (pa > pb) return true;
96 
97  // Identical blocks.
98  return false;
99  }
100  };
101 
102  CBlockIndex *pindexBestInvalid;
103  // may contain all CBlockIndex*'s that have validness >=BLOCK_VALID_TRANSACTIONS, and must contain those who aren't failed
104  set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexValid;
105 
106  CCriticalSection cs_LastBlockFile;
107  CBlockFileInfo infoLastBlockFile;
108  int nLastBlockFile = 0;
109 
110  // Every received block is assigned a unique and increasing identifier, so we
111  // know which one to give priority in case of a fork.
112  CCriticalSection cs_nBlockSequenceId;
113  // Blocks loaded from disk are assigned id 0, so start the counter at 1.
114  uint32_t nBlockSequenceId = 1;
115 
116  // Sources of received blocks, to be able to send them reject messages or ban
117  // them, if processing happens afterwards. Protected by cs_main.
118  map<uint256, NodeId> mapBlockSource;
119 
120  // Blocks that are in flight, and that are in the queue to be downloaded.
121  // Protected by cs_main.
122  struct QueuedBlock {
123  uint256 hash;
124  CBlockIndex *pindex; // Optional.
125  int64_t nTime; // Time of "getdata" request in microseconds.
126  int nQueuedBefore; // Number of blocks in flight at the time of request.
127  };
128  map<uint256, pair<NodeId, list<QueuedBlock>::iterator> > mapBlocksInFlight;
129  map<uint256, pair<NodeId, list<uint256>::iterator> > mapBlocksToDownload;
130 }
131 
133 //
134 // dispatching functions
135 //
136 
137 // These functions dispatch to one or all registered wallets
138 
139 namespace {
140 struct CMainSignals {
141  // Notifies listeners of updated transaction data (passing hash, transaction, and optionally the block it is found in.
142  boost::signals2::signal<void (const uint256 &, const CTransaction &, const CBlock *)> SyncTransaction;
143  // Notifies listeners of an erased transaction (currently disabled, requires transaction replacement).
144  boost::signals2::signal<void (const uint256 &)> EraseTransaction;
145  // Notifies listeners of an updated transaction without new data (for now: a coinbase potentially becoming visible).
146  boost::signals2::signal<void (const uint256 &)> UpdatedTransaction;
147  // Notifies listeners of a new active block chain.
148  boost::signals2::signal<void (const CBlockLocator &)> SetBestChain;
149  // Notifies listeners about an inventory item being seen on the network.
150  boost::signals2::signal<void (const uint256 &)> Inventory;
151  // Tells listeners to broadcast their data.
152  boost::signals2::signal<void ()> Broadcast;
153 } g_signals;
154 }
155 
157  g_signals.SyncTransaction.connect(boost::bind(&CWalletInterface::SyncTransaction, pwalletIn, _1, _2, _3));
158  g_signals.EraseTransaction.connect(boost::bind(&CWalletInterface::EraseFromWallet, pwalletIn, _1));
159  g_signals.UpdatedTransaction.connect(boost::bind(&CWalletInterface::UpdatedTransaction, pwalletIn, _1));
160  g_signals.SetBestChain.connect(boost::bind(&CWalletInterface::SetBestChain, pwalletIn, _1));
161  g_signals.Inventory.connect(boost::bind(&CWalletInterface::Inventory, pwalletIn, _1));
162  g_signals.Broadcast.connect(boost::bind(&CWalletInterface::ResendWalletTransactions, pwalletIn));
163 }
164 
166  g_signals.Broadcast.disconnect(boost::bind(&CWalletInterface::ResendWalletTransactions, pwalletIn));
167  g_signals.Inventory.disconnect(boost::bind(&CWalletInterface::Inventory, pwalletIn, _1));
168  g_signals.SetBestChain.disconnect(boost::bind(&CWalletInterface::SetBestChain, pwalletIn, _1));
169  g_signals.UpdatedTransaction.disconnect(boost::bind(&CWalletInterface::UpdatedTransaction, pwalletIn, _1));
170  g_signals.EraseTransaction.disconnect(boost::bind(&CWalletInterface::EraseFromWallet, pwalletIn, _1));
171  g_signals.SyncTransaction.disconnect(boost::bind(&CWalletInterface::SyncTransaction, pwalletIn, _1, _2, _3));
172 }
173 
175  g_signals.Broadcast.disconnect_all_slots();
176  g_signals.Inventory.disconnect_all_slots();
177  g_signals.SetBestChain.disconnect_all_slots();
178  g_signals.UpdatedTransaction.disconnect_all_slots();
179  g_signals.EraseTransaction.disconnect_all_slots();
180  g_signals.SyncTransaction.disconnect_all_slots();
181 }
182 
183 void SyncWithWallets(const uint256 &hash, const CTransaction &tx, const CBlock *pblock) {
184  g_signals.SyncTransaction(hash, tx, pblock);
185 }
186 
188 //
189 // Registration of network node signals.
190 //
191 
192 namespace {
193 
194 struct CBlockReject {
195  unsigned char chRejectCode;
196  string strRejectReason;
197  uint256 hashBlock;
198 };
199 
200 // Maintain validation-specific state about nodes, protected by cs_main, instead
201 // by CNode's own locks. This simplifies asynchronous operation, where
202 // processing of incoming data is done after the ProcessMessage call returns,
203 // and we're no longer holding the node's locks.
204 struct CNodeState {
205  // Accumulated misbehaviour score for this peer.
206  int nMisbehavior;
207  // Whether this peer should be disconnected and banned.
208  bool fShouldBan;
209  // String name of this peer (debugging/logging purposes).
210  std::string name;
211  // List of asynchronously-determined block rejections to notify this peer about.
212  std::vector<CBlockReject> rejects;
213  // The best known block we know this peer has announced.
214  CBlockIndex *pindexBestKnownBlock;
215  // The hash of the last unknown block this peer has announced.
216  uint256 hashLastUnknownBlock;
217  // The last full block we both have.
218  CBlockIndex *pindexLastCommonBlock;
219  // Whether we've started headers synchronization with this peer.
220  bool fSyncStarted;
221  // Since when we're stalling block download progress (in microseconds), or 0.
222  int64_t nStallingSince;
223  list<QueuedBlock> vBlocksInFlight;
224  int nBlocksInFlight;
225  // Whether we consider this a preferred download peer.
226  bool fPreferredDownload;
227 
228  // Following variables removed in v0.99 upgrade to come.
229  list<uint256> vBlocksToDownload;
230  int nBlocksToDownload;
231  int64_t nLastBlockReceive;
232  int64_t nLastBlockProcess;
233 
234  CNodeState() {
235  nMisbehavior = 0;
236  fShouldBan = false;
237  pindexBestKnownBlock = NULL;
238  hashLastUnknownBlock = uint256(0);
239  pindexLastCommonBlock = NULL;
240  fSyncStarted = false;
241  nStallingSince = 0;
242  nBlocksInFlight = 0;
243  fPreferredDownload = false;
244  // Following initializations to remove in future upgrade...
245  nBlocksToDownload = 0;
246  nLastBlockReceive = 0;
247  nLastBlockProcess = 0;
248  }
249 };
250 
251 // Map maintaining per-node state. Requires cs_main.
252 map<NodeId, CNodeState> mapNodeState;
253 
254 // Requires cs_main.
255 CNodeState *State(NodeId pnode) {
256  map<NodeId, CNodeState>::iterator it = mapNodeState.find(pnode);
257  if (it == mapNodeState.end())
258  return NULL;
259  return &it->second;
260 }
261 
262 int GetHeight()
263 {
264  LOCK(cs_main);
265  return chainActive.Height();
266 }
267 
268 void InitializeNode(NodeId nodeid, const CNode *pnode) {
269  LOCK(cs_main);
270  CNodeState &state = mapNodeState.insert(std::make_pair(nodeid, CNodeState())).first->second;
271  state.name = pnode->addrName;
272 }
273 
274 void FinalizeNode(NodeId nodeid) {
275  LOCK(cs_main);
276  CNodeState *state = State(nodeid);
277 
278  BOOST_FOREACH(const QueuedBlock& entry, state->vBlocksInFlight)
279  mapBlocksInFlight.erase(entry.hash);
280  BOOST_FOREACH(const uint256& hash, state->vBlocksToDownload)
281  mapBlocksToDownload.erase(hash);
282  EraseOrphansFor(nodeid);
283 
284  mapNodeState.erase(nodeid);
285 }
286 
287 // Requires cs_main.
288 void MarkBlockAsReceived(const uint256 &hash, NodeId nodeFrom = -1) {
289  map<uint256, pair<NodeId, list<uint256>::iterator> >::iterator itToDownload = mapBlocksToDownload.find(hash);
290  if (itToDownload != mapBlocksToDownload.end()) {
291  CNodeState *state = State(itToDownload->second.first);
292  state->vBlocksToDownload.erase(itToDownload->second.second);
293  state->nBlocksToDownload--;
294  mapBlocksToDownload.erase(itToDownload);
295  }
296 
297  map<uint256, pair<NodeId, list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash);
298  if (itInFlight != mapBlocksInFlight.end()) {
299  CNodeState *state = State(itInFlight->second.first);
300  state->vBlocksInFlight.erase(itInFlight->second.second);
301  state->nBlocksInFlight--;
302  if (itInFlight->second.first == nodeFrom)
303  state->nLastBlockReceive = GetTimeMicros();
304  mapBlocksInFlight.erase(itInFlight);
305  }
306 
307 }
308 
309 // Requires cs_main.
310 bool AddBlockToQueue(NodeId nodeid, const uint256 &hash) {
311  if (mapBlocksToDownload.count(hash) || mapBlocksInFlight.count(hash))
312  return false;
313 
314  CNodeState *state = State(nodeid);
315  if (state == NULL)
316  return false;
317 
318  list<uint256>::iterator it = state->vBlocksToDownload.insert(state->vBlocksToDownload.end(), hash);
319  state->nBlocksToDownload++;
320  if (state->nBlocksToDownload > 5000)
321  Misbehaving(nodeid, 10);
322  mapBlocksToDownload[hash] = std::make_pair(nodeid, it);
323  return true;
324 }
325 
326 // Requires cs_main.
327 void MarkBlockAsInFlight(NodeId nodeid, const uint256 &hash) {
328  CNodeState *state = State(nodeid);
329  assert(state != NULL);
330 
331  // Make sure it's not listed somewhere already.
332  MarkBlockAsReceived(hash);
333 
334  QueuedBlock newentry = {hash, NULL, GetTimeMicros(), state->nBlocksInFlight};
335  if (state->nBlocksInFlight == 0)
336  state->nLastBlockReceive = newentry.nTime; // Reset when a first request is sent.
337  list<QueuedBlock>::iterator it = state->vBlocksInFlight.insert(state->vBlocksInFlight.end(), newentry);
338  state->nBlocksInFlight++;
339  mapBlocksInFlight[hash] = std::make_pair(nodeid, it);
340 }
341 
342 }
343 
345  LOCK(cs_main);
346  CNodeState *state = State(nodeid);
347  if (state == NULL)
348  return false;
349  stats.nMisbehavior = state->nMisbehavior;
350  stats.nSyncHeight = state->pindexBestKnownBlock ? state->pindexBestKnownBlock->nHeight : -1;
351  stats.nCommonHeight = state->pindexLastCommonBlock ? state->pindexLastCommonBlock->nHeight : -1;
352  BOOST_FOREACH(const QueuedBlock& queue, state->vBlocksInFlight) {
353  if (queue.pindex)
354  stats.vHeightInFlight.push_back(queue.pindex->nHeight);
355  }
356  return true;
357 }
358 
360 {
361  nodeSignals.GetHeight.connect(&GetHeight);
362  nodeSignals.ProcessMessages.connect(&ProcessMessages);
363  nodeSignals.SendMessages.connect(&SendMessages);
364  nodeSignals.InitializeNode.connect(&InitializeNode);
365  nodeSignals.FinalizeNode.connect(&FinalizeNode);
366 }
367 
369 {
370  nodeSignals.GetHeight.disconnect(&GetHeight);
371  nodeSignals.ProcessMessages.disconnect(&ProcessMessages);
372  nodeSignals.SendMessages.disconnect(&SendMessages);
373  nodeSignals.InitializeNode.disconnect(&InitializeNode);
374  nodeSignals.FinalizeNode.disconnect(&FinalizeNode);
375 }
376 
378 //
379 // CChain implementation
380 //
381 
383  if (pindex == NULL) {
384  vChain.clear();
385  return NULL;
386  }
387  vChain.resize(pindex->nHeight + 1);
388  while (pindex && vChain[pindex->nHeight] != pindex) {
389  vChain[pindex->nHeight] = pindex;
390  pindex = pindex->pprev;
391  }
392  return pindex;
393 }
394 
396  int nStep = 1;
397  std::vector<uint256> vHave;
398  vHave.reserve(32);
399 
400  if (!pindex)
401  pindex = Tip();
402  while (pindex) {
403  vHave.push_back(pindex->GetBlockHash());
404  // Stop when we have added the genesis block.
405  if (pindex->nHeight == 0)
406  break;
407  // Exponentially larger steps back, plus the genesis block.
408  int nHeight = std::max(pindex->nHeight - nStep, 0);
409  // In case pindex is not in this chain, iterate pindex->pprev to find blocks.
410  while (pindex->nHeight > nHeight && !Contains(pindex))
411  pindex = pindex->pprev;
412  // If pindex is in this chain, use direct height-based access.
413  if (pindex->nHeight > nHeight)
414  pindex = (*this)[nHeight];
415  if (vHave.size() > 10)
416  nStep *= 2;
417  }
418 
419  return CBlockLocator(vHave);
420 }
421 
423  // Find the first block the caller has in the main chain
424  BOOST_FOREACH(const uint256& hash, locator.vHave) {
425  std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
426  if (mi != mapBlockIndex.end())
427  {
428  CBlockIndex* pindex = (*mi).second;
429  if (Contains(pindex))
430  return pindex;
431  }
432  }
433  return Genesis();
434 }
435 
438 
440 //
441 // mapOrphanTransactions
442 //
443 
444 bool AddOrphanTx(const CTransaction& tx, NodeId peer)
445 {
446  uint256 hash = tx.GetHash();
447  if (mapOrphanTransactions.count(hash))
448  return false;
449 
450  // Ignore big transactions, to avoid a
451  // send-big-orphans memory exhaustion attack. If a peer has a legitimate
452  // large transaction with a missing parent then we assume
453  // it will rebroadcast it later, after the parent transaction(s)
454  // have been mined or received.
455  // 10,000 orphans, each of which is at most 5,000 bytes big is
456  // at most 500 megabytes of orphans:
457  unsigned int sz = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
458  if (sz > 5000)
459  {
460  LogPrint("mempool", "ignoring large orphan tx (size: %u, hash: %s)\n", sz, hash.ToString());
461  return false;
462  }
463 
464  mapOrphanTransactions[hash].tx = tx;
465  mapOrphanTransactions[hash].fromPeer = peer;
466  BOOST_FOREACH(const CTxIn& txin, tx.vin)
467  mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash);
468 
469  LogPrint("mempool", "stored orphan tx %s (mapsz %u prevsz %u)\n", hash.ToString(),
471  return true;
472 }
473 
474 void static EraseOrphanTx(uint256 hash)
475 {
476  map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.find(hash);
477  if (it == mapOrphanTransactions.end())
478  return;
479  BOOST_FOREACH(const CTxIn& txin, it->second.tx.vin)
480  {
481  map<uint256, set<uint256> >::iterator itPrev = mapOrphanTransactionsByPrev.find(txin.prevout.hash);
482  if (itPrev == mapOrphanTransactionsByPrev.end())
483  continue;
484  itPrev->second.erase(hash);
485  if (itPrev->second.empty())
486  mapOrphanTransactionsByPrev.erase(itPrev);
487  }
488  mapOrphanTransactions.erase(it);
489 }
490 
492 {
493  int nErased = 0;
494  map<uint256, COrphanTx>::iterator iter = mapOrphanTransactions.begin();
495  while (iter != mapOrphanTransactions.end())
496  {
497  map<uint256, COrphanTx>::iterator maybeErase = iter++; // increment to avoid iterator becoming invalid
498  if (maybeErase->second.fromPeer == peer)
499  {
500  EraseOrphanTx(maybeErase->second.tx.GetHash());
501  ++nErased;
502  }
503  }
504  if (nErased > 0) LogPrint("mempool", "Erased %d orphan tx from peer %d\n", nErased, peer);
505 }
506 
507 
508 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
509 {
510  unsigned int nEvicted = 0;
511  while (mapOrphanTransactions.size() > nMaxOrphans)
512  {
513  // Evict a random orphan:
514  uint256 randomhash = GetRandHash();
515  map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
516  if (it == mapOrphanTransactions.end())
517  it = mapOrphanTransactions.begin();
518  EraseOrphanTx(it->first);
519  ++nEvicted;
520  }
521  return nEvicted;
522 }
523 
524 
525 
526 
527 
528 
529 
530 bool IsStandardTx(const CTransaction& tx, string& reason)
531 {
532  AssertLockHeld(cs_main);
533  if (tx.nVersion > CTransaction::CURRENT_VERSION || tx.nVersion < 1) {
534  reason = "version";
535  return false;
536  }
537 
538  // Treat non-final transactions as non-standard to prevent a specific type
539  // of double-spend attack, as well as DoS attacks. (if the transaction
540  // can't be mined, the attacker isn't expending resources broadcasting it)
541  // Basically we don't want to propagate transactions that can't included in
542  // the next block.
543  //
544  // However, IsFinalTx() is confusing... Without arguments, it uses
545  // chainActive.Height() to evaluate nLockTime; when a block is accepted, chainActive.Height()
546  // is set to the value of nHeight in the block. However, when IsFinalTx()
547  // is called within CBlock::AcceptBlock(), the height of the block *being*
548  // evaluated is what is used. Thus if we want to know if a transaction can
549  // be part of the *next* block, we need to call IsFinalTx() with one more
550  // than chainActive.Height().
551  //
552  // Timestamps on the other hand don't get any special treatment, because we
553  // can't know what timestamp the next block will have, and there aren't
554  // timestamp applications where it matters.
555  if (!IsFinalTx(tx, chainActive.Height() + 1)) {
556  reason = "non-final";
557  return false;
558  }
559 
560  // Extremely large transactions with lots of inputs can cost the network
561  // almost as much to process as they cost the sender in fees, because
562  // computing signature hashes is O(ninputs*txsize). Limiting transactions
563  // to MAX_STANDARD_TX_SIZE mitigates CPU exhaustion attacks.
564  unsigned int sz = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
565  if (sz >= MAX_STANDARD_TX_SIZE) {
566  reason = "tx-size";
567  return false;
568  }
569 
570  BOOST_FOREACH(const CTxIn& txin, tx.vin)
571  {
572  // Biggest 'standard' txin is a 15-of-15 P2SH multisig with compressed
573  // keys. (remember the 520 byte limit on redeemScript size) That works
574  // out to a (15*(33+1))+3=513 byte redeemScript, 513+1+15*(73+1)=1624
575  // bytes of scriptSig, which we round off to 1650 bytes for some minor
576  // future-proofing. That's also enough to spend a 20-of-20
577  // CHECKMULTISIG scriptPubKey, though such a scriptPubKey is not
578  // considered standard)
579  if (txin.scriptSig.size() > 1650) {
580  reason = "scriptsig-size";
581  return false;
582  }
583  if (!txin.scriptSig.IsPushOnly()) {
584  reason = "scriptsig-not-pushonly";
585  return false;
586  }
587  if (!txin.scriptSig.HasCanonicalPushes()) {
588  reason = "scriptsig-non-canonical-push";
589  return false;
590  }
591  }
592 
593  unsigned int nDataOut = 0;
594  txnouttype whichType;
595  BOOST_FOREACH(const CTxOut& txout, tx.vout) {
596  if (!::IsStandard(txout.scriptPubKey, whichType)) {
597  reason = "scriptpubkey";
598  return false;
599  }
600  if (whichType == TX_NULL_DATA)
601  nDataOut++;
602  else if (txout.IsDust(CTransaction::nMinRelayTxFee)) {
603  reason = "dust";
604  return false;
605  }
606  }
607 
608  // only one OP_RETURN txout is permitted
609  if (nDataOut > 1) {
610  reason = "multi-op-return";
611  return false;
612  }
613 
614  return true;
615 }
616 
617 bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)
618 {
619  AssertLockHeld(cs_main);
620  // Time based nLockTime implemented in 0.1.6
621  if (tx.nLockTime == 0)
622  return true;
623  if (nBlockHeight == 0)
624  nBlockHeight = chainActive.Height();
625  if (nBlockTime == 0)
626  nBlockTime = GetAdjustedTime();
627  if ((int64_t)tx.nLockTime < ((int64_t)tx.nLockTime < LOCKTIME_THRESHOLD ? (int64_t)nBlockHeight : nBlockTime))
628  return true;
629  BOOST_FOREACH(const CTxIn& txin, tx.vin)
630  if (!txin.IsFinal())
631  return false;
632  return true;
633 }
634 
635 //
636 // Check transaction inputs, and make sure any
637 // pay-to-script-hash transactions are evaluating IsStandard scripts
638 //
639 // Why bother? To avoid denial-of-service attacks; an attacker
640 // can submit a standard HASH... OP_EQUAL transaction,
641 // which will get accepted into blocks. The redemption
642 // script can be anything; an attacker could use a very
643 // expensive-to-check-upon-redemption script like:
644 // DUP CHECKSIG DROP ... repeated 100 times... OP_1
645 //
646 bool AreInputsStandard(const CTransaction& tx, CCoinsViewCache& mapInputs)
647 {
648  if (tx.IsCoinBase())
649  return true; // Coinbases don't use vin normally
650 
651  for (unsigned int i = 0; i < tx.vin.size(); i++)
652  {
653  const CTxOut& prev = mapInputs.GetOutputFor(tx.vin[i]);
654 
655  vector<vector<unsigned char> > vSolutions;
656  txnouttype whichType;
657  // get the scriptPubKey corresponding to this input:
658  const CScript& prevScript = prev.scriptPubKey;
659  if (!Solver(prevScript, whichType, vSolutions))
660  return false;
661  int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
662  if (nArgsExpected < 0)
663  return false;
664 
665  // Transactions with extra stuff in their scriptSigs are
666  // non-standard. Note that this EvalScript() call will
667  // be quick, because if there are any operations
668  // beside "push data" in the scriptSig the
669  // IsStandard() call returns false
670  vector<vector<unsigned char> > stack;
671  if (!EvalScript(stack, tx.vin[i].scriptSig, tx, i, false, 0))
672  return false;
673 
674  if (whichType == TX_SCRIPTHASH)
675  {
676  if (stack.empty())
677  return false;
678  CScript subscript(stack.back().begin(), stack.back().end());
679  vector<vector<unsigned char> > vSolutions2;
680  txnouttype whichType2;
681  if (!Solver(subscript, whichType2, vSolutions2))
682  return false;
683  if (whichType2 == TX_SCRIPTHASH)
684  return false;
685 
686  int tmpExpected;
687  tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
688  if (tmpExpected < 0)
689  return false;
690  nArgsExpected += tmpExpected;
691  }
692 
693  if (stack.size() != (unsigned int)nArgsExpected)
694  return false;
695  }
696 
697  return true;
698 }
699 
700 unsigned int GetLegacySigOpCount(const CTransaction& tx)
701 {
702  unsigned int nSigOps = 0;
703  BOOST_FOREACH(const CTxIn& txin, tx.vin)
704  {
705  nSigOps += txin.scriptSig.GetSigOpCount(false);
706  }
707  BOOST_FOREACH(const CTxOut& txout, tx.vout)
708  {
709  nSigOps += txout.scriptPubKey.GetSigOpCount(false);
710  }
711  return nSigOps;
712 }
713 
714 unsigned int GetP2SHSigOpCount(const CTransaction& tx, CCoinsViewCache& inputs)
715 {
716  if (tx.IsCoinBase())
717  return 0;
718 
719  unsigned int nSigOps = 0;
720  for (unsigned int i = 0; i < tx.vin.size(); i++)
721  {
722  const CTxOut &prevout = inputs.GetOutputFor(tx.vin[i]);
723  if (prevout.scriptPubKey.IsPayToScriptHash())
724  nSigOps += prevout.scriptPubKey.GetSigOpCount(tx.vin[i].scriptSig);
725  }
726  return nSigOps;
727 }
728 
729 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
730 {
731  AssertLockHeld(cs_main);
732  CBlock blockTmp;
733 
734  if (pblock == NULL) {
735  CCoins coins;
736  if (pcoinsTip->GetCoins(GetHash(), coins)) {
737  CBlockIndex *pindex = chainActive[coins.nHeight];
738  if (pindex) {
739  if (!ReadBlockFromDisk(blockTmp, pindex))
740  return 0;
741  pblock = &blockTmp;
742  }
743  }
744  }
745 
746  if (pblock) {
747  // Update the tx's hashBlock
748  hashBlock = pblock->GetHash();
749 
750  // Locate the transaction
751  for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++)
752  if (pblock->vtx[nIndex] == *(CTransaction*)this)
753  break;
754  if (nIndex == (int)pblock->vtx.size())
755  {
756  vMerkleBranch.clear();
757  nIndex = -1;
758  LogPrintf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
759  return 0;
760  }
761 
762  // Fill in merkle branch
763  vMerkleBranch = pblock->GetMerkleBranch(nIndex);
764  }
765 
766  // Is the tx in a block that's in the main chain
767  map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
768  if (mi == mapBlockIndex.end())
769  return 0;
770  CBlockIndex* pindex = (*mi).second;
771  if (!pindex || !chainActive.Contains(pindex))
772  return 0;
773 
774  return chainActive.Height() - pindex->nHeight + 1;
775 }
776 
777 
778 
779 
780 
781 
782 
784 {
785  // Basic checks that don't depend on any context
786  if (tx.vin.empty())
787  return state.DoS(10, error("CheckTransaction() : vin empty"),
788  REJECT_INVALID, "bad-txns-vin-empty");
789  if (tx.vout.empty())
790  return state.DoS(10, error("CheckTransaction() : vout empty"),
791  REJECT_INVALID, "bad-txns-vout-empty");
792  // Size limits
793  if (::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
794  return state.DoS(100, error("CheckTransaction() : size limits failed"),
795  REJECT_INVALID, "bad-txns-oversize");
796 
797  // Check for negative or overflow output values
798  int64_t nValueOut = 0;
799  BOOST_FOREACH(const CTxOut& txout, tx.vout)
800  {
801  if (txout.nValue < 0)
802  return state.DoS(100, error("CheckTransaction() : txout.nValue negative"),
803  REJECT_INVALID, "bad-txns-vout-negative");
804  if (txout.nValue > MAX_MONEY)
805  return state.DoS(100, error("CheckTransaction() : txout.nValue too high"),
806  REJECT_INVALID, "bad-txns-vout-toolarge");
807  nValueOut += txout.nValue;
808  if (!MoneyRange(nValueOut))
809  return state.DoS(100, error("CheckTransaction() : txout total out of range"),
810  REJECT_INVALID, "bad-txns-txouttotal-toolarge");
811  }
812 
813  // Check for duplicate inputs
814  set<COutPoint> vInOutPoints;
815  BOOST_FOREACH(const CTxIn& txin, tx.vin)
816  {
817  if (vInOutPoints.count(txin.prevout))
818  return state.DoS(100, error("CheckTransaction() : duplicate inputs"),
819  REJECT_INVALID, "bad-txns-inputs-duplicate");
820  vInOutPoints.insert(txin.prevout);
821  }
822 
823  /* ToDo: GRNotes: The following chunck of code was commented out in Anc 8.6, from what I can tell the genesis block
824  * has a string 95 bytes long, so this was failing with script size error, this important set of tests on the transaction
825  * never got 'uncommented' and fixed so the following CheckTransaction code could run properly. Would like to keep it here now,
826  * so setting the size limit higher, and get the client to start building the blockchain database properly....
827  * Bitcoin's value here was size() > 100....changed to 120
828  */
829  if (tx.IsCoinBase())
830  {
831  // ToDo: Change or accept the new max script size here, 120 is arbitrary...
832  if (tx.vin[0].scriptSig.size() < 2 || tx.vin[0].scriptSig.size() > 120)
833  return state.DoS(100, error("CheckTransaction() : coinbase script size"),
834  REJECT_INVALID, "bad-cb-length");
835  }
836  else
837  {
838  BOOST_FOREACH(const CTxIn& txin, tx.vin)
839  if (txin.prevout.IsNull())
840  return state.DoS(10, error("CheckTransaction() : prevout is null"),
841  REJECT_INVALID, "bad-txns-prevout-null");
842  }
843 
844  return true;
845 }
846 
847 int64_t GetMinFee(const CTransaction& tx, unsigned int nBytes, bool fAllowFree, enum GetMinFee_mode mode)
848 {
849  // Base fee is either nMinTxFee or nMinRelayTxFee
850  int64_t nBaseFee = (mode == GMF_RELAY) ? tx.nMinRelayTxFee : tx.nMinTxFee;
851 
852  int64_t nMinFee = (1 + (int64_t)nBytes / 1000) * nBaseFee;
853 
854  if (fAllowFree)
855  {
856  // There is a free transaction area in blocks created by most miners,
857  // * If we are relaying we allow transactions up to DEFAULT_BLOCK_PRIORITY_SIZE - 1000
858  // to be considered to fall into this category. We don't want to encourage sending
859  // multiple transactions instead of one big transaction to avoid fees.
860  // * If we are creating a transaction we allow transactions up to 1,000 bytes
861  // to be considered safe and assume they can likely make it into this section.
862  if (nBytes < (mode == GMF_SEND ? 5000 : (DEFAULT_BLOCK_PRIORITY_SIZE - 1000)))
863  nMinFee = 0;
864  }
865 
866  // Litecoin
867  // To limit dust spam, add nBaseFee for each output smaller than DUST_SOFT_LIMIT
868  BOOST_FOREACH(const CTxOut& txout, tx.vout)
869  if (txout.nValue < DUST_SOFT_LIMIT)
870  nMinFee += nBaseFee;
871 
872  if (!MoneyRange(nMinFee))
873  nMinFee = MAX_MONEY;
874  return nMinFee;
875 }
876 
877 
878 bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransaction &tx, bool fLimitFree,
879  bool* pfMissingInputs, bool fRejectInsaneFee)
880 {
881  AssertLockHeld(cs_main);
882  if (pfMissingInputs)
883  *pfMissingInputs = false;
884 
885  if (!CheckTransaction(tx, state))
886  return error("AcceptToMemoryPool: : CheckTransaction failed");
887 
888  // Coinbase is only valid in a block, not as a loose transaction
889  if (tx.IsCoinBase())
890  return state.DoS(100, error("AcceptToMemoryPool: : coinbase as individual tx"),
891  REJECT_INVALID, "coinbase");
892 
893  // Rather not work on nonstandard transactions (unless -testnet/-regtest)
894  string reason;
895  if (Params().NetworkID() == CChainParams::MAIN && !IsStandardTx(tx, reason))
896  return state.DoS(0,
897  error("AcceptToMemoryPool : nonstandard transaction: %s", reason),
898  REJECT_NONSTANDARD, reason);
899 
900  // is it already in the memory pool?
901  uint256 hash = tx.GetHash();
902  if (pool.exists(hash))
903  return false;
904 
905  // Check for conflicts with in-memory transactions
906  {
907  LOCK(pool.cs); // protect pool.mapNextTx
908  for (unsigned int i = 0; i < tx.vin.size(); i++)
909  {
910  COutPoint outpoint = tx.vin[i].prevout;
911  if (pool.mapNextTx.count(outpoint))
912  {
913  // Disable replacement feature for now
914  return false;
915  }
916  }
917  }
918 
919  {
920  CCoinsView dummy;
921  CCoinsViewCache view(dummy);
922 
923  {
924  LOCK(pool.cs);
925  CCoinsViewMemPool viewMemPool(*pcoinsTip, pool);
926  view.SetBackend(viewMemPool);
927 
928  // do we already have it?
929  if (view.HaveCoins(hash))
930  return false;
931 
932  // do all inputs exist?
933  // Note that this does not check for the presence of actual outputs (see the next check for that),
934  // only helps filling in pfMissingInputs (to determine missing vs spent).
935  BOOST_FOREACH(const CTxIn txin, tx.vin) {
936  if (!view.HaveCoins(txin.prevout.hash)) {
937  if (pfMissingInputs)
938  *pfMissingInputs = true;
939  return false;
940  }
941  }
942 
943  // are the actual inputs available?
944  if (!view.HaveInputs(tx))
945  return state.Invalid(error("AcceptToMemoryPool : inputs already spent"),
946  REJECT_DUPLICATE, "bad-txns-inputs-spent");
947 
948  // Bring the best block into scope
949  view.GetBestBlock();
950 
951  // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
952  view.SetBackend(dummy);
953  }
954 
955  // Check for non-standard pay-to-script-hash in inputs
956  if (Params().NetworkID() == CChainParams::MAIN && !AreInputsStandard(tx, view))
957  return error("AcceptToMemoryPool: : nonstandard transaction input");
958 
959  // Note: if you modify this code to accept non-standard transactions, then
960  // you should add code here to check that the transaction does a
961  // reasonable number of ECDSA signature verifications.
962 
963  int64_t nValueIn = view.GetValueIn(tx);
964  int64_t nValueOut = tx.GetValueOut();
965  int64_t nFees = nValueIn-nValueOut;
966  double dPriority = view.GetPriority(tx, chainActive.Height());
967 
968  CTxMemPoolEntry entry(tx, nFees, GetTime(), dPriority, chainActive.Height());
969  unsigned int nSize = entry.GetTxSize();
970 
971  // Don't accept it if it can't get into a block
972  int64_t txMinFee = GetMinFee(tx, nSize, true, GMF_RELAY);
973  if (fLimitFree && nFees < txMinFee)
974  return state.DoS(0, error("AcceptToMemoryPool : not enough fees %s, %d < %d",
975  hash.ToString(), nFees, txMinFee),
976  REJECT_INSUFFICIENTFEE, "insufficient fee");
977 
978  // Continuously rate-limit free transactions
979  // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
980  // be annoying or make others' transactions take longer to confirm.
981  if (fLimitFree && nFees < CTransaction::nMinRelayTxFee)
982  {
983  static CCriticalSection csFreeLimiter;
984  static double dFreeCount;
985  static int64_t nLastTime;
986  int64_t nNow = GetTime();
987 
988  LOCK(csFreeLimiter);
989 
990  // Use an exponentially decaying ~10-minute window:
991  dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
992  nLastTime = nNow;
993  // -limitfreerelay unit is thousand-bytes-per-minute
994  // At default rate it would take over a month to fill 1GB
995  if (dFreeCount >= GetArg("-limitfreerelay", 15)*10*1000)
996  return state.DoS(0, error("AcceptToMemoryPool : free transaction rejected by rate limiter"),
997  REJECT_INSUFFICIENTFEE, "insufficient priority");
998  LogPrint("mempool", "Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
999  dFreeCount += nSize;
1000  }
1001 
1002  if (fRejectInsaneFee && nFees > CTransaction::nMinRelayTxFee * 10000)
1003  return error("AcceptToMemoryPool: : insane fees %s, %d > %d",
1004  hash.ToString(),
1005  nFees, CTransaction::nMinRelayTxFee * 10000);
1006 
1007  // Check against previous transactions
1008  // This is done last to help prevent CPU exhaustion denial-of-service attacks.
1009  if (!CheckInputs(tx, state, view, true, SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC))
1010  {
1011  return error("AcceptToMemoryPool: : ConnectInputs failed %s", hash.ToString());
1012  }
1013  // Store transaction in memory
1014  pool.addUnchecked(hash, entry);
1015  }
1016 
1017  g_signals.SyncTransaction(hash, tx, NULL);
1018 
1019  return true;
1020 }
1021 
1022 
1024 {
1025  if (hashBlock == 0 || nIndex == -1)
1026  return 0;
1027  AssertLockHeld(cs_main);
1028 
1029  // Find the block it claims to be in
1030  map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1031  if (mi == mapBlockIndex.end())
1032  return 0;
1033  CBlockIndex* pindex = (*mi).second;
1034  if (!pindex || !chainActive.Contains(pindex))
1035  return 0;
1036 
1037  // Make sure the merkle branch connects to this block
1038  if (!fMerkleVerified)
1039  {
1040  if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
1041  return 0;
1042  fMerkleVerified = true;
1043  }
1044 
1045  pindexRet = pindex;
1046  return chainActive.Height() - pindex->nHeight + 1;
1047 }
1048 
1050 {
1051  AssertLockHeld(cs_main);
1052  int nResult = GetDepthInMainChainINTERNAL(pindexRet);
1053  if (nResult == 0 && !mempool.exists(GetHash()))
1054  return -1; // Not in chain, not in mempool
1055 
1056  return nResult;
1057 }
1058 
1060 {
1061  if (!IsCoinBase())
1062  return 0;
1063  return max(0, (COINBASE_MATURITY+1) - GetDepthInMainChain());
1064 }
1065 
1066 
1067 bool CMerkleTx::AcceptToMemoryPool(bool fLimitFree)
1068 {
1069  CValidationState state;
1070  return ::AcceptToMemoryPool(mempool, state, *this, fLimitFree, NULL);
1071 }
1072 
1073 
1074 // Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock
1075 bool GetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock, bool fAllowSlow)
1076 {
1077  CBlockIndex *pindexSlow = NULL;
1078  {
1079  LOCK(cs_main);
1080  {
1081  if (mempool.lookup(hash, txOut))
1082  {
1083  return true;
1084  }
1085  }
1086 
1087  if (fTxIndex) {
1088  CDiskTxPos postx;
1089  if (pblocktree->ReadTxIndex(hash, postx)) {
1090  CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);
1091  CBlockHeader header;
1092  try {
1093  file >> header;
1094  fseek(file, postx.nTxOffset, SEEK_CUR);
1095  file >> txOut;
1096  } catch (std::exception &e) {
1097  return error("%s : Deserialize or I/O error - %s", __func__, e.what());
1098  }
1099  hashBlock = header.GetHash();
1100  if (txOut.GetHash() != hash)
1101  return error("%s : txid mismatch", __func__);
1102  return true;
1103  }
1104  }
1105 
1106  if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
1107  int nHeight = -1;
1108  {
1109  CCoinsViewCache &view = *pcoinsTip;
1110  CCoins coins;
1111  if (view.GetCoins(hash, coins))
1112  nHeight = coins.nHeight;
1113  }
1114  if (nHeight > 0)
1115  pindexSlow = chainActive[nHeight];
1116  }
1117  }
1118 
1119  if (pindexSlow) {
1120  CBlock block;
1121  if (ReadBlockFromDisk(block, pindexSlow)) {
1122  BOOST_FOREACH(const CTransaction &tx, block.vtx) {
1123  if (tx.GetHash() == hash) {
1124  txOut = tx;
1125  hashBlock = pindexSlow->GetBlockHash();
1126  return true;
1127  }
1128  }
1129  }
1130  }
1131 
1132  return false;
1133 }
1134 
1135 
1136 
1137 
1138 
1139 
1141 //
1142 // CBlock and CBlockIndex
1143 //
1144 
1146 {
1147  // Open history file to append
1148  CAutoFile fileout = CAutoFile(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
1149  if (!fileout)
1150  return error("WriteBlockToDisk : OpenBlockFile failed");
1151 
1152  // Write index header
1153  unsigned int nSize = fileout.GetSerializeSize(block);
1154  fileout << FLATDATA(Params().MessageStart()) << nSize;
1155 
1156  // Write block
1157  long fileOutPos = ftell(fileout);
1158  if (fileOutPos < 0)
1159  return error("WriteBlockToDisk : ftell failed");
1160  pos.nPos = (unsigned int)fileOutPos;
1161  fileout << block;
1162 
1163  // Flush stdio buffers and commit to disk before returning
1164  fflush(fileout);
1165  if (!IsInitialBlockDownload())
1166  FileCommit(fileout);
1167 
1168  return true;
1169 }
1170 
1171 bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos)
1172 {
1173  block.SetNull();
1174 
1175  // Open history file to read
1176  CAutoFile filein = CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
1177  if (!filein)
1178  return error("ReadBlockFromDisk : OpenBlockFile failed");
1179 
1180  // Read block
1181  try {
1182  filein >> block;
1183  }
1184  catch (std::exception &e) {
1185  return error("%s : Deserialize or I/O error - %s", __func__, e.what());
1186  }
1187 
1188  // Check the header
1189  if (!CheckProofOfWork(block.GetPoWHash(), block.nBits))
1190  return error("ReadBlockFromDisk : Errors in block header");
1191 
1192  return true;
1193 }
1194 
1195 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex)
1196 {
1197  if (!ReadBlockFromDisk(block, pindex->GetBlockPos()))
1198  return false;
1199  if (block.GetHash() != pindex->GetBlockHash())
1200  return error("ReadBlockFromDisk(CBlock&, CBlockIndex*) : GetHash() doesn't match index");
1201  return true;
1202 }
1203 
1204 uint256 static GetOrphanRoot(const uint256& hash)
1205 {
1206  map<uint256, COrphanBlock*>::iterator it = mapOrphanBlocks.find(hash);
1207  if (it == mapOrphanBlocks.end())
1208  return hash;
1209 
1210  // Work back to the first block in the orphan chain
1211  do {
1212  map<uint256, COrphanBlock*>::iterator it2 = mapOrphanBlocks.find(it->second->hashPrev);
1213  if (it2 == mapOrphanBlocks.end())
1214  return it->first;
1215  it = it2;
1216  } while(true);
1217 }
1218 
1219 // Remove a random orphan block (which does not have any dependent orphans).
1220 void static PruneOrphanBlocks()
1221 {
1222  if (mapOrphanBlocksByPrev.size() <= (size_t)std::max((int64_t)0, GetArg("-maxorphanblocks", DEFAULT_MAX_ORPHAN_BLOCKS)))
1223  return;
1224 
1225  // Pick a random orphan block.
1226  int pos = insecure_rand() % mapOrphanBlocksByPrev.size();
1227  std::multimap<uint256, COrphanBlock*>::iterator it = mapOrphanBlocksByPrev.begin();
1228  while (pos--) it++;
1229 
1230  // As long as this block has other orphans depending on it, move to one of those successors.
1231  do {
1232  std::multimap<uint256, COrphanBlock*>::iterator it2 = mapOrphanBlocksByPrev.find(it->second->hashBlock);
1233  if (it2 == mapOrphanBlocksByPrev.end())
1234  break;
1235  it = it2;
1236  } while(1);
1237 
1238  uint256 hash = it->second->hashBlock;
1239  delete it->second;
1240  mapOrphanBlocksByPrev.erase(it);
1241  mapOrphanBlocks.erase(hash);
1242 }
1243 
1244 #include "main2.cpp"
1245 
1247 {
1248  LOCK(cs_main);
1249  if (fImporting || fReindex || chainActive.Height() < Checkpoints::GetTotalBlocksEstimate())
1250  return true;
1251  static int64_t nLastUpdate;
1252  static CBlockIndex* pindexLastBest;
1253  if (chainActive.Tip() != pindexLastBest)
1254  {
1255  pindexLastBest = chainActive.Tip();
1256  nLastUpdate = GetTime();
1257  }
1258  return (GetTime() - nLastUpdate < 10 &&
1259  chainActive.Tip()->GetBlockTime() < GetTime() - 24 * 60 * 60);
1260 }
1261 
1262 bool fLargeWorkForkFound = false;
1265 
1267 {
1268  AssertLockHeld(cs_main);
1269  // Before we get past initial download, we cannot reliably alert about forks
1270  // (we assume we don't get stuck on a fork before the last checkpoint)
1271  if (IsInitialBlockDownload())
1272  return;
1273 
1274  // If our best fork is no longer within 72 blocks (+/- 12 hours if no one mines it)
1275  // of our head, drop it
1276  if (pindexBestForkTip && chainActive.Height() - pindexBestForkTip->nHeight >= 72)
1277  pindexBestForkTip = NULL;
1278 
1279  if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > chainActive.Tip()->nChainWork + (chainActive.Tip()->GetBlockWork() * 6).getuint256()))
1280  {
1281  if (!fLargeWorkForkFound)
1282  {
1283  std::string strCmd = GetArg("-alertnotify", "");
1284  if (!strCmd.empty())
1285  {
1286  std::string warning = std::string("'Warning: Large-work fork detected, forking after block ") +
1287  pindexBestForkBase->phashBlock->ToString() + std::string("'");
1288  boost::replace_all(strCmd, "%s", warning);
1289  boost::thread t(runCommand, strCmd); // thread runs free
1290  }
1291  }
1292  if (pindexBestForkTip)
1293  {
1294  LogPrintf("CheckForkWarningConditions: Warning: Large valid fork found\n forking the chain at height %d (%s)\n lasting to height %d (%s).\nChain state database corruption likely.\n",
1295  pindexBestForkBase->nHeight, pindexBestForkBase->phashBlock->ToString(),
1296  pindexBestForkTip->nHeight, pindexBestForkTip->phashBlock->ToString());
1297  fLargeWorkForkFound = true;
1298  }
1299  else
1300  {
1301  LogPrintf("CheckForkWarningConditions: Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.\n");
1302  fLargeWorkInvalidChainFound = true;
1303  }
1304  }
1305  else
1306  {
1307  fLargeWorkForkFound = false;
1308  fLargeWorkInvalidChainFound = false;
1309  }
1310 }
1311 
1313 {
1314  AssertLockHeld(cs_main);
1315  // If we are on a fork that is sufficiently large, set a warning flag
1316  CBlockIndex* pfork = pindexNewForkTip;
1317  CBlockIndex* plonger = chainActive.Tip();
1318  while (pfork && pfork != plonger)
1319  {
1320  while (plonger && plonger->nHeight > pfork->nHeight)
1321  plonger = plonger->pprev;
1322  if (pfork == plonger)
1323  break;
1324  pfork = pfork->pprev;
1325  }
1326 
1327  // We define a condition which we should warn the user about as a fork of at least 7 blocks
1328  // who's tip is within 72 blocks (+/- 12 hours if no one mines it) of ours
1329  // We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network
1330  // hash rate operating on the fork.
1331  // or a chain that is entirely longer than ours and invalid (note that this should be detected by both)
1332  // We define it this way because it allows us to only store the highest fork tip (+ base) which meets
1333  // the 7-block condition and from this always have the most-likely-to-cause-warning fork
1334  if (pfork && (!pindexBestForkTip || (pindexBestForkTip && pindexNewForkTip->nHeight > pindexBestForkTip->nHeight)) &&
1335  pindexNewForkTip->nChainWork - pfork->nChainWork > (pfork->GetBlockWork() * 7).getuint256() &&
1336  chainActive.Height() - pindexNewForkTip->nHeight < 72)
1337  {
1338  pindexBestForkTip = pindexNewForkTip;
1339  pindexBestForkBase = pfork;
1340  }
1341 
1343 }
1344 
1345 // Requires cs_main.
1346 void Misbehaving(NodeId pnode, int howmuch)
1347 {
1348  if (howmuch == 0)
1349  return;
1350 
1351  CNodeState *state = State(pnode);
1352  if (state == NULL)
1353  return;
1354 
1355  state->nMisbehavior += howmuch;
1356  if (state->nMisbehavior >= GetArg("-banscore", 100))
1357  {
1358  LogPrintf("Misbehaving: %s (%d -> %d) BAN THRESHOLD EXCEEDED\n", state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
1359  state->fShouldBan = true;
1360  } else
1361  LogPrintf("Misbehaving: %s (%d -> %d)\n", state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
1362 }
1363 
1364 void static InvalidChainFound(CBlockIndex* pindexNew)
1365 {
1366  if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
1367  {
1368  pindexBestInvalid = pindexNew;
1369  // The current code doesn't actually read the BestInvalidWork entry in
1370  // the block database anymore, as it is derived from the flags in block
1371  // index entry. We only write it for backward compatibility.
1372  pblocktree->WriteBestInvalidWork(CBigNum(pindexBestInvalid->nChainWork));
1374  }
1375  LogPrintf("InvalidChainFound: invalid block=%s height=%d log2_work=%.8g date=%s\n",
1376  pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
1377  log(pindexNew->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
1378  pindexNew->GetBlockTime()));
1379  LogPrintf("InvalidChainFound: current best=%s height=%d log2_work=%.8g date=%s\n",
1380  chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), log(chainActive.Tip()->nChainWork.getdouble())/log(2.0),
1381  DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()));
1383 }
1384 
1385 void static InvalidBlockFound(CBlockIndex *pindex, const CValidationState &state) {
1386  int nDoS = 0;
1387  if (state.IsInvalid(nDoS)) {
1388  std::map<uint256, NodeId>::iterator it = mapBlockSource.find(pindex->GetBlockHash());
1389  if (it != mapBlockSource.end() && State(it->second)) {
1390  CBlockReject reject = {state.GetRejectCode(), state.GetRejectReason(), pindex->GetBlockHash()};
1391  State(it->second)->rejects.push_back(reject);
1392  if (nDoS > 0)
1393  Misbehaving(it->second, nDoS);
1394  }
1395  }
1396  if (!state.CorruptionPossible()) {
1397  pindex->nStatus |= BLOCK_FAILED_VALID;
1398  pblocktree->WriteBlockIndex(CDiskBlockIndex(pindex));
1399  setBlockIndexValid.erase(pindex);
1400  InvalidChainFound(pindex);
1401  }
1402 }
1403 
1404 void UpdateTime(CBlockHeader& block, const CBlockIndex* pindexPrev)
1405 {
1406  block.nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
1407 
1408  // Updating time can change work required on testnet:
1409  if (TestNet())
1410  block.nBits = GetNextWorkRequired(pindexPrev, &block);
1411 }
1412 
1413 
1414 
1415 
1416 
1417 
1418 
1419 
1420 
1421 
1422 
1423 void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight, const uint256 &txhash)
1424 {
1425  bool ret;
1426  // mark inputs spent
1427  if (!tx.IsCoinBase()) {
1428  BOOST_FOREACH(const CTxIn &txin, tx.vin) {
1429  CCoins &coins = inputs.GetCoins(txin.prevout.hash);
1430  CTxInUndo undo;
1431  ret = coins.Spend(txin.prevout, undo);
1432  assert(ret);
1433  txundo.vprevout.push_back(undo);
1434  }
1435  }
1436 
1437  // add outputs
1438  ret = inputs.SetCoins(txhash, CCoins(tx, nHeight));
1439  assert(ret);
1440 }
1441 
1443  const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1444  if (!VerifyScript(scriptSig, scriptPubKey, *ptxTo, nIn, nFlags, nHashType))
1445  return error("CScriptCheck() : %s VerifySignature failed", ptxTo->GetHash().ToString());
1446  return true;
1447 }
1448 
1449 bool VerifySignature(const CCoins& txFrom, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType)
1450 {
1451  return CScriptCheck(txFrom, txTo, nIn, flags, nHashType)();
1452 }
1453 
1454 bool CheckInputs(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, std::vector<CScriptCheck> *pvChecks)
1455 {
1456  if (!tx.IsCoinBase())
1457  {
1458  if (pvChecks)
1459  pvChecks->reserve(tx.vin.size());
1460 
1461  // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1462  // for an attacker to attempt to split the network.
1463  if (!inputs.HaveInputs(tx))
1464  return state.Invalid(error("CheckInputs() : %s inputs unavailable", tx.GetHash().ToString()));
1465 
1466  // While checking, GetBestBlock() refers to the parent block.
1467  // This is also true for mempool checks.
1468  CBlockIndex *pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second;
1469  int nSpendHeight = pindexPrev->nHeight + 1;
1470  int64_t nValueIn = 0;
1471  int64_t nFees = 0;
1472  for (unsigned int i = 0; i < tx.vin.size(); i++)
1473  {
1474  const COutPoint &prevout = tx.vin[i].prevout;
1475  const CCoins &coins = inputs.GetCoins(prevout.hash);
1476 
1477  // If prev is coinbase, check that it's matured
1478  if (coins.IsCoinBase()) {
1479  if (nSpendHeight - coins.nHeight < COINBASE_MATURITY)
1480  return state.Invalid(
1481  error("CheckInputs() : tried to spend coinbase at depth %d", nSpendHeight - coins.nHeight),
1482  REJECT_INVALID, "bad-txns-premature-spend-of-coinbase");
1483  }
1484 
1485  // Check for negative or overflow input values
1486  nValueIn += coins.vout[prevout.n].nValue;
1487  if (!MoneyRange(coins.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1488  return state.DoS(100, error("CheckInputs() : txin values out of range"),
1489  REJECT_INVALID, "bad-txns-inputvalues-outofrange");
1490 
1491  }
1492 
1493  if (nValueIn < tx.GetValueOut())
1494  return state.DoS(100, error("CheckInputs() : %s value in < value out", tx.GetHash().ToString()),
1495  REJECT_INVALID, "bad-txns-in-belowout");
1496 
1497  // Tally transaction fees
1498  int64_t nTxFee = nValueIn - tx.GetValueOut();
1499  if (nTxFee < 0)
1500  return state.DoS(100, error("CheckInputs() : %s nTxFee < 0", tx.GetHash().ToString()),
1501  REJECT_INVALID, "bad-txns-fee-negative");
1502  nFees += nTxFee;
1503  if (!MoneyRange(nFees))
1504  return state.DoS(100, error("CheckInputs() : nFees out of range"),
1505  REJECT_INVALID, "bad-txns-fee-outofrange");
1506 
1507  // The first loop above does all the inexpensive checks.
1508  // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1509  // Helps prevent CPU exhaustion attacks.
1510 
1511  // Skip ECDSA signature verification when connecting blocks
1512  // before the last block chain checkpoint. This is safe because block merkle hashes are
1513  // still computed and checked, and any change will be caught at the next checkpoint.
1514  if (fScriptChecks) {
1515  for (unsigned int i = 0; i < tx.vin.size(); i++) {
1516  const COutPoint &prevout = tx.vin[i].prevout;
1517  const CCoins &coins = inputs.GetCoins(prevout.hash);
1518 
1519  // Verify signature
1520  CScriptCheck check(coins, tx, i, flags, 0);
1521  if (pvChecks) {
1522  pvChecks->push_back(CScriptCheck());
1523  check.swap(pvChecks->back());
1524  } else if (!check()) {
1525  if (flags & SCRIPT_VERIFY_STRICTENC) {
1526  // For now, check whether the failure was caused by non-canonical
1527  // encodings or not; if so, don't trigger DoS protection.
1528  CScriptCheck check(coins, tx, i, flags & (~SCRIPT_VERIFY_STRICTENC), 0);
1529  if (check())
1530  return state.Invalid(false, REJECT_NONSTANDARD, "non-canonical");
1531  }
1532  return state.DoS(100,false, REJECT_NONSTANDARD, "non-canonical");
1533  }
1534  }
1535  }
1536  }
1537 
1538  return true;
1539 }
1540 
1541 
1542 
1543 bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool* pfClean)
1544 {
1545  assert(pindex->GetBlockHash() == view.GetBestBlock());
1546 
1547  if (pfClean)
1548  *pfClean = false;
1549 
1550  bool fClean = true;
1551 
1552  CBlockUndo blockUndo;
1553  CDiskBlockPos pos = pindex->GetUndoPos();
1554  if (pos.IsNull())
1555  return error("DisconnectBlock() : no undo data available");
1556  if (!blockUndo.ReadFromDisk(pos, pindex->pprev->GetBlockHash()))
1557  return error("DisconnectBlock() : failure reading undo data");
1558 
1559  if (blockUndo.vtxundo.size() + 1 != block.vtx.size())
1560  return error("DisconnectBlock() : block and undo data inconsistent");
1561 
1562  // undo transactions in reverse order
1563  for (int i = block.vtx.size() - 1; i >= 0; i--) {
1564  const CTransaction &tx = block.vtx[i];
1565  uint256 hash = tx.GetHash();
1566 
1567  // check that all outputs are available
1568  if (!view.HaveCoins(hash)) {
1569  fClean = fClean && error("DisconnectBlock() : outputs still spent? database corrupted");
1570  view.SetCoins(hash, CCoins());
1571  }
1572  CCoins &outs = view.GetCoins(hash);
1573  // Check that all outputs are available and match the outputs in the block itself
1574  // exactly. Note that transactions with only provably unspendable outputs won't
1575  // have outputs available even in the block itself, so we handle that case
1576  // specially with outsEmpty.
1577  //CCoins outsEmpty;
1578  //CCoins &outs = view.HaveCoins(hash) ? view.GetCoins(hash) : outsEmpty;
1579  //outs.ClearUnspendable();
1580 
1581  CCoins outsBlock = CCoins(tx, pindex->nHeight);
1582  // The CCoins serialization does not serialize negative numbers.
1583  // No network rules currently depend on the version here, so an inconsistency is harmless
1584  // but it must be corrected before txout nversion ever influences a network rule.
1585  if (outsBlock.nVersion < 0)
1586  outs.nVersion = outsBlock.nVersion;
1587  if (outs != outsBlock)
1588  fClean = fClean && error("DisconnectBlock() : added transaction mismatch? database corrupted");
1589 
1590  // remove outputs
1591  outs = CCoins();
1592 
1593  // restore inputs
1594  if (i > 0) { // not coinbases
1595  const CTxUndo &txundo = blockUndo.vtxundo[i-1];
1596  if (txundo.vprevout.size() != tx.vin.size())
1597  return error("DisconnectBlock() : transaction and undo data inconsistent");
1598  for (unsigned int j = tx.vin.size(); j-- > 0;) {
1599  const COutPoint &out = tx.vin[j].prevout;
1600  const CTxInUndo &undo = txundo.vprevout[j];
1601  CCoins coins;
1602  view.GetCoins(out.hash, coins); // this can fail if the prevout was already entirely spent
1603  if (undo.nHeight != 0) {
1604  // undo data contains height: this is the last output of the prevout tx being spent
1605  if (!coins.IsPruned())
1606  fClean = fClean && error("DisconnectBlock() : undo data overwriting existing transaction");
1607  coins = CCoins();
1608  coins.fCoinBase = undo.fCoinBase;
1609  coins.nHeight = undo.nHeight;
1610  coins.nVersion = undo.nVersion;
1611  } else {
1612  if (coins.IsPruned())
1613  fClean = fClean && error("DisconnectBlock() : undo data adding output to missing transaction");
1614  }
1615  if (coins.IsAvailable(out.n))
1616  fClean = fClean && error("DisconnectBlock() : undo data overwriting existing output");
1617  if (coins.vout.size() < out.n+1)
1618  coins.vout.resize(out.n+1);
1619  coins.vout[out.n] = undo.txout;
1620  if (!view.SetCoins(out.hash, coins))
1621  return error("DisconnectBlock() : cannot restore coin inputs");
1622  }
1623  }
1624  }
1625 
1626  // move best block pointer to prevout block
1627  view.SetBestBlock(pindex->pprev->GetBlockHash());
1628 
1629  if (pfClean) {
1630  *pfClean = fClean;
1631  return true;
1632  } else {
1633  return fClean;
1634  }
1635 }
1636 
1637 void static FlushBlockFile(bool fFinalize = false)
1638 {
1639  LOCK(cs_LastBlockFile);
1640 
1641  CDiskBlockPos posOld(nLastBlockFile, 0);
1642 
1643  FILE *fileOld = OpenBlockFile(posOld);
1644  if (fileOld) {
1645  if (fFinalize)
1646  TruncateFile(fileOld, infoLastBlockFile.nSize);
1647  FileCommit(fileOld);
1648  fclose(fileOld);
1649  }
1650 
1651  fileOld = OpenUndoFile(posOld);
1652  if (fileOld) {
1653  if (fFinalize)
1654  TruncateFile(fileOld, infoLastBlockFile.nUndoSize);
1655  FileCommit(fileOld);
1656  fclose(fileOld);
1657  }
1658 }
1659 
1660 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
1661 
1662 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
1663 
1665  RenameThread("anoncoin-scriptch");
1666  scriptcheckqueue.Thread();
1667 }
1668 
1669 bool ConnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool fJustCheck)
1670 {
1671  AssertLockHeld(cs_main);
1672  // Check it again in case a previous version let a bad block in
1673  if (!CheckBlock(block, state, !fJustCheck, !fJustCheck))
1674  return false;
1675 
1676  // verify that the view's current state corresponds to the previous block
1677  uint256 hashPrevBlock = pindex->pprev == NULL ? uint256(0) : pindex->pprev->GetBlockHash();
1678  assert(hashPrevBlock == view.GetBestBlock());
1679 
1680  // Special case for the genesis block, skipping connection of its transactions
1681  // (its coinbase is unspendable)
1682  if (block.GetHash() == Params().HashGenesisBlock()) {
1683  view.SetBestBlock(pindex->GetBlockHash());
1684  return true;
1685  }
1686 
1687  bool fScriptChecks = pindex->nHeight >= Checkpoints::GetTotalBlocksEstimate();
1688 
1689  // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1690  // unless those are already completely spent.
1691  // If such overwrites are allowed, coinbases and transactions depending upon those
1692  // can be duplicated to remove the ability to spend the first instance -- even after
1693  // being sent to another address.
1694  // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1695  // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1696  // already refuses previously-known transaction ids entirely.
1697  // This rule was originally applied all blocks whose timestamp was after October 1, 2012, 0:00 UTC.
1698  // Now that the whole chain is irreversibly beyond that time it is applied to all blocks,
1699  // this prevents exploiting the issue against nodes in their initial block download.
1700  bool fEnforceBIP30 = true;
1701  if (fEnforceBIP30) {
1702  for (unsigned int i = 0; i < block.vtx.size(); i++) {
1703  uint256 hash = block.GetTxHash(i);
1704  if (view.HaveCoins(hash) && !view.GetCoins(hash).IsPruned())
1705  return state.DoS(100, error("ConnectBlock() : tried to overwrite transaction"),
1706  REJECT_INVALID, "bad-txns-BIP30");
1707  }
1708  }
1709 
1710  // BIP16 didn't become active until Oct 1 2012
1711  int64_t nBIP16SwitchTime = 1349049600;
1712  bool fStrictPayToScriptHash = (pindex->nTime >= nBIP16SwitchTime);
1713 
1714  unsigned int flags = SCRIPT_VERIFY_NOCACHE |
1715  (fStrictPayToScriptHash ? SCRIPT_VERIFY_P2SH : SCRIPT_VERIFY_NONE);
1716 
1717  CBlockUndo blockundo;
1718 
1719  CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
1720 
1721  int64_t nStart = GetTimeMicros();
1722  int64_t nFees = 0;
1723  int nInputs = 0;
1724  unsigned int nSigOps = 0;
1725  CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size()));
1726  std::vector<std::pair<uint256, CDiskTxPos> > vPos;
1727  vPos.reserve(block.vtx.size());
1728  for (unsigned int i = 0; i < block.vtx.size(); i++)
1729  {
1730  const CTransaction &tx = block.vtx[i];
1731 
1732  nInputs += tx.vin.size();
1733  nSigOps += GetLegacySigOpCount(tx);
1734  if (nSigOps > MAX_BLOCK_SIGOPS)
1735  return state.DoS(100, error("ConnectBlock() : too many sigops"),
1736  REJECT_INVALID, "bad-blk-sigops");
1737 
1738  if (!tx.IsCoinBase())
1739  {
1740  if (!view.HaveInputs(tx))
1741  return state.DoS(100, error("ConnectBlock() : inputs missing/spent"),
1742  REJECT_INVALID, "bad-txns-inputs-missingorspent");
1743 
1744  if (fStrictPayToScriptHash)
1745  {
1746  // Add in sigops done by pay-to-script-hash inputs;
1747  // this is to prevent a "rogue miner" from creating
1748  // an incredibly-expensive-to-validate block.
1749  nSigOps += GetP2SHSigOpCount(tx, view);
1750  if (nSigOps > MAX_BLOCK_SIGOPS)
1751  return state.DoS(100, error("ConnectBlock() : too many sigops"),
1752  REJECT_INVALID, "bad-blk-sigops");
1753  }
1754 
1755  nFees += view.GetValueIn(tx)-tx.GetValueOut();
1756 
1757  std::vector<CScriptCheck> vChecks;
1758  if (!CheckInputs(tx, state, view, fScriptChecks, flags, nScriptCheckThreads ? &vChecks : NULL))
1759  return false;
1760  control.Add(vChecks);
1761  }
1762 
1763  CTxUndo txundo;
1764  UpdateCoins(tx, state, view, txundo, pindex->nHeight, block.GetTxHash(i));
1765  if (!tx.IsCoinBase())
1766  blockundo.vtxundo.push_back(txundo);
1767 
1768  vPos.push_back(std::make_pair(block.GetTxHash(i), pos));
1769  pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
1770  }
1771  int64_t nTime = GetTimeMicros() - nStart;
1772  if (fBenchmark)
1773  LogPrintf("- Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin)\n", (unsigned)block.vtx.size(), 0.001 * nTime, 0.001 * nTime / block.vtx.size(), nInputs <= 1 ? 0 : 0.001 * nTime / (nInputs-1));
1774 
1775  if (block.vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))
1776  return state.DoS(100,
1777  error("ConnectBlock() : coinbase pays too much (actual=%d vs limit=%d)",
1778  block.vtx[0].GetValueOut(), GetBlockValue(pindex->nHeight, nFees)),
1779  REJECT_INVALID, "bad-cb-amount");
1780 
1781  if (!control.Wait())
1782  return state.DoS(100, false);
1783  int64_t nTime2 = GetTimeMicros() - nStart;
1784  if (fBenchmark)
1785  LogPrintf("- Verify %u txins: %.2fms (%.3fms/txin)\n", nInputs - 1, 0.001 * nTime2, nInputs <= 1 ? 0 : 0.001 * nTime2 / (nInputs-1));
1786 
1787  if (fJustCheck)
1788  return true;
1789 
1790  // Write undo information to disk
1791  if (pindex->GetUndoPos().IsNull() || (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS)
1792  {
1793  if (pindex->GetUndoPos().IsNull()) {
1794  CDiskBlockPos pos;
1795  if (!FindUndoPos(state, pindex->nFile, pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40))
1796  return error("ConnectBlock() : FindUndoPos failed");
1797  if (!blockundo.WriteToDisk(pos, pindex->pprev->GetBlockHash()))
1798  return state.Abort(_("Failed to write undo data"));
1799 
1800  // update nUndoPos in block index
1801  pindex->nUndoPos = pos.nPos;
1802  pindex->nStatus |= BLOCK_HAVE_UNDO;
1803  }
1804 
1805  pindex->nStatus = (pindex->nStatus & ~BLOCK_VALID_MASK) | BLOCK_VALID_SCRIPTS;
1806 
1807  CDiskBlockIndex blockindex(pindex);
1808  if (!pblocktree->WriteBlockIndex(blockindex))
1809  return state.Abort(_("Failed to write block index"));
1810  }
1811 
1812  if (fTxIndex)
1813  if (!pblocktree->WriteTxIndex(vPos))
1814  return state.Abort(_("Failed to write transaction index"));
1815 
1816  // add this block to the view's block chain
1817  bool ret;
1818  ret = view.SetBestBlock(pindex->GetBlockHash());
1819  assert(ret);
1820 
1821  // Watch for transactions paying to me
1822  for (unsigned int i = 0; i < block.vtx.size(); i++)
1823  g_signals.SyncTransaction(block.GetTxHash(i), block.vtx[i], &block);
1824 
1825  return true;
1826 }
1827 
1828 // Update the on-disk chain state.
1829 bool static WriteChainState(CValidationState &state) {
1830  static int64_t nLastWrite = 0;
1831  if (!IsInitialBlockDownload() || pcoinsTip->GetCacheSize() > nCoinCacheSize || GetTimeMicros() > nLastWrite + 600*1000000) {
1832  // Typical CCoins structures on disk are around 100 bytes in size.
1833  // Pushing a new one to the database can cause it to be written
1834  // twice (once in the log, and once in the tables). This is already
1835  // an overestimation, as most will delete an existing entry or
1836  // overwrite one. Still, use a conservative safety factor of 2.
1837  if (!CheckDiskSpace(100 * 2 * 2 * pcoinsTip->GetCacheSize()))
1838  return state.Error("out of disk space");
1839  FlushBlockFile();
1840  pblocktree->Sync();
1841  if (!pcoinsTip->Flush())
1842  return state.Abort(_("Failed to write to coin database"));
1843  nLastWrite = GetTimeMicros();
1844  }
1845  return true;
1846 }
1847 
1848 // Update chainActive and related internal data structures.
1849 void static UpdateTip(CBlockIndex *pindexNew) {
1850  chainActive.SetTip(pindexNew);
1851 
1852  // Update best block in wallet (so we can detect restored wallets)
1853  bool fIsInitialDownload = IsInitialBlockDownload();
1854  if ((chainActive.Height() % 20160) == 0 || (!fIsInitialDownload && (chainActive.Height() % 144) == 0))
1855  g_signals.SetBestChain(chainActive.GetLocator());
1856 
1857  // New best block
1859  mempool.AddTransactionsUpdated(1);
1860  LogPrintf("UpdateTip: new best=%s height=%d log2_work=%.8g tx=%lu date=%s progress=%f\n",
1861  chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), log(chainActive.Tip()->nChainWork.getdouble())/log(2.0), (unsigned long)chainActive.Tip()->nChainTx,
1862  DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
1864 
1865  // Check the version of the last 100 blocks to see if we need to upgrade:
1866  if (!fIsInitialDownload)
1867  {
1868  int nUpgraded = 0;
1869  const CBlockIndex* pindex = chainActive.Tip();
1870  for (int i = 0; i < 100 && pindex != NULL; i++)
1871  {
1872  if (pindex->nVersion > CBlock::CURRENT_VERSION)
1873  ++nUpgraded;
1874  pindex = pindex->pprev;
1875  }
1876  if (nUpgraded > 0)
1877  LogPrintf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, (int)CBlock::CURRENT_VERSION);
1878  if (nUpgraded > 100/2)
1879  // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
1880  strMiscWarning = _("Warning: This version is obsolete, upgrade required!");
1881  }
1882 }
1883 
1884 // Disconnect chainActive's tip.
1885 bool static DisconnectTip(CValidationState &state) {
1886  CBlockIndex *pindexDelete = chainActive.Tip();
1887  assert(pindexDelete);
1888  mempool.check(pcoinsTip);
1889  // Read block from disk.
1890  CBlock block;
1891  if (!ReadBlockFromDisk(block, pindexDelete))
1892  return state.Abort(_("Failed to read block"));
1893  // Apply the block atomically to the chain state.
1894  int64_t nStart = GetTimeMicros();
1895  {
1896  CCoinsViewCache view(*pcoinsTip, true);
1897  if (!DisconnectBlock(block, state, pindexDelete, view))
1898  return error("DisconnectTip() : DisconnectBlock %s failed", pindexDelete->GetBlockHash().ToString());
1899  assert(view.Flush());
1900  }
1901  if (fBenchmark)
1902  LogPrintf("- Disconnect: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
1903  // Write the chain state to disk, if necessary.
1904  if (!WriteChainState(state))
1905  return false;
1906  // Resurrect mempool transactions from the disconnected block.
1907  BOOST_FOREACH(const CTransaction &tx, block.vtx) {
1908  // ignore validation errors in resurrected transactions
1909  list<CTransaction> removed;
1910  CValidationState stateDummy;
1911  if (!tx.IsCoinBase())
1912  if (!AcceptToMemoryPool(mempool, stateDummy, tx, false, NULL))
1913  mempool.remove(tx, removed, true);
1914  }
1915  mempool.check(pcoinsTip);
1916  // Update chainActive and related variables.
1917  UpdateTip(pindexDelete->pprev);
1918  // Let wallets know transactions went from 1-confirmed to
1919  // 0-confirmed or conflicted:
1920  BOOST_FOREACH(const CTransaction &tx, block.vtx) {
1921  SyncWithWallets(tx.GetHash(), tx, NULL);
1922  }
1923  return true;
1924 }
1925 
1926 // Connect a new block to chainActive.
1927 bool static ConnectTip(CValidationState &state, CBlockIndex *pindexNew) {
1928  assert(pindexNew->pprev == chainActive.Tip());
1929  mempool.check(pcoinsTip);
1930  // Read block from disk.
1931  CBlock block;
1932  if (!ReadBlockFromDisk(block, pindexNew))
1933  return state.Abort(_("Failed to read block"));
1934  // Apply the block atomically to the chain state.
1935  int64_t nStart = GetTimeMicros();
1936  {
1937  CCoinsViewCache view(*pcoinsTip, true);
1938  CInv inv(MSG_BLOCK, pindexNew->GetBlockHash());
1939  if (!ConnectBlock(block, state, pindexNew, view)) {
1940  if (state.IsInvalid())
1941  InvalidBlockFound(pindexNew, state);
1942  return error("ConnectTip() : ConnectBlock %s failed", pindexNew->GetBlockHash().ToString());
1943  }
1944  mapBlockSource.erase(inv.hash);
1945  assert(view.Flush());
1946  }
1947  if (fBenchmark)
1948  LogPrintf("- Connect: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
1949  // Write the chain state to disk, if necessary.
1950  if (!WriteChainState(state))
1951  return false;
1952  // Remove conflicting transactions from the mempool.
1953  list<CTransaction> txConflicted;
1954  BOOST_FOREACH(const CTransaction &tx, block.vtx) {
1955  list<CTransaction> unused;
1956  mempool.remove(tx, unused);
1957  mempool.removeConflicts(tx, txConflicted);
1958  }
1959  mempool.check(pcoinsTip);
1960  // Update chainActive & related variables.
1961  UpdateTip(pindexNew);
1962  // Tell wallet about transactions that went from mempool
1963  // to conflicted:
1964  BOOST_FOREACH(const CTransaction &tx, txConflicted) {
1965  SyncWithWallets(tx.GetHash(), tx, NULL);
1966  }
1967  // ... and about transactions that got confirmed:
1968  BOOST_FOREACH(const CTransaction &tx, block.vtx) {
1969  SyncWithWallets(tx.GetHash(), tx, &block);
1970  }
1971  return true;
1972 }
1973 
1974 // Make chainMostWork correspond to the chain with the most work in it, that isn't
1975 // known to be invalid (it's however far from certain to be valid).
1976 void static FindMostWorkChain() {
1977  CBlockIndex *pindexNew = NULL;
1978 
1979  // In case the current best is invalid, do not consider it.
1980  while (chainMostWork.Tip() && (chainMostWork.Tip()->nStatus & BLOCK_FAILED_MASK)) {
1981  setBlockIndexValid.erase(chainMostWork.Tip());
1982  chainMostWork.SetTip(chainMostWork.Tip()->pprev);
1983  }
1984 
1985  do {
1986  // Find the best candidate header.
1987  {
1988  std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexValid.rbegin();
1989  if (it == setBlockIndexValid.rend())
1990  return;
1991  pindexNew = *it;
1992  }
1993 
1994  // Check whether all blocks on the path between the currently active chain and the candidate are valid.
1995  // Just going until the active chain is an optimization, as we know all blocks in it are valid already.
1996  CBlockIndex *pindexTest = pindexNew;
1997  bool fInvalidAncestor = false;
1998  while (pindexTest && !chainActive.Contains(pindexTest)) {
1999  if (pindexTest->nStatus & BLOCK_FAILED_MASK) {
2000  // Candidate has an invalid ancestor, remove entire chain from the set.
2001  if (pindexBestInvalid == NULL || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
2002  pindexBestInvalid = pindexNew; CBlockIndex *pindexFailed = pindexNew;
2003  while (pindexTest != pindexFailed) {
2004  pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
2005  setBlockIndexValid.erase(pindexFailed);
2006  pindexFailed = pindexFailed->pprev;
2007  }
2008  fInvalidAncestor = true;
2009  break;
2010  }
2011  pindexTest = pindexTest->pprev;
2012  }
2013  if (fInvalidAncestor)
2014  continue;
2015 
2016  break;
2017  } while(true);
2018 
2019  // Check whether it's actually an improvement.
2020  if (chainMostWork.Tip() && !CBlockIndexWorkComparator()(chainMostWork.Tip(), pindexNew))
2021  return;
2022 
2023  // We have a new best.
2024  chainMostWork.SetTip(pindexNew);
2025 }
2026 
2027 // Try to activate to the most-work chain (thereby connecting it).
2029  LOCK(cs_main);
2030  CBlockIndex *pindexOldTip = chainActive.Tip();
2031  bool fComplete = false;
2032  while (!fComplete) {
2033  FindMostWorkChain();
2034  fComplete = true;
2035 
2036  // Check whether we have something to do.
2037  if (chainMostWork.Tip() == NULL) break;
2038 
2039  // Disconnect active blocks which are no longer in the best chain.
2040  while (chainActive.Tip() && !chainMostWork.Contains(chainActive.Tip())) {
2041  if (!DisconnectTip(state))
2042  return false;
2043  }
2044 
2045  // Connect new blocks.
2046  while (!chainActive.Contains(chainMostWork.Tip())) {
2047  CBlockIndex *pindexConnect = chainMostWork[chainActive.Height() + 1];
2048  if (!ConnectTip(state, pindexConnect)) {
2049  if (state.IsInvalid()) {
2050  // The block violates a consensus rule.
2051  if (!state.CorruptionPossible())
2052  InvalidChainFound(chainMostWork.Tip());
2053  fComplete = false;
2054  state = CValidationState();
2055  break;
2056  } else {
2057  // A system error occurred (disk space, database error, ...).
2058  return false;
2059  }
2060  }
2061  }
2062  }
2063 
2064  if (chainActive.Tip() != pindexOldTip) {
2065  std::string strCmd = GetArg("-blocknotify", "");
2066  if (!IsInitialBlockDownload() && !strCmd.empty())
2067  {
2068  boost::replace_all(strCmd, "%s", chainActive.Tip()->GetBlockHash().GetHex());
2069  boost::thread t(runCommand, strCmd); // thread runs free
2070  }
2071  }
2072 
2073  return true;
2074 }
2075 
2076 bool AddToBlockIndex(CBlock& block, CValidationState& state, const CDiskBlockPos& pos)
2077 {
2078  // Check for duplicate
2079  uint256 hash = block.GetHash();
2080  if (mapBlockIndex.count(hash))
2081  return state.Invalid(error("AddToBlockIndex() : %s already exists", hash.ToString()), 0, "duplicate");
2082 
2083  // Construct new block index object
2084  CBlockIndex* pindexNew = new CBlockIndex(block);
2085  assert(pindexNew);
2086  {
2087  LOCK(cs_nBlockSequenceId);
2088  pindexNew->nSequenceId = nBlockSequenceId++;
2089  }
2090  map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2091  pindexNew->phashBlock = &((*mi).first);
2092  map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(block.hashPrevBlock);
2093  if (miPrev != mapBlockIndex.end())
2094  {
2095  pindexNew->pprev = (*miPrev).second;
2096  pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2097  }
2098  pindexNew->nTx = block.vtx.size();
2099  pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + pindexNew->GetBlockWork().getuint256();
2100  pindexNew->nChainTx = (pindexNew->pprev ? pindexNew->pprev->nChainTx : 0) + pindexNew->nTx;
2101  pindexNew->nFile = pos.nFile;
2102  pindexNew->nDataPos = pos.nPos;
2103  pindexNew->nUndoPos = 0;
2105  setBlockIndexValid.insert(pindexNew);
2106 
2107  if (!pblocktree->WriteBlockIndex(CDiskBlockIndex(pindexNew)))
2108  return state.Abort(_("Failed to write block index"));
2109 
2110  // New best?
2111  if (!ActivateBestChain(state))
2112  return false;
2113 
2114  LOCK(cs_main);
2115  if (pindexNew == chainActive.Tip())
2116  {
2117  // Clear fork warning if its no longer applicable
2119  // Notify UI to display prev block's coinbase if it was ours
2120  static uint256 hashPrevBestCoinBase;
2121  g_signals.UpdatedTransaction(hashPrevBestCoinBase);
2122  hashPrevBestCoinBase = block.GetTxHash(0);
2123  } else
2125 
2126  if (!pblocktree->Flush())
2127  return state.Abort(_("Failed to sync block index"));
2128 
2130  return true;
2131 }
2132 
2133 
2134 bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false)
2135 {
2136  bool fUpdatedLast = false;
2137 
2138  LOCK(cs_LastBlockFile);
2139 
2140  if (fKnown) {
2141  if (nLastBlockFile != pos.nFile) {
2142  nLastBlockFile = pos.nFile;
2143  infoLastBlockFile.SetNull();
2144  pblocktree->ReadBlockFileInfo(nLastBlockFile, infoLastBlockFile);
2145  fUpdatedLast = true;
2146  }
2147  } else {
2148  while (infoLastBlockFile.nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
2149  LogPrintf("Leaving block file %i: %s\n", nLastBlockFile, infoLastBlockFile.ToString());
2150  FlushBlockFile(true);
2151  nLastBlockFile++;
2152  infoLastBlockFile.SetNull();
2153  pblocktree->ReadBlockFileInfo(nLastBlockFile, infoLastBlockFile); // check whether data for the new file somehow already exist; can fail just fine
2154  fUpdatedLast = true;
2155  }
2156  pos.nFile = nLastBlockFile;
2157  pos.nPos = infoLastBlockFile.nSize;
2158  }
2159 
2160  infoLastBlockFile.nSize += nAddSize;
2161  infoLastBlockFile.AddBlock(nHeight, nTime);
2162 
2163  if (!fKnown) {
2164  unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2165  unsigned int nNewChunks = (infoLastBlockFile.nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2166  if (nNewChunks > nOldChunks) {
2167  if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
2168  FILE *file = OpenBlockFile(pos);
2169  if (file) {
2170  LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
2171  AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
2172  fclose(file);
2173  }
2174  }
2175  else
2176  return state.Error("out of disk space");
2177  }
2178  }
2179 
2180  if (!pblocktree->WriteBlockFileInfo(nLastBlockFile, infoLastBlockFile))
2181  return state.Abort(_("Failed to write file info"));
2182  if (fUpdatedLast)
2183  pblocktree->WriteLastBlockFile(nLastBlockFile);
2184 
2185  return true;
2186 }
2187 
2188 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
2189 {
2190  pos.nFile = nFile;
2191 
2192  LOCK(cs_LastBlockFile);
2193 
2194  unsigned int nNewSize;
2195  if (nFile == nLastBlockFile) {
2196  pos.nPos = infoLastBlockFile.nUndoSize;
2197  nNewSize = (infoLastBlockFile.nUndoSize += nAddSize);
2198  if (!pblocktree->WriteBlockFileInfo(nLastBlockFile, infoLastBlockFile))
2199  return state.Abort(_("Failed to write block info"));
2200  } else {
2201  CBlockFileInfo info;
2202  if (!pblocktree->ReadBlockFileInfo(nFile, info))
2203  return state.Abort(_("Failed to read block info"));
2204  pos.nPos = info.nUndoSize;
2205  nNewSize = (info.nUndoSize += nAddSize);
2206  if (!pblocktree->WriteBlockFileInfo(nFile, info))
2207  return state.Abort(_("Failed to write block info"));
2208  }
2209 
2210  unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2211  unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2212  if (nNewChunks > nOldChunks) {
2213  if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
2214  FILE *file = OpenUndoFile(pos);
2215  if (file) {
2216  LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
2217  AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
2218  fclose(file);
2219  }
2220  }
2221  else
2222  return state.Error("out of disk space");
2223  }
2224 
2225  return true;
2226 }
2227 
2228 
2229 bool CheckBlock(const CBlock& block, CValidationState& state, bool fCheckPOW, bool fCheckMerkleRoot)
2230 {
2231  // These are checks that are independent of context
2232  // that can be verified before saving an orphan block.
2233 
2234  // Size limits
2235  if (block.vtx.empty() || block.vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
2236  return state.DoS(100, error("CheckBlock() : size limits failed"),
2237  REJECT_INVALID, "bad-blk-length");
2238 
2239  // Check proof of work matches claimed amount
2240  if (fCheckPOW && !CheckProofOfWork(block.GetPoWHash(), block.nBits))
2241  return state.DoS(50, error("CheckBlock() : proof of work failed"),
2242  REJECT_INVALID, "high-hash");
2243 
2244  // Check timestamp
2245  if (block.GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
2246  return state.Invalid(error("CheckBlock() : block timestamp too far in the future"),
2247  REJECT_INVALID, "time-too-new");
2248 
2249  // First transaction must be coinbase, the rest must not be
2250  if (block.vtx.empty() || !block.vtx[0].IsCoinBase())
2251  return state.DoS(100, error("CheckBlock() : first tx is not coinbase"),
2252  REJECT_INVALID, "bad-cb-missing");
2253  for (unsigned int i = 1; i < block.vtx.size(); i++)
2254  if (block.vtx[i].IsCoinBase())
2255  return state.DoS(100, error("CheckBlock() : more than one coinbase"),
2256  REJECT_INVALID, "bad-cb-multiple");
2257 
2258  // Check transactions
2259  BOOST_FOREACH(const CTransaction& tx, block.vtx)
2260  if (!CheckTransaction(tx, state))
2261  return error("CheckBlock() : CheckTransaction failed");
2262 
2263  // Build the merkle tree already. We need it anyway later, and it makes the
2264  // block cache the transaction hashes, which means they don't need to be
2265  // recalculated many times during this block's validation.
2266  block.BuildMerkleTree();
2267 
2268  // Check for duplicate txids. This is caught by ConnectInputs(),
2269  // but catching it earlier avoids a potential DoS attack:
2270  set<uint256> uniqueTx;
2271  for (unsigned int i = 0; i < block.vtx.size(); i++) {
2272  uniqueTx.insert(block.GetTxHash(i));
2273  }
2274  if (uniqueTx.size() != block.vtx.size())
2275  return state.DoS(100, error("CheckBlock() : duplicate transaction"),
2276  REJECT_INVALID, "bad-txns-duplicate", true);
2277 
2278  unsigned int nSigOps = 0;
2279  BOOST_FOREACH(const CTransaction& tx, block.vtx)
2280  {
2281  nSigOps += GetLegacySigOpCount(tx);
2282  }
2283  if (nSigOps > MAX_BLOCK_SIGOPS)
2284  return state.DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"),
2285  REJECT_INVALID, "bad-blk-sigops", true);
2286 
2287  // Check merkle root
2288  if (fCheckMerkleRoot && block.hashMerkleRoot != block.vMerkleTree.back())
2289  return state.DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"),
2290  REJECT_INVALID, "bad-txnmrklroot", true);
2291 
2292  return true;
2293 }
2294 
2296 {
2297  AssertLockHeld(cs_main);
2298  // Check for duplicate
2299  uint256 hash = block.GetHash();
2300  if (mapBlockIndex.count(hash))
2301  return state.Invalid(error("AcceptBlock() : block already in mapBlockIndex"), 0, "duplicate");
2302 
2303  // Get prev block index
2304  CBlockIndex* pindexPrev = NULL;
2305  int nHeight = 0;
2306  if (hash != Params().HashGenesisBlock()) {
2307  map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
2308  if (mi == mapBlockIndex.end())
2309  return state.DoS(10, error("AcceptBlock() : prev block not found"), 0, "bad-prevblk");
2310  pindexPrev = (*mi).second;
2311  nHeight = pindexPrev->nHeight+1;
2312 
2313  // Check proof of work
2314  if (block.nBits != GetNextWorkRequired(pindexPrev, &block))
2315  return state.DoS(100, error("AcceptBlock() : incorrect proof of work"),
2316  REJECT_INVALID, "bad-diffbits");
2317 
2318  // Check timestamp against prev
2319  if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
2320  return state.Invalid(error("AcceptBlock() : block's timestamp is too early"),
2321  REJECT_INVALID, "time-too-old");
2322 
2323  // Check that all transactions are finalized
2324  BOOST_FOREACH(const CTransaction& tx, block.vtx)
2325  if (!IsFinalTx(tx, nHeight, block.GetBlockTime()))
2326  return state.DoS(10, error("AcceptBlock() : contains a non-final transaction"),
2327  REJECT_INVALID, "bad-txns-nonfinal");
2328 
2329  // Check that the block chain matches the known block chain up to a checkpoint
2330  if (!Checkpoints::CheckBlock(nHeight, hash))
2331  return state.DoS(100, error("AcceptBlock() : rejected by checkpoint lock-in at %d", nHeight),
2332  REJECT_CHECKPOINT, "checkpoint mismatch");
2333 
2334  // Don't accept any forks from the main chain prior to last checkpoint
2336  if (pcheckpoint && nHeight < pcheckpoint->nHeight)
2337  return state.DoS(100, error("AcceptBlock() : forked chain older than last checkpoint (height %d)", nHeight));
2338 
2339  // Reject block.nVersion=1 blocks (mainnet >= 710000, testnet >= 400000)
2340  if (block.nVersion < 2)
2341  {
2342  if ((!TestNet() && nHeight >= 710000) ||
2343  (TestNet() && nHeight >= 400000))
2344  {
2345  return state.Invalid(error("AcceptBlock() : rejected nVersion=1 block"),
2346  REJECT_OBSOLETE, "bad-version");
2347  }
2348  }
2349  // Enforce block.nVersion=2 rule that the coinbase starts with serialized block height
2350  if (block.nVersion >= 2)
2351  {
2352  if ((!TestNet() && nHeight >= 710000) ||
2353  (TestNet() && nHeight >= 400000))
2354  {
2355  CScript expect = CScript() << nHeight;
2356  if (block.vtx[0].vin[0].scriptSig.size() < expect.size() ||
2357  !std::equal(expect.begin(), expect.end(), block.vtx[0].vin[0].scriptSig.begin()))
2358  return state.DoS(100, error("AcceptBlock() : block height mismatch in coinbase"),
2359  REJECT_INVALID, "bad-cb-height");
2360  }
2361  }
2362  }
2363 
2364  // Write block to history file
2365  try {
2366  unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
2367  CDiskBlockPos blockPos;
2368  if (dbp != NULL)
2369  blockPos = *dbp;
2370  if (!FindBlockPos(state, blockPos, nBlockSize+8, nHeight, block.nTime, dbp != NULL))
2371  return error("AcceptBlock() : FindBlockPos failed");
2372  if (dbp == NULL)
2373  if (!WriteBlockToDisk(block, blockPos))
2374  return state.Abort(_("Failed to write block"));
2375  if (!AddToBlockIndex(block, state, blockPos))
2376  return error("AcceptBlock() : AddToBlockIndex failed");
2377  } catch(std::runtime_error &e) {
2378  return state.Abort(_("System error: ") + e.what());
2379  }
2380 
2381  // Relay inventory, but don't relay old inventory during initial block download
2382  int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
2383  if (chainActive.Tip()->GetBlockHash() == hash)
2384  {
2385  LOCK(cs_vNodes);
2386  BOOST_FOREACH(CNode* pnode, vNodes)
2387  if (chainActive.Height() > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
2388  pnode->PushInventory(CInv(MSG_BLOCK, hash));
2389  }
2390 
2391  return true;
2392 }
2393 
2394 bool CBlockIndex::IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired, unsigned int nToCheck)
2395 {
2396  unsigned int nFound = 0;
2397  for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++)
2398  {
2399  if (pstart->nVersion >= minVersion)
2400  ++nFound;
2401  pstart = pstart->pprev;
2402  }
2403  return (nFound >= nRequired);
2404 }
2405 
2407 {
2408  AssertLockHeld(cs_main);
2409  const CBlockIndex* pindex = this;
2410  for (int i = 0; i < nMedianTimeSpan/2; i++)
2411  {
2412  if (!chainActive.Next(pindex))
2413  return GetBlockTime();
2414  pindex = chainActive.Next(pindex);
2415  }
2416  return pindex->GetMedianTimePast();
2417 }
2418 
2419 void PushGetBlocks(CNode* pnode, CBlockIndex* pindexBegin, uint256 hashEnd)
2420 {
2421  AssertLockHeld(cs_main);
2422  // Filter out duplicate requests
2423  if (pindexBegin == pnode->pindexLastGetBlocksBegin && hashEnd == pnode->hashLastGetBlocksEnd)
2424  return;
2425  pnode->pindexLastGetBlocksBegin = pindexBegin;
2426  pnode->hashLastGetBlocksEnd = hashEnd;
2427 
2428  pnode->PushMessage("getblocks", chainActive.GetLocator(pindexBegin), hashEnd);
2429 }
2430 
2431 bool ProcessBlock(CValidationState &state, CNode* pfrom, CBlock* pblock, CDiskBlockPos *dbp)
2432 {
2433  AssertLockHeld(cs_main);
2434 
2435  // Check for duplicate
2436  uint256 hash = pblock->GetHash();
2437  if (mapBlockIndex.count(hash))
2438  return state.Invalid(error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString()), 0, "duplicate");
2439  if (mapOrphanBlocks.count(hash))
2440  return state.Invalid(error("ProcessBlock() : already have block (orphan) %s", hash.ToString()), 0, "duplicate");
2441 
2442  // Preliminary checks
2443  if (!CheckBlock(*pblock, state))
2444  return error("ProcessBlock() : CheckBlock FAILED");
2445 
2447  if (pcheckpoint && pblock->hashPrevBlock != (chainActive.Tip() ? chainActive.Tip()->GetBlockHash() : uint256(0)))
2448  {
2449  // Extra checks to prevent "fill up memory by spamming with bogus blocks"
2450  int64_t deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
2451  if (deltaTime < 0)
2452  {
2453  return state.DoS(100, error("ProcessBlock() : block with timestamp before last checkpoint"),
2454  REJECT_CHECKPOINT, "time-too-old");
2455  }
2456  CBigNum bnNewBlock;
2457  bnNewBlock.SetCompact(pblock->nBits);
2458  CBigNum bnRequired;
2459  bnRequired.SetCompact(ComputeMinWork(pcheckpoint->nBits, deltaTime));
2460  if (bnNewBlock > bnRequired)
2461  {
2462  return state.DoS(100, error("ProcessBlock() : block with too little proof-of-work"),
2463  REJECT_INVALID, "bad-diffbits");
2464  }
2465  }
2466 
2467 
2468  // If we don't already have its previous block, shunt it off to holding area until we get it
2469  if (pblock->hashPrevBlock != 0 && !mapBlockIndex.count(pblock->hashPrevBlock))
2470  {
2471  LogPrintf("ProcessBlock: ORPHAN BLOCK %lu, prev=%s\n", (unsigned long)mapOrphanBlocks.size(), pblock->hashPrevBlock.ToString());
2472 
2473  // Accept orphans as long as there is a node to request its parents from
2474  if (pfrom) {
2475  PruneOrphanBlocks();
2476  COrphanBlock* pblock2 = new COrphanBlock();
2477  {
2478  CDataStream ss(SER_DISK, CLIENT_VERSION);
2479  ss << *pblock;
2480  pblock2->vchBlock = std::vector<unsigned char>(ss.begin(), ss.end());
2481  }
2482  pblock2->hashBlock = hash;
2483  pblock2->hashPrev = pblock->hashPrevBlock;
2484  mapOrphanBlocks.insert(make_pair(hash, pblock2));
2485  mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrev, pblock2));
2486 
2487  // Ask this guy to fill in what we're missing
2488  PushGetBlocks(pfrom, chainActive.Tip(), GetOrphanRoot(hash));
2489  }
2490  return true;
2491  }
2492 
2493  // Store to disk
2494  if (!AcceptBlock(*pblock, state, dbp))
2495  return error("ProcessBlock() : AcceptBlock FAILED");
2496 
2497  // Recursively process any orphan blocks that depended on this one
2498  vector<uint256> vWorkQueue;
2499  vWorkQueue.push_back(hash);
2500  for (unsigned int i = 0; i < vWorkQueue.size(); i++)
2501  {
2502  uint256 hashPrev = vWorkQueue[i];
2503  for (multimap<uint256, COrphanBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
2504  mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
2505  ++mi)
2506  {
2507  CBlock block;
2508  {
2509  CDataStream ss(mi->second->vchBlock, SER_DISK, CLIENT_VERSION);
2510  ss >> block;
2511  }
2512  block.BuildMerkleTree();
2513  // 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)
2514  CValidationState stateDummy;
2515  if (AcceptBlock(block, stateDummy))
2516  vWorkQueue.push_back(mi->second->hashBlock);
2517  mapOrphanBlocks.erase(mi->second->hashBlock);
2518  delete mi->second;
2519  }
2520  mapOrphanBlocksByPrev.erase(hashPrev);
2521  }
2522 
2523  LogPrintf("ProcessBlock: ACCEPTED\n");
2524  return true;
2525 }
2526 
2527 
2528 
2529 
2530 
2531 
2532 
2533 
2535 {
2536  header = block.GetBlockHeader();
2537 
2538  vector<bool> vMatch;
2539  vector<uint256> vHashes;
2540 
2541  vMatch.reserve(block.vtx.size());
2542  vHashes.reserve(block.vtx.size());
2543 
2544  for (unsigned int i = 0; i < block.vtx.size(); i++)
2545  {
2546  uint256 hash = block.vtx[i].GetHash();
2547  if (filter.IsRelevantAndUpdate(block.vtx[i], hash))
2548  {
2549  vMatch.push_back(true);
2550  vMatchedTxn.push_back(make_pair(i, hash));
2551  }
2552  else
2553  vMatch.push_back(false);
2554  vHashes.push_back(hash);
2555  }
2556 
2557  txn = CPartialMerkleTree(vHashes, vMatch);
2558 }
2559 
2560 
2561 
2562 
2563 
2564 
2565 
2566 
2567 uint256 CPartialMerkleTree::CalcHash(int height, unsigned int pos, const std::vector<uint256> &vTxid) {
2568  if (height == 0) {
2569  // hash at height 0 is the txids themself
2570  return vTxid[pos];
2571  } else {
2572  // calculate left hash
2573  uint256 left = CalcHash(height-1, pos*2, vTxid), right;
2574  // calculate right hash if not beyong the end of the array - copy left hash otherwise1
2575  if (pos*2+1 < CalcTreeWidth(height-1))
2576  right = CalcHash(height-1, pos*2+1, vTxid);
2577  else
2578  right = left;
2579  // combine subhashes
2580  return Hash(BEGIN(left), END(left), BEGIN(right), END(right));
2581  }
2582 }
2583 
2584 void CPartialMerkleTree::TraverseAndBuild(int height, unsigned int pos, const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch) {
2585  // determine whether this node is the parent of at least one matched txid
2586  bool fParentOfMatch = false;
2587  for (unsigned int p = pos << height; p < (pos+1) << height && p < nTransactions; p++)
2588  fParentOfMatch |= vMatch[p];
2589  // store as flag bit
2590  vBits.push_back(fParentOfMatch);
2591  if (height==0 || !fParentOfMatch) {
2592  // if at height 0, or nothing interesting below, store hash and stop
2593  vHash.push_back(CalcHash(height, pos, vTxid));
2594  } else {
2595  // otherwise, don't store any hash, but descend into the subtrees
2596  TraverseAndBuild(height-1, pos*2, vTxid, vMatch);
2597  if (pos*2+1 < CalcTreeWidth(height-1))
2598  TraverseAndBuild(height-1, pos*2+1, vTxid, vMatch);
2599  }
2600 }
2601 
2602 uint256 CPartialMerkleTree::TraverseAndExtract(int height, unsigned int pos, unsigned int &nBitsUsed, unsigned int &nHashUsed, std::vector<uint256> &vMatch) {
2603  if (nBitsUsed >= vBits.size()) {
2604  // overflowed the bits array - failure
2605  fBad = true;
2606  return 0;
2607  }
2608  bool fParentOfMatch = vBits[nBitsUsed++];
2609  if (height==0 || !fParentOfMatch) {
2610  // if at height 0, or nothing interesting below, use stored hash and do not descend
2611  if (nHashUsed >= vHash.size()) {
2612  // overflowed the hash array - failure
2613  fBad = true;
2614  return 0;
2615  }
2616  const uint256 &hash = vHash[nHashUsed++];
2617  if (height==0 && fParentOfMatch) // in case of height 0, we have a matched txid
2618  vMatch.push_back(hash);
2619  return hash;
2620  } else {
2621  // otherwise, descend into the subtrees to extract matched txids and hashes
2622  uint256 left = TraverseAndExtract(height-1, pos*2, nBitsUsed, nHashUsed, vMatch), right;
2623  if (pos*2+1 < CalcTreeWidth(height-1))
2624  right = TraverseAndExtract(height-1, pos*2+1, nBitsUsed, nHashUsed, vMatch);
2625  else
2626  right = left;
2627  // and combine them before returning
2628  return Hash(BEGIN(left), END(left), BEGIN(right), END(right));
2629  }
2630 }
2631 
2632 CPartialMerkleTree::CPartialMerkleTree(const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch) : nTransactions(vTxid.size()), fBad(false) {
2633  // reset state
2634  vBits.clear();
2635  vHash.clear();
2636 
2637  // calculate height of tree
2638  int nHeight = 0;
2639  while (CalcTreeWidth(nHeight) > 1)
2640  nHeight++;
2641 
2642  // traverse the partial tree
2643  TraverseAndBuild(nHeight, 0, vTxid, vMatch);
2644 }
2645 
2646 CPartialMerkleTree::CPartialMerkleTree() : nTransactions(0), fBad(true) {}
2647 
2648 uint256 CPartialMerkleTree::ExtractMatches(std::vector<uint256> &vMatch) {
2649  vMatch.clear();
2650  // An empty set will not work
2651  if (nTransactions == 0)
2652  return 0;
2653  // check for excessively high numbers of transactions
2654  if (nTransactions > MAX_BLOCK_SIZE / 60) // 60 is the lower bound for the size of a serialized CTransaction
2655  return 0;
2656  // there can never be more hashes provided than one for every txid
2657  if (vHash.size() > nTransactions)
2658  return 0;
2659  // there must be at least one bit per node in the partial tree, and at least one node per hash
2660  if (vBits.size() < vHash.size())
2661  return 0;
2662  // calculate height of tree
2663  int nHeight = 0;
2664  while (CalcTreeWidth(nHeight) > 1)
2665  nHeight++;
2666  // traverse the partial tree
2667  unsigned int nBitsUsed = 0, nHashUsed = 0;
2668  uint256 hashMerkleRoot = TraverseAndExtract(nHeight, 0, nBitsUsed, nHashUsed, vMatch);
2669  // verify that no problems occured during the tree traversal
2670  if (fBad)
2671  return 0;
2672  // verify that all bits were consumed (except for the padding caused by serializing it as a byte sequence)
2673  if ((nBitsUsed+7)/8 != (vBits.size()+7)/8)
2674  return 0;
2675  // verify that all hashes were consumed
2676  if (nHashUsed != vHash.size())
2677  return 0;
2678  return hashMerkleRoot;
2679 }
2680 
2681 
2682 
2683 
2684 
2685 
2686 
2687 bool AbortNode(const std::string &strMessage) {
2688  strMiscWarning = strMessage;
2689  LogPrintf("*** %s\n", strMessage);
2691  StartShutdown();
2692  return false;
2693 }
2694 
2695 bool CheckDiskSpace(uint64_t nAdditionalBytes)
2696 {
2697  uint64_t nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
2698 
2699  // Check for nMinDiskSpace bytes (currently 50MB)
2700  if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
2701  return AbortNode(_("Error: Disk space is low!"));
2702 
2703  return true;
2704 }
2705 
2706 FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
2707 {
2708  if (pos.IsNull())
2709  return NULL;
2710  boost::filesystem::path path = GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
2711  boost::filesystem::create_directories(path.parent_path());
2712  FILE* file = fopen(path.string().c_str(), "rb+");
2713  if (!file && !fReadOnly)
2714  file = fopen(path.string().c_str(), "wb+");
2715  if (!file) {
2716  LogPrintf("Unable to open file %s\n", path.string());
2717  return NULL;
2718  }
2719  if (pos.nPos) {
2720  if (fseek(file, pos.nPos, SEEK_SET)) {
2721  LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string());
2722  fclose(file);
2723  return NULL;
2724  }
2725  }
2726  return file;
2727 }
2728 
2729 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
2730  return OpenDiskFile(pos, "blk", fReadOnly);
2731 }
2732 
2733 FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
2734  return OpenDiskFile(pos, "rev", fReadOnly);
2735 }
2736 
2738 {
2739  if (hash == 0)
2740  return NULL;
2741 
2742  // Return existing
2743  map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
2744  if (mi != mapBlockIndex.end())
2745  return (*mi).second;
2746 
2747  // Create new
2748  CBlockIndex* pindexNew = new CBlockIndex();
2749  if (!pindexNew)
2750  throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
2751  mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2752  pindexNew->phashBlock = &((*mi).first);
2753 
2754  return pindexNew;
2755 }
2756 
2757 bool static LoadBlockIndexDB()
2758 {
2759  if (!pblocktree->LoadBlockIndexGuts())
2760  return false;
2761 
2762  boost::this_thread::interruption_point();
2763 
2764  // Calculate nChainWork
2765  vector<pair<int, CBlockIndex*> > vSortedByHeight;
2766  vSortedByHeight.reserve(mapBlockIndex.size());
2767  BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
2768  {
2769  CBlockIndex* pindex = item.second;
2770  vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
2771  }
2772  sort(vSortedByHeight.begin(), vSortedByHeight.end());
2773  BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
2774  {
2775  CBlockIndex* pindex = item.second;
2776  pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + pindex->GetBlockWork().getuint256();
2777  pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
2778  if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS && !(pindex->nStatus & BLOCK_FAILED_MASK))
2779  setBlockIndexValid.insert(pindex);
2780  if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork))
2781  pindexBestInvalid = pindex;
2782  }
2783 
2784  // Load block file info
2785  pblocktree->ReadLastBlockFile(nLastBlockFile);
2786  LogPrintf("LoadBlockIndexDB(): last block file = %i\n", nLastBlockFile);
2787  if (pblocktree->ReadBlockFileInfo(nLastBlockFile, infoLastBlockFile))
2788  LogPrintf("LoadBlockIndexDB(): last block file info: %s\n", infoLastBlockFile.ToString());
2789 
2790  // Check whether we need to continue reindexing
2791  bool fReindexing = false;
2792  pblocktree->ReadReindexing(fReindexing);
2793  fReindex |= fReindexing;
2794 
2795  // Check whether we have a transaction index
2796  pblocktree->ReadFlag("txindex", fTxIndex);
2797  LogPrintf("LoadBlockIndexDB(): transaction index %s\n", fTxIndex ? "enabled" : "disabled");
2798 
2799  // Load pointer to end of best chain
2800  std::map<uint256, CBlockIndex*>::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
2801  if (it == mapBlockIndex.end())
2802  return true;
2803  chainActive.SetTip(it->second);
2804  LogPrintf("LoadBlockIndexDB(): hashBestChain=%s height=%d date=%s progress=%f\n",
2805  chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(),
2806  DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
2808 
2809  return true;
2810 }
2811 
2812 bool VerifyDB(int nCheckLevel, int nCheckDepth)
2813 {
2814  LOCK(cs_main);
2815  if (chainActive.Tip() == NULL || chainActive.Tip()->pprev == NULL)
2816  return true;
2817 
2818  // Verify blocks in the best chain
2819  if (nCheckDepth <= 0)
2820  nCheckDepth = 1000000000; // suffices until the year 19000
2821  if (nCheckDepth > chainActive.Height())
2822  nCheckDepth = chainActive.Height();
2823  nCheckLevel = std::max(0, std::min(4, nCheckLevel));
2824  LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
2825  CCoinsViewCache coins(*pcoinsTip, true);
2826  CBlockIndex* pindexState = chainActive.Tip();
2827  CBlockIndex* pindexFailure = NULL;
2828  int nGoodTransactions = 0;
2829  CValidationState state;
2830  for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev)
2831  {
2832  boost::this_thread::interruption_point();
2833  if (pindex->nHeight < chainActive.Height()-nCheckDepth)
2834  break;
2835  CBlock block;
2836  // check level 0: read from disk
2837  if (!ReadBlockFromDisk(block, pindex))
2838  return error("VerifyDB() : *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
2839  // check level 1: verify block validity
2840  if (nCheckLevel >= 1 && !CheckBlock(block, state))
2841  return error("VerifyDB() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
2842  // check level 2: verify undo validity
2843  if (nCheckLevel >= 2 && pindex) {
2844  CBlockUndo undo;
2845  CDiskBlockPos pos = pindex->GetUndoPos();
2846  if (!pos.IsNull()) {
2847  if (!undo.ReadFromDisk(pos, pindex->pprev->GetBlockHash()))
2848  return error("VerifyDB() : *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
2849  }
2850  }
2851  // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
2852  if (nCheckLevel >= 3 && pindex == pindexState && (coins.GetCacheSize() + pcoinsTip->GetCacheSize()) <= 2*nCoinCacheSize + 32000) {
2853  bool fClean = true;
2854  if (!DisconnectBlock(block, state, pindex, coins, &fClean))
2855  return error("VerifyDB() : *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
2856  pindexState = pindex->pprev;
2857  if (!fClean) {
2858  nGoodTransactions = 0;
2859  pindexFailure = pindex;
2860  } else
2861  nGoodTransactions += block.vtx.size();
2862  }
2863  }
2864  if (pindexFailure)
2865  return error("VerifyDB() : *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
2866 
2867  // check level 4: try reconnecting blocks
2868  if (nCheckLevel >= 4) {
2869  CBlockIndex *pindex = pindexState;
2870  while (pindex != chainActive.Tip()) {
2871  boost::this_thread::interruption_point();
2872  pindex = chainActive.Next(pindex);
2873  CBlock block;
2874  if (!ReadBlockFromDisk(block, pindex))
2875  return error("VerifyDB() : *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
2876  if (!ConnectBlock(block, state, pindex, coins))
2877  return error("VerifyDB() : *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
2878  }
2879  }
2880 
2881  LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive.Height() - pindexState->nHeight, nGoodTransactions);
2882 
2883  return true;
2884 }
2885 
2887 {
2888  mapBlockIndex.clear();
2889  setBlockIndexValid.clear();
2890  chainActive.SetTip(NULL);
2891  pindexBestInvalid = NULL;
2892 }
2893 
2895 {
2896  // Load block index from databases
2897  if (!fReindex && !LoadBlockIndexDB())
2898  return false;
2899  return true;
2900 }
2901 
2902 
2904  LOCK(cs_main);
2905  // Check whether we're already initialized
2906  if (chainActive.Genesis() != NULL)
2907  return true;
2908 
2909  // Use the provided setting for -txindex in the new database
2910  fTxIndex = GetBoolArg("-txindex", false);
2911  pblocktree->WriteFlag("txindex", fTxIndex);
2912  LogPrintf("Initializing databases...\n");
2913 
2914  // Only add the genesis block if not reindexing (in which case we reuse the one already on disk)
2915  if (!fReindex) {
2916  try {
2917  CBlock &block = const_cast<CBlock&>(Params().GenesisBlock());
2918  // Start new block file
2919  unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
2920  CDiskBlockPos blockPos;
2921  CValidationState state;
2922  if (!FindBlockPos(state, blockPos, nBlockSize+8, 0, block.nTime))
2923  return error("LoadBlockIndex() : FindBlockPos failed");
2924  if (!WriteBlockToDisk(block, blockPos))
2925  return error("LoadBlockIndex() : writing genesis block to disk failed");
2926  if (!AddToBlockIndex(block, state, blockPos))
2927  return error("LoadBlockIndex() : genesis block not accepted");
2928  } catch(std::runtime_error &e) {
2929  return error("LoadBlockIndex() : failed to initialize block database: %s", e.what());
2930  }
2931  }
2932 
2933  return true;
2934 }
2935 
2936 
2937 
2939 {
2940  AssertLockHeld(cs_main);
2941  // pre-compute tree structure
2942  map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
2943  for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
2944  {
2945  CBlockIndex* pindex = (*mi).second;
2946  mapNext[pindex->pprev].push_back(pindex);
2947  // test
2948  //while (rand() % 3 == 0)
2949  // mapNext[pindex->pprev].push_back(pindex);
2950  }
2951 
2952  vector<pair<int, CBlockIndex*> > vStack;
2953  vStack.push_back(make_pair(0, chainActive.Genesis()));
2954 
2955  int nPrevCol = 0;
2956  while (!vStack.empty())
2957  {
2958  int nCol = vStack.back().first;
2959  CBlockIndex* pindex = vStack.back().second;
2960  vStack.pop_back();
2961 
2962  // print split or gap
2963  if (nCol > nPrevCol)
2964  {
2965  for (int i = 0; i < nCol-1; i++)
2966  LogPrintf("| ");
2967  LogPrintf("|\\\n");
2968  }
2969  else if (nCol < nPrevCol)
2970  {
2971  for (int i = 0; i < nCol; i++)
2972  LogPrintf("| ");
2973  LogPrintf("|\n");
2974  }
2975  nPrevCol = nCol;
2976 
2977  // print columns
2978  for (int i = 0; i < nCol; i++)
2979  LogPrintf("| ");
2980 
2981  // print item
2982  CBlock block;
2983  ReadBlockFromDisk(block, pindex);
2984  LogPrintf("%d (blk%05u.dat:0x%x) %s tx %u\n",
2985  pindex->nHeight,
2986  pindex->GetBlockPos().nFile, pindex->GetBlockPos().nPos,
2987  DateTimeStrFormat("%Y-%m-%d %H:%M:%S", block.GetBlockTime()),
2988  block.vtx.size());
2989 
2990  // put the main time-chain first
2991  vector<CBlockIndex*>& vNext = mapNext[pindex];
2992  for (unsigned int i = 0; i < vNext.size(); i++)
2993  {
2994  if (chainActive.Next(vNext[i]))
2995  {
2996  swap(vNext[0], vNext[i]);
2997  break;
2998  }
2999  }
3000 
3001  // iterate children
3002  for (unsigned int i = 0; i < vNext.size(); i++)
3003  vStack.push_back(make_pair(nCol+i, vNext[i]));
3004  }
3005 }
3006 
3007 bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp)
3008 {
3009  int64_t nStart = GetTimeMillis();
3010 
3011  int nLoaded = 0;
3012  try {
3013  CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SIZE, MAX_BLOCK_SIZE+8, SER_DISK, CLIENT_VERSION);
3014  uint64_t nStartByte = 0;
3015  if (dbp) {
3016  // (try to) skip already indexed part
3017  CBlockFileInfo info;
3018  if (pblocktree->ReadBlockFileInfo(dbp->nFile, info)) {
3019  nStartByte = info.nSize;
3020  blkdat.Seek(info.nSize);
3021  }
3022  }
3023  uint64_t nRewind = blkdat.GetPos();
3024  while (blkdat.good() && !blkdat.eof()) {
3025  boost::this_thread::interruption_point();
3026 
3027  blkdat.SetPos(nRewind);
3028  nRewind++; // start one byte further next time, in case of failure
3029  blkdat.SetLimit(); // remove former limit
3030  unsigned int nSize = 0;
3031  try {
3032  // locate a header
3033  unsigned char buf[MESSAGE_START_SIZE];
3034  blkdat.FindByte(Params().MessageStart()[0]);
3035  nRewind = blkdat.GetPos()+1;
3036  blkdat >> FLATDATA(buf);
3037  if (memcmp(buf, Params().MessageStart(), MESSAGE_START_SIZE))
3038  continue;
3039  // read size
3040  blkdat >> nSize;
3041  if (nSize < 80 || nSize > MAX_BLOCK_SIZE)
3042  continue;
3043  } catch (std::exception &e) {
3044  // no valid block header found; don't complain
3045  break;
3046  }
3047  try {
3048  // read block
3049  uint64_t nBlockPos = blkdat.GetPos();
3050  blkdat.SetLimit(nBlockPos + nSize);
3051  CBlock block;
3052  blkdat >> block;
3053  nRewind = blkdat.GetPos();
3054 
3055  // process block
3056  if (nBlockPos >= nStartByte) {
3057  LOCK(cs_main);
3058  if (dbp)
3059  dbp->nPos = nBlockPos;
3060  CValidationState state;
3061  if (ProcessBlock(state, NULL, &block, dbp))
3062  nLoaded++;
3063  if (state.IsError())
3064  break;
3065  }
3066  } catch (std::exception &e) {
3067  LogPrintf("%s : Deserialize or I/O error - %s", __func__, e.what());
3068  }
3069  }
3070  fclose(fileIn);
3071  } catch(std::runtime_error &e) {
3072  AbortNode(_("Error: system error: ") + e.what());
3073  }
3074  if (nLoaded > 0)
3075  LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart);
3076  return nLoaded > 0;
3077 }
3078 
3079 
3080 
3081 
3082 
3083 
3084 
3085 
3086 
3087 
3089 //
3090 // CAlert
3091 //
3092 
3093 string GetWarnings(string strFor)
3094 {
3095  int nPriority = 0;
3096  string strStatusBar;
3097  string strRPC;
3098 
3099  if (GetBoolArg("-testsafemode", false))
3100  strRPC = "test";
3101 
3103  strStatusBar = _("This is a pre-release test build - use at your own risk - do not use for mining or merchant applications");
3104 
3105  // Misc warnings like out of disk space and clock is wrong
3106  if (strMiscWarning != "")
3107  {
3108  nPriority = 1000;
3109  strStatusBar = strMiscWarning;
3110  }
3111 
3112  if (fLargeWorkForkFound)
3113  {
3114  nPriority = 2000;
3115  strStatusBar = strRPC = _("Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.");
3116  }
3117  else if (fLargeWorkInvalidChainFound)
3118  {
3119  nPriority = 2000;
3120  strStatusBar = strRPC = _("Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade.");
3121  }
3122 
3123  // Alerts
3124  {
3125  LOCK(cs_mapAlerts);
3126  BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
3127  {
3128  const CAlert& alert = item.second;
3129  if (alert.AppliesToMe() && alert.nPriority > nPriority)
3130  {
3131  nPriority = alert.nPriority;
3132  strStatusBar = alert.strStatusBar;
3133  }
3134  }
3135  }
3136 
3137  if (strFor == "statusbar")
3138  return strStatusBar;
3139  else if (strFor == "rpc")
3140  return strRPC;
3141  assert(!"GetWarnings() : invalid parameter");
3142  return "error";
3143 }
3144 
3145 void static RelayAlerts(CNode* pfrom)
3146 {
3147  LOCK(cs_mapAlerts);
3148  BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
3149  item.second.RelayTo(pfrom);
3150 }
3151 
3152 
3153 
3154 
3155 
3156 
3157 
3159 //
3160 // Messages
3161 //
3162 
3163 
3164 bool static AlreadyHave(const CInv& inv)
3165 {
3166  switch (inv.type)
3167  {
3168  case MSG_TX:
3169  {
3170  bool txInMap = false;
3171  txInMap = mempool.exists(inv.hash);
3172  return txInMap || mapOrphanTransactions.count(inv.hash) ||
3173  pcoinsTip->HaveCoins(inv.hash);
3174  }
3175  case MSG_BLOCK:
3176  return mapBlockIndex.count(inv.hash) ||
3177  mapOrphanBlocks.count(inv.hash);
3178  }
3179  // Don't know what it is, just say we already got one
3180  return true;
3181 }
3182 
3183 
3184 void static ProcessGetData(CNode* pfrom)
3185 {
3186  std::deque<CInv>::iterator it = pfrom->vRecvGetData.begin();
3187 
3188  vector<CInv> vNotFound;
3189 
3190  LOCK(cs_main);
3191 
3192  while (it != pfrom->vRecvGetData.end()) {
3193  // Don't bother if send buffer is too full to respond anyway
3194  if (pfrom->nSendSize >= SendBufferSize())
3195  break;
3196 
3197  const CInv &inv = *it;
3198  {
3199  boost::this_thread::interruption_point();
3200  it++;
3201 
3202  if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
3203  {
3204  bool send = false;
3205  map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
3206  if (mi != mapBlockIndex.end())
3207  {
3208  // If the requested block is at a height below our last
3209  // checkpoint, only serve it if it's in the checkpointed chain
3210  int nHeight = mi->second->nHeight;
3212  if (pcheckpoint && nHeight < pcheckpoint->nHeight) {
3213  if (!chainActive.Contains(mi->second))
3214  {
3215  LogPrintf("ProcessGetData(): ignoring request for old block that isn't in the main chain\n");
3216  } else {
3217  send = true;
3218  }
3219  } else {
3220  send = true;
3221  }
3222  }
3223  if (send)
3224  {
3225  // Send block from disk
3226  CBlock block;
3227  ReadBlockFromDisk(block, (*mi).second);
3228  if (inv.type == MSG_BLOCK)
3229  pfrom->PushMessage("block", block);
3230  else // MSG_FILTERED_BLOCK)
3231  {
3232  LOCK(pfrom->cs_filter);
3233  if (pfrom->pfilter)
3234  {
3235  CMerkleBlock merkleBlock(block, *pfrom->pfilter);
3236  pfrom->PushMessage("merkleblock", merkleBlock);
3237  // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
3238  // This avoids hurting performance by pointlessly requiring a round-trip
3239  // Note that there is currently no way for a node to request any single transactions we didnt send here -
3240  // they must either disconnect and retry or request the full block.
3241  // Thus, the protocol spec specified allows for us to provide duplicate txn here,
3242  // however we MUST always provide at least what the remote peer needs
3243  typedef std::pair<unsigned int, uint256> PairType;
3244  BOOST_FOREACH(PairType& pair, merkleBlock.vMatchedTxn)
3245  if (!pfrom->setInventoryKnown.count(CInv(MSG_TX, pair.second)))
3246  pfrom->PushMessage("tx", block.vtx[pair.first]);
3247  }
3248  // else
3249  // no response
3250  }
3251 
3252  // Trigger them to send a getblocks request for the next batch of inventory
3253  if (inv.hash == pfrom->hashContinue)
3254  {
3255  // Bypass PushInventory, this must send even if redundant,
3256  // and we want it right after the last block so they don't
3257  // wait for other stuff first.
3258  vector<CInv> vInv;
3259  vInv.push_back(CInv(MSG_BLOCK, chainActive.Tip()->GetBlockHash()));
3260  pfrom->PushMessage("inv", vInv);
3261  pfrom->hashContinue = 0;
3262  }
3263  }
3264  }
3265  else if (inv.IsKnownType())
3266  {
3267  // Send stream from relay memory
3268  bool pushed = false;
3269  {
3270  LOCK(cs_mapRelay);
3271  map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
3272  if (mi != mapRelay.end()) {
3273  pfrom->PushMessage(inv.GetCommand(), (*mi).second);
3274  pushed = true;
3275  }
3276  }
3277  if (!pushed && inv.type == MSG_TX) {
3278  CTransaction tx;
3279  if (mempool.lookup(inv.hash, tx)) {
3280  CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
3281  ss.reserve(1000);
3282  ss << tx;
3283  pfrom->PushMessage("tx", ss);
3284  pushed = true;
3285  }
3286  }
3287  if (!pushed) {
3288  vNotFound.push_back(inv);
3289  }
3290  }
3291 
3292  // Track requests for our stuff.
3293  g_signals.Inventory(inv.hash);
3294 
3295  if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
3296  break;
3297  }
3298  }
3299 
3300  pfrom->vRecvGetData.erase(pfrom->vRecvGetData.begin(), it);
3301 
3302  if (!vNotFound.empty()) {
3303  // Let the peer know that we didn't find what it asked for, so it doesn't
3304  // have to wait around forever. Currently only SPV clients actually care
3305  // about this message: it's needed when they are recursively walking the
3306  // dependencies of relevant unconfirmed transactions. SPV clients want to
3307  // do that because they want to know about (and store and rebroadcast and
3308  // risk analyze) the dependencies of transactions relevant to them, without
3309  // having to download the entire memory pool.
3310  pfrom->PushMessage("notfound", vNotFound);
3311  }
3312 }
3313 
3314 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
3315 {
3317  LogPrint("net", "received: %s (%u bytes)\n", strCommand, vRecv.size());
3318  if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
3319  {
3320  LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n");
3321  return true;
3322  }
3323 
3324  {
3325  LOCK(cs_main);
3326  State(pfrom->GetId())->nLastBlockProcess = GetTimeMicros();
3327  }
3328 
3329 
3330 
3331  if (strCommand == "version")
3332  {
3333  // Each connection can only send one version message
3334  if (pfrom->nVersion != 0)
3335  {
3336  pfrom->PushMessage("reject", strCommand, REJECT_DUPLICATE, string("Duplicate version message"));
3337  Misbehaving(pfrom->GetId(), 1);
3338  return false;
3339  }
3340 
3341  int64_t nTime;
3342  CAddress addrMe;
3343  CAddress addrFrom;
3344  uint64_t nNonce = 1;
3345  vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
3346  if (pfrom->nVersion < MIN_PEER_PROTO_VERSION)
3347  {
3348  // relay alerts prior to disconnection
3349  RelayAlerts(pfrom);
3350  // disconnect from peers older than this proto version
3351  LogPrintf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString(), pfrom->nVersion);
3352  pfrom->PushMessage("reject", strCommand, REJECT_OBSOLETE,
3353  strprintf("Version must be %d or greater", MIN_PEER_PROTO_VERSION));
3354  pfrom->fDisconnect = true;
3355  return true;
3356  }
3357 
3358  if (pfrom->nVersion == 10300)
3359  pfrom->nVersion = 300;
3360  if (!vRecv.empty())
3361  vRecv >> addrFrom >> nNonce;
3362  if (!vRecv.empty()) {
3363  vRecv >> LIMITED_STRING(pfrom->strSubVer, 256);
3364  pfrom->cleanSubVer = SanitizeString(pfrom->strSubVer);
3365  }
3366 
3367  // Disconnect certain incompatible clients
3368  const char *badSubVers[] = { "/potcoinseeder", "/reddcoinseeder", "/worldcoinseeder" };
3369  for (int x = 0; x < 3; x++)
3370  {
3371  if (pfrom->cleanSubVer.find(badSubVers[x], 0) == 0)
3372  {
3373  LogPrintf("invalid subver %s at %s, disconnecting\n", pfrom->cleanSubVer, pfrom->addr.ToString());
3374  pfrom->PushMessage("reject", strCommand, REJECT_INVALID, string("invalid client subver"));
3375  pfrom->fDisconnect = true;
3376  return true;
3377  }
3378  }
3379 
3380  if (!vRecv.empty())
3381  vRecv >> pfrom->nStartingHeight;
3382  if (!vRecv.empty())
3383  vRecv >> pfrom->fRelayTxes; // set to true after we get the first filter* message
3384  else
3385  pfrom->fRelayTxes = true;
3386 
3387  if (pfrom->fInbound && addrMe.IsRoutable())
3388  {
3389  pfrom->addrLocal = addrMe;
3390  SeenLocal(addrMe);
3391  }
3392 
3393  // Disconnect if we connected to ourself
3394  if (nNonce == nLocalHostNonce && nNonce > 1)
3395  {
3396  LogPrintf("connected to self at %s, disconnecting\n", pfrom->addr.ToString());
3397  pfrom->fDisconnect = true;
3398  return true;
3399  }
3400 
3401  // Be shy and don't send version until we hear
3402  if (pfrom->fInbound)
3403  pfrom->PushVersion();
3404 
3405  pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
3406 
3407 
3408  // Change version
3409  pfrom->PushMessage("verack");
3410  pfrom->ssSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3411 
3412 #ifdef ENABLE_I2PSAM
3413  pfrom->SetSendStreamType(pfrom->GetSendStreamType() & ( (pfrom->nServices & NODE_I2P) ? ~SER_IPADDRONLY : SER_IPADDRONLY));
3414 #endif
3415  if (!pfrom->fInbound)
3416  {
3417  // Advertise our address
3418  if (!fNoListen && !IsInitialBlockDownload())
3419  {
3420  CAddress addr = GetLocalAddress(&pfrom->addr);
3421  if (addr.IsRoutable())
3422  pfrom->PushAddress(addr);
3423  }
3424 
3425  // Get recent addresses
3426  if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
3427  {
3428  pfrom->PushMessage("getaddr");
3429  pfrom->fGetAddr = true;
3430  }
3431  addrman.Good(pfrom->addr);
3432  } else {
3433  if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
3434  {
3435  addrman.Add(addrFrom, addrFrom);
3436  addrman.Good(addrFrom);
3437  }
3438  }
3439 
3440  // Relay alerts
3441  RelayAlerts(pfrom);
3442 
3443  pfrom->fSuccessfullyConnected = true;
3444 
3445  LogPrintf("receive version message: %s: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", pfrom->cleanSubVer, pfrom->nVersion, pfrom->nStartingHeight, addrMe.ToString(), addrFrom.ToString(), pfrom->addr.ToString());
3446 
3447  AddTimeData(pfrom->addr, nTime);
3448  }
3449 
3450 
3451  else if (pfrom->nVersion == 0)
3452  {
3453  // Must have a version message before anything else
3454  Misbehaving(pfrom->GetId(), 1);
3455  return false;
3456  }
3457 
3458 
3459  else if (strCommand == "verack")
3460  {
3461  pfrom->SetRecvVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3462 #ifdef ENABLE_I2PSAM
3463  pfrom->SetRecvStreamType( pfrom->GetRecvStreamType() & ( (pfrom->nServices & NODE_I2P) ? ~SER_IPADDRONLY : SER_IPADDRONLY) );
3464 #endif
3465  }
3466 
3467 
3468  else if (strCommand == "addr")
3469  {
3470  vector<CAddress> vAddr;
3471  vRecv >> vAddr;
3472 
3473  // Don't want addr from older versions unless seeding
3474  if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
3475  return true;
3476  if (vAddr.size() > 1000)
3477  {
3478  Misbehaving(pfrom->GetId(), 20);
3479  return error("message addr size() = %u", vAddr.size());
3480  }
3481 
3482  // Store the new addresses
3483  vector<CAddress> vAddrOk;
3484  int64_t nNow = GetAdjustedTime();
3485  int64_t nSince = nNow - 10 * 60;
3486  BOOST_FOREACH(CAddress& addr, vAddr)
3487  {
3488  boost::this_thread::interruption_point();
3489 
3490  if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
3491  addr.nTime = nNow - 5 * 24 * 60 * 60;
3492  pfrom->AddAddressKnown(addr);
3493  bool fReachable = IsReachable(addr);
3494  if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
3495  {
3496  // Relay to a limited number of other nodes
3497  {
3498  LOCK(cs_vNodes);
3499  // Use deterministic randomness to send to the same nodes for 24 hours
3500  // at a time so the setAddrKnowns of the chosen nodes prevent repeats
3501  static uint256 hashSalt;
3502  if (hashSalt == 0)
3503  hashSalt = GetRandHash();
3504  uint64_t hashAddr = addr.GetHash();
3505  uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60));
3506  hashRand = Hash(BEGIN(hashRand), END(hashRand));
3507  multimap<uint256, CNode*> mapMix;
3508  BOOST_FOREACH(CNode* pnode, vNodes)
3509  {
3510  if (pnode->nVersion < CADDR_TIME_VERSION)
3511  continue;
3512  unsigned int nPointer;
3513  memcpy(&nPointer, &pnode, sizeof(nPointer));
3514  uint256 hashKey = hashRand ^ nPointer;
3515  hashKey = Hash(BEGIN(hashKey), END(hashKey));
3516  mapMix.insert(make_pair(hashKey, pnode));
3517  }
3518  int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
3519  for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
3520  ((*mi).second)->PushAddress(addr);
3521  }
3522  }
3523  // Do not store addresses outside our network
3524  if (fReachable)
3525 #ifdef ENABLE_I2PSAM
3526  {
3527  // Here we introduce a new concept starting with protocol version 70008, the idea of not keeping any clearnet
3528  // nodes in our own copy of the peers address book....this means that once I2P is enabled, or set as the -onlynet
3529  // we're going to increasingly add only to our own interests by using and keeping track of the I2P network peers.
3530  if( !IsI2PEnabled() || addr.IsNativeI2P() )
3531  vAddrOk.push_back(addr);
3532  }
3533 #else // Original Code
3534  vAddrOk.push_back(addr);
3535 #endif
3536 
3537  }
3538  addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
3539  if (vAddr.size() < 1000)
3540  pfrom->fGetAddr = false;
3541  if (pfrom->fOneShot)
3542  pfrom->fDisconnect = true;
3543  }
3544 
3545 
3546  else if (strCommand == "inv")
3547  {
3548  vector<CInv> vInv;
3549  vRecv >> vInv;
3550  if (vInv.size() > MAX_INV_SZ)
3551  {
3552  Misbehaving(pfrom->GetId(), 20);
3553  return error("message inv size() = %u", vInv.size());
3554  }
3555 
3556  LOCK(cs_main);
3557 
3558  for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
3559  {
3560  const CInv &inv = vInv[nInv];
3561 
3562  boost::this_thread::interruption_point();
3563  pfrom->AddInventoryKnown(inv);
3564 
3565  bool fAlreadyHave = AlreadyHave(inv);
3566  LogPrint("net", " got inventory: %s %s\n", inv.ToString(), fAlreadyHave ? "have" : "new");
3567 
3568  if (!fAlreadyHave) {
3569  if (!fImporting && !fReindex) {
3570  if (inv.type == MSG_BLOCK)
3571  AddBlockToQueue(pfrom->GetId(), inv.hash);
3572  else
3573  pfrom->AskFor(inv);
3574  }
3575  } else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) {
3576  PushGetBlocks(pfrom, chainActive.Tip(), GetOrphanRoot(inv.hash));
3577  }
3578 
3579  // Track requests for our stuff
3580  g_signals.Inventory(inv.hash);
3581 
3582  if (pfrom->nSendSize > (SendBufferSize() * 2)) {
3583  Misbehaving(pfrom->GetId(), 50);
3584  return error("send buffer size() = %u", pfrom->nSendSize);
3585  }
3586  }
3587  }
3588 
3589 
3590  else if (strCommand == "getdata")
3591  {
3592  vector<CInv> vInv;
3593  vRecv >> vInv;
3594  if (vInv.size() > MAX_INV_SZ)
3595  {
3596  Misbehaving(pfrom->GetId(), 20);
3597  return error("message getdata size() = %u", vInv.size());
3598  }
3599 
3600  if (fDebug || (vInv.size() != 1))
3601  LogPrint("net", "received getdata (%u invsz)\n", vInv.size());
3602 
3603  if ((fDebug && vInv.size() > 0) || (vInv.size() == 1))
3604  LogPrint("net", "received getdata for: %s\n", vInv[0].ToString());
3605 
3606  pfrom->vRecvGetData.insert(pfrom->vRecvGetData.end(), vInv.begin(), vInv.end());
3607  ProcessGetData(pfrom);
3608  }
3609 
3610 
3611  else if (strCommand == "getblocks")
3612  {
3613  CBlockLocator locator;
3614  uint256 hashStop;
3615  vRecv >> locator >> hashStop;
3616 
3617  LOCK(cs_main);
3618 
3619  // Find the last block the caller has in the main chain
3620  CBlockIndex* pindex = chainActive.FindFork(locator);
3621 
3622  // Send the rest of the chain
3623  if (pindex)
3624  pindex = chainActive.Next(pindex);
3625  int nLimit = 500;
3626  LogPrint("net", "getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString(), nLimit);
3627  for (; pindex; pindex = chainActive.Next(pindex))
3628  {
3629  if (pindex->GetBlockHash() == hashStop)
3630  {
3631  LogPrint("net", " getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3632  break;
3633  }
3634  pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
3635  if (--nLimit <= 0)
3636  {
3637  // When this block is requested, we'll send an inv that'll make them
3638  // getblocks the next batch of inventory.
3639  LogPrint("net", " getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3640  pfrom->hashContinue = pindex->GetBlockHash();
3641  break;
3642  }
3643  }
3644  }
3645 
3646 
3647  else if (strCommand == "getheaders")
3648  {
3649  CBlockLocator locator;
3650  uint256 hashStop;
3651  vRecv >> locator >> hashStop;
3652 
3653  LOCK(cs_main);
3654 
3655  CBlockIndex* pindex = NULL;
3656  if (locator.IsNull())
3657  {
3658  // If locator is null, return the hashStop block
3659  map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
3660  if (mi == mapBlockIndex.end())
3661  return true;
3662  pindex = (*mi).second;
3663  }
3664  else
3665  {
3666  // Find the last block the caller has in the main chain
3667  pindex = chainActive.FindFork(locator);
3668  if (pindex)
3669  pindex = chainActive.Next(pindex);
3670  }
3671 
3672  // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
3673  vector<CBlock> vHeaders;
3674  int nLimit = 2000;
3675  LogPrint("net", "getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString());
3676  for (; pindex; pindex = chainActive.Next(pindex))
3677  {
3678  vHeaders.push_back(pindex->GetBlockHeader());
3679  if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
3680  break;
3681  }
3682  pfrom->PushMessage("headers", vHeaders);
3683  }
3684 
3685 
3686  else if (strCommand == "tx")
3687  {
3688  vector<uint256> vWorkQueue;
3689  vector<uint256> vEraseQueue;
3690  CTransaction tx;
3691  vRecv >> tx;
3692 
3693  CInv inv(MSG_TX, tx.GetHash());
3694  pfrom->AddInventoryKnown(inv);
3695 
3696  LOCK(cs_main);
3697 
3698  bool fMissingInputs = false;
3699  CValidationState state;
3700  if (AcceptToMemoryPool(mempool, state, tx, true, &fMissingInputs))
3701  {
3702  mempool.check(pcoinsTip);
3703  RelayTransaction(tx, inv.hash);
3704  mapAlreadyAskedFor.erase(inv);
3705  vWorkQueue.push_back(inv.hash);
3706  vEraseQueue.push_back(inv.hash);
3707 
3708 
3709  LogPrint("mempool", "AcceptToMemoryPool: %s %s : accepted %s (poolsz %u)\n",
3710  pfrom->addr.ToString(), pfrom->cleanSubVer,
3711  tx.GetHash().ToString(),
3712  mempool.mapTx.size());
3713 
3714  // Recursively process any orphan transactions that depended on this one
3715  set<NodeId> setMisbehaving;
3716  for (unsigned int i = 0; i < vWorkQueue.size(); i++)
3717  {
3718  map<uint256, set<uint256> >::iterator itByPrev = mapOrphanTransactionsByPrev.find(vWorkQueue[i]);
3719  if (itByPrev == mapOrphanTransactionsByPrev.end())
3720  continue;
3721  for (set<uint256>::iterator mi = itByPrev->second.begin();
3722  mi != itByPrev->second.end();
3723  ++mi)
3724  {
3725  const uint256& orphanHash = *mi;
3726  const CTransaction& orphanTx = mapOrphanTransactions[orphanHash].tx;
3727  NodeId fromPeer = mapOrphanTransactions[orphanHash].fromPeer;
3728  bool fMissingInputs2 = false;
3729  // Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan
3730  // resolution (that is, feeding people an invalid transaction based on LegitTxX in order to get
3731  // anyone relaying LegitTxX banned)
3732  CValidationState stateDummy;
3733 
3734  vEraseQueue.push_back(orphanHash);
3735 
3736  if (setMisbehaving.count(fromPeer))
3737  continue;
3738  if (AcceptToMemoryPool(mempool, stateDummy, orphanTx, true, &fMissingInputs2))
3739  {
3740  LogPrint("mempool", " accepted orphan tx %s\n", orphanHash.ToString());
3741  RelayTransaction(orphanTx, orphanHash);
3742  mapAlreadyAskedFor.erase(CInv(MSG_TX, orphanHash));
3743  vWorkQueue.push_back(orphanHash);
3744  }
3745  else if (!fMissingInputs2)
3746  {
3747  int nDos = 0;
3748  if (stateDummy.IsInvalid(nDos) && nDos > 0)
3749  {
3750  // Punish peer that gave us an invalid orphan tx
3751  Misbehaving(fromPeer, nDos);
3752  setMisbehaving.insert(fromPeer);
3753  LogPrint("mempool", " invalid orphan tx %s\n", orphanHash.ToString());
3754  }
3755  // too-little-fee orphan
3756  LogPrint("mempool", " removed orphan tx %s\n", orphanHash.ToString());
3757  }
3758  mempool.check(pcoinsTip);
3759  }
3760  }
3761 
3762  BOOST_FOREACH(uint256 hash, vEraseQueue)
3763  EraseOrphanTx(hash);
3764  }
3765  else if (fMissingInputs)
3766  {
3767  AddOrphanTx(tx, pfrom->GetId());
3768 
3769  // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
3770  unsigned int nMaxOrphanTx = (unsigned int)std::max((int64_t)0, GetArg("-maxorphantx", DEFAULT_MAX_ORPHAN_TRANSACTIONS));
3771  unsigned int nEvicted = LimitOrphanTxSize(nMaxOrphanTx);
3772  if (nEvicted > 0)
3773  LogPrint("mempool", "mapOrphan overflow, removed %u tx\n", nEvicted);
3774  }
3775  int nDoS = 0;
3776  if (state.IsInvalid(nDoS))
3777  {
3778  LogPrint("mempool", "%s from %s %s was not accepted into the memory pool: %s\n", tx.GetHash().ToString(),
3779  pfrom->addr.ToString(), pfrom->cleanSubVer,
3780  state.GetRejectReason());
3781  pfrom->PushMessage("reject", strCommand, state.GetRejectCode(),
3782  state.GetRejectReason(), inv.hash);
3783  if (nDoS > 0)
3784  Misbehaving(pfrom->GetId(), nDoS);
3785  }
3786  }
3787 
3788 
3789  else if (strCommand == "block" && !fImporting && !fReindex) // Ignore blocks received while importing
3790  {
3791  CBlock block;
3792  vRecv >> block;
3793 
3794  LogPrint("net", "received block %s\n", block.GetHash().ToString());
3795  // block.print();
3796 
3797  CInv inv(MSG_BLOCK, block.GetHash());
3798  pfrom->AddInventoryKnown(inv);
3799 
3800  LOCK(cs_main);
3801  // Remember who we got this block from.
3802  mapBlockSource[inv.hash] = pfrom->GetId();
3803  MarkBlockAsReceived(inv.hash, pfrom->GetId());
3804 
3805  CValidationState state;
3806  ProcessBlock(state, pfrom, &block);
3807  }
3808 
3809 
3810  else if (strCommand == "getaddr")
3811  {
3812  pfrom->vAddrToSend.clear();
3813  vector<CAddress> vAddr = addrman.GetAddr();
3814  BOOST_FOREACH(const CAddress &addr, vAddr)
3815  pfrom->PushAddress(addr);
3816  }
3817 
3818 
3819  else if (strCommand == "mempool")
3820  {
3821  LOCK2(cs_main, pfrom->cs_filter);
3822 
3823  std::vector<uint256> vtxid;
3824  mempool.queryHashes(vtxid);
3825  vector<CInv> vInv;
3826  BOOST_FOREACH(uint256& hash, vtxid) {
3827  CInv inv(MSG_TX, hash);
3828  CTransaction tx;
3829  bool fInMemPool = mempool.lookup(hash, tx);
3830  if (!fInMemPool) continue; // another thread removed since queryHashes, maybe...
3831  if ((pfrom->pfilter && pfrom->pfilter->IsRelevantAndUpdate(tx, hash)) ||
3832  (!pfrom->pfilter))
3833  vInv.push_back(inv);
3834  if (vInv.size() == MAX_INV_SZ) {
3835  pfrom->PushMessage("inv", vInv);
3836  vInv.clear();
3837  }
3838  }
3839  if (vInv.size() > 0)
3840  pfrom->PushMessage("inv", vInv);
3841  }
3842 
3843 
3844  else if (strCommand == "ping")
3845  {
3846  if (pfrom->nVersion > BIP0031_VERSION)
3847  {
3848  uint64_t nonce = 0;
3849  vRecv >> nonce;
3850  // Echo the message back with the nonce. This allows for two useful features:
3851  //
3852  // 1) A remote node can quickly check if the connection is operational
3853  // 2) Remote nodes can measure the latency of the network thread. If this node
3854  // is overloaded it won't respond to pings quickly and the remote node can
3855  // avoid sending us more work, like chain download requests.
3856  //
3857  // The nonce stops the remote getting confused between different pings: without
3858  // it, if the remote node sends a ping once per second and this node takes 5
3859  // seconds to respond to each, the 5th ping the remote sends would appear to
3860  // return very quickly.
3861  pfrom->PushMessage("pong", nonce);
3862  }
3863  }
3864 
3865 
3866  else if (strCommand == "pong")
3867  {
3868  int64_t pingUsecEnd = GetTimeMicros();
3869  uint64_t nonce = 0;
3870  size_t nAvail = vRecv.in_avail();
3871  bool bPingFinished = false;
3872  std::string sProblem;
3873 
3874  if (nAvail >= sizeof(nonce)) {
3875  vRecv >> nonce;
3876 
3877  // Only process pong message if there is an outstanding ping (old ping without nonce should never pong)
3878  if (pfrom->nPingNonceSent != 0) {
3879  if (nonce == pfrom->nPingNonceSent) {
3880  // Matching pong received, this ping is no longer outstanding
3881  bPingFinished = true;
3882  int64_t pingUsecTime = pingUsecEnd - pfrom->nPingUsecStart;
3883  if (pingUsecTime > 0) {
3884  // Successful ping time measurement, replace previous
3885  pfrom->nPingUsecTime = pingUsecTime;
3886  } else {
3887  // This should never happen
3888  sProblem = "Timing mishap";
3889  }
3890  } else {
3891  // Nonce mismatches are normal when pings are overlapping
3892  sProblem = "Nonce mismatch";
3893  if (nonce == 0) {
3894  // This is most likely a bug in another implementation somewhere, cancel this ping
3895  bPingFinished = true;
3896  sProblem = "Nonce zero";
3897  }
3898  }
3899  } else {
3900  sProblem = "Unsolicited pong without ping";
3901  }
3902  } else {
3903  // This is most likely a bug in another implementation somewhere, cancel this ping
3904  bPingFinished = true;
3905  sProblem = "Short payload";
3906  }
3907 
3908  if (!(sProblem.empty())) {
3909  LogPrint("net", "pong %s %s: %s, %x expected, %x received, %u bytes\n",
3910  pfrom->addr.ToString(),
3911  pfrom->cleanSubVer,
3912  sProblem,
3913  pfrom->nPingNonceSent,
3914  nonce,
3915  nAvail);
3916  }
3917  if (bPingFinished) {
3918  pfrom->nPingNonceSent = 0;
3919  }
3920  }
3921 
3922 
3923  else if (strCommand == "alert")
3924  {
3925  CAlert alert;
3926  vRecv >> alert;
3927 
3928  uint256 alertHash = alert.GetHash();
3929  if (pfrom->setKnown.count(alertHash) == 0)
3930  {
3931  if (alert.ProcessAlert())
3932  {
3933  // Relay
3934  pfrom->setKnown.insert(alertHash);
3935  {
3936  LOCK(cs_vNodes);
3937  BOOST_FOREACH(CNode* pnode, vNodes)
3938  alert.RelayTo(pnode);
3939  }
3940  }
3941  else {
3942  // Small DoS penalty so peers that send us lots of
3943  // duplicate/expired/invalid-signature/whatever alerts
3944  // eventually get banned.
3945  // This isn't a Misbehaving(100) (immediate ban) because the
3946  // peer might be an older or different implementation with
3947  // a different signature key, etc.
3948  Misbehaving(pfrom->GetId(), 10);
3949  }
3950  }
3951  }
3952 
3953 
3954  else if (strCommand == "filterload")
3955  {
3956  CBloomFilter filter;
3957  vRecv >> filter;
3958 
3959  if (!filter.IsWithinSizeConstraints())
3960  // There is no excuse for sending a too-large filter
3961  Misbehaving(pfrom->GetId(), 100);
3962  else
3963  {
3964  LOCK(pfrom->cs_filter);
3965  delete pfrom->pfilter;
3966  pfrom->pfilter = new CBloomFilter(filter);
3967  pfrom->pfilter->UpdateEmptyFull();
3968  }
3969  pfrom->fRelayTxes = true;
3970  }
3971 
3972 
3973  else if (strCommand == "filteradd")
3974  {
3975  vector<unsigned char> vData;
3976  vRecv >> vData;
3977 
3978  // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
3979  // and thus, the maximum size any matched object can have) in a filteradd message
3980  if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE)
3981  {
3982  Misbehaving(pfrom->GetId(), 100);
3983  } else {
3984  LOCK(pfrom->cs_filter);
3985  if (pfrom->pfilter)
3986  pfrom->pfilter->insert(vData);
3987  else
3988  Misbehaving(pfrom->GetId(), 100);
3989  }
3990  }
3991 
3992 
3993  else if (strCommand == "filterclear")
3994  {
3995  LOCK(pfrom->cs_filter);
3996  delete pfrom->pfilter;
3997  pfrom->pfilter = new CBloomFilter();
3998  pfrom->fRelayTxes = true;
3999  }
4000 
4001 
4002  else if (strCommand == "reject")
4003  {
4004  if (fDebug) {
4005  try {
4006  string strMsg; unsigned char ccode; string strReason;
4007  vRecv >> LIMITED_STRING(strMsg, CMessageHeader::COMMAND_SIZE) >> ccode >> LIMITED_STRING(strReason, 111);
4008 
4009  ostringstream ss;
4010  ss << strMsg << " code " << itostr(ccode) << ": " << strReason;
4011 
4012  if (strMsg == "block" || strMsg == "tx")
4013  {
4014  uint256 hash;
4015  vRecv >> hash;
4016  ss << ": hash " << hash.ToString();
4017  }
4018  LogPrint("net", "Reject %s\n", SanitizeString(ss.str()));
4019  } catch (std::ios_base::failure& e) {
4020  // Avoid feedback loops by preventing reject messages from triggering a new reject message.
4021  LogPrint("net", "Unparseable reject message received\n");
4022  }
4023  }
4024  }
4025 
4026  else
4027  {
4028  // Ignore unknown commands for extensibility
4029  }
4030 
4031 
4032  // Update the last seen time for this node's address
4033  if (pfrom->fNetworkNode)
4034  if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
4036 
4037 
4038  return true;
4039 }
4040 
4041 // requires LOCK(cs_vRecvMsg)
4043 {
4044  //if (fDebug)
4045  // LogPrintf("ProcessMessages(%u messages)\n", pfrom->vRecvMsg.size());
4046 
4047  //
4048  // Message format
4049  // (4) message start
4050  // (12) command
4051  // (4) size
4052  // (4) checksum
4053  // (x) data
4054  //
4055  bool fOk = true;
4056 
4057  if (!pfrom->vRecvGetData.empty())
4058  ProcessGetData(pfrom);
4059 
4060  // this maintains the order of responses
4061  if (!pfrom->vRecvGetData.empty()) return fOk;
4062 
4063  std::deque<CNetMessage>::iterator it = pfrom->vRecvMsg.begin();
4064  while (!pfrom->fDisconnect && it != pfrom->vRecvMsg.end()) {
4065  // Don't bother if send buffer is too full to respond anyway
4066  if (pfrom->nSendSize >= SendBufferSize())
4067  break;
4068 
4069  // get next message
4070  CNetMessage& msg = *it;
4071 
4072  //if (fDebug)
4073  // LogPrintf("ProcessMessages(message %u msgsz, %u bytes, complete:%s)\n",
4074  // msg.hdr.nMessageSize, msg.vRecv.size(),
4075  // msg.complete() ? "Y" : "N");
4076 
4077  // end, if an incomplete message is found
4078  if (!msg.complete())
4079  break;
4080 
4081  // at this point, any failure means we can delete the current message
4082  it++;
4083 
4084  // Scan for message start
4085  if (memcmp(msg.hdr.pchMessageStart, Params().MessageStart(), MESSAGE_START_SIZE) != 0) {
4086  LogPrintf("\n\nPROCESSMESSAGE: INVALID MESSAGESTART\n\n");
4087  fOk = false;
4088  break;
4089  }
4090 
4091  // Read header
4092  CMessageHeader& hdr = msg.hdr;
4093  if (!hdr.IsValid())
4094  {
4095  LogPrintf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand());
4096  continue;
4097  }
4098  string strCommand = hdr.GetCommand();
4099 
4100  // Message size
4101  unsigned int nMessageSize = hdr.nMessageSize;
4102 
4103  // Checksum
4104  CDataStream& vRecv = msg.vRecv;
4105  uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
4106  unsigned int nChecksum = 0;
4107  memcpy(&nChecksum, &hash, sizeof(nChecksum));
4108  if (nChecksum != hdr.nChecksum)
4109  {
4110  LogPrintf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
4111  strCommand, nMessageSize, nChecksum, hdr.nChecksum);
4112  continue;
4113  }
4114 
4115  // Process message
4116  bool fRet = false;
4117  try
4118  {
4119  fRet = ProcessMessage(pfrom, strCommand, vRecv);
4120  boost::this_thread::interruption_point();
4121  }
4122  catch (std::ios_base::failure& e)
4123  {
4124  pfrom->PushMessage("reject", strCommand, REJECT_MALFORMED, string("error parsing message"));
4125  if (strstr(e.what(), "end of data"))
4126  {
4127  // Allow exceptions from under-length message on vRecv
4128  LogPrintf("ProcessMessages(%s, %u bytes) : Exception '%s' caught, normally caused by a message being shorter than its stated length\n", strCommand, nMessageSize, e.what());
4129  }
4130  else if (strstr(e.what(), "size too large"))
4131  {
4132  // Allow exceptions from over-long size
4133  LogPrintf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand, nMessageSize, e.what());
4134  }
4135  else
4136  {
4137  PrintExceptionContinue(&e, "ProcessMessages()");
4138  }
4139  }
4140  catch (boost::thread_interrupted) {
4141  throw;
4142  }
4143  catch (std::exception& e) {
4144  PrintExceptionContinue(&e, "ProcessMessages()");
4145  } catch (...) {
4146  PrintExceptionContinue(NULL, "ProcessMessages()");
4147  }
4148 
4149  if (!fRet)
4150  LogPrintf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand, nMessageSize);
4151 
4152  break;
4153  }
4154 
4155  // In case the connection got shut down, its receive buffer was wiped
4156  if (!pfrom->fDisconnect)
4157  pfrom->vRecvMsg.erase(pfrom->vRecvMsg.begin(), it);
4158 
4159  return fOk;
4160 }
4161 
4162 
4163 bool SendMessages(CNode* pto, bool fSendTrickle)
4164 {
4165  {
4166  // Don't send anything until we get their version message
4167  if (pto->nVersion == 0)
4168  return true;
4169 
4170  //
4171  // Message: ping
4172  //
4173  bool pingSend = false;
4174  if (pto->fPingQueued) {
4175  // RPC ping request by user
4176  pingSend = true;
4177  }
4178  if (pto->nPingNonceSent == 0 && pto->nPingUsecStart + PING_INTERVAL * 1000000 < GetTimeMicros()) {
4179  // Ping automatically sent as a latency probe & keepalive.
4180  pingSend = true;
4181  }
4182  if (pingSend) {
4183  uint64_t nonce = 0;
4184  while (nonce == 0) {
4185  RAND_bytes((unsigned char*)&nonce, sizeof(nonce));
4186  }
4187  pto->fPingQueued = false;
4188  pto->nPingUsecStart = GetTimeMicros();
4189  if (pto->nVersion > BIP0031_VERSION) {
4190  pto->nPingNonceSent = nonce;
4191  pto->PushMessage("ping", nonce);
4192  } else {
4193  // Peer is too old to support ping command with nonce, pong will never arrive.
4194  pto->nPingNonceSent = 0;
4195  pto->PushMessage("ping");
4196  }
4197  }
4198 
4199  TRY_LOCK(cs_main, lockMain); // Acquire cs_main for IsInitialBlockDownload() and CNodeState()
4200  if (!lockMain)
4201  return true;
4202 
4203  // Address refresh broadcast
4204  static int64_t nLastRebroadcast;
4205  if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
4206  {
4207  {
4208  LOCK(cs_vNodes);
4209  BOOST_FOREACH(CNode* pnode, vNodes)
4210  {
4211  // Periodically clear setAddrKnown to allow refresh broadcasts
4212  if (nLastRebroadcast)
4213  pnode->setAddrKnown.clear();
4214 
4215  // Rebroadcast our address
4216  if (!fNoListen)
4217  {
4218  CAddress addr = GetLocalAddress(&pnode->addr);
4219  if (addr.IsRoutable())
4220  pnode->PushAddress(addr);
4221  }
4222  }
4223  }
4224  nLastRebroadcast = GetTime();
4225  }
4226 
4227  //
4228  // Message: addr
4229  //
4230  if (fSendTrickle)
4231  {
4232  vector<CAddress> vAddr;
4233  vAddr.reserve(pto->vAddrToSend.size());
4234  BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
4235  {
4236  // returns true if wasn't already contained in the set
4237  if (pto->setAddrKnown.insert(addr).second)
4238  {
4239  vAddr.push_back(addr);
4240  // receiver rejects addr messages larger than 1000
4241  if (vAddr.size() >= 1000)
4242  {
4243  pto->PushMessage("addr", vAddr);
4244  vAddr.clear();
4245  }
4246  }
4247  }
4248  pto->vAddrToSend.clear();
4249  if (!vAddr.empty())
4250  pto->PushMessage("addr", vAddr);
4251  }
4252 
4253  CNodeState &state = *State(pto->GetId());
4254  if (state.fShouldBan) {
4255  if (pto->addr.IsLocal())
4256  LogPrintf("Warning: not banning local node %s!\n", pto->addr.ToString());
4257  else {
4258  pto->fDisconnect = true;
4259  CNode::Ban(pto->addr);
4260  }
4261  state.fShouldBan = false;
4262  }
4263 
4264  BOOST_FOREACH(const CBlockReject& reject, state.rejects)
4265  pto->PushMessage("reject", (string)"block", reject.chRejectCode, reject.strRejectReason, reject.hashBlock);
4266  state.rejects.clear();
4267 
4268  // Start block sync
4269  if (pto->fStartSync && !fImporting && !fReindex) {
4270  pto->fStartSync = false;
4271  PushGetBlocks(pto, chainActive.Tip(), uint256(0));
4272  }
4273 
4274  // Resend wallet transactions that haven't gotten in a block yet
4275  // Except during reindex, importing and IBD, when old wallet
4276  // transactions become unconfirmed and spams other nodes.
4278  {
4279  g_signals.Broadcast();
4280  }
4281 
4282  //
4283  // Message: inventory
4284  //
4285  vector<CInv> vInv;
4286  vector<CInv> vInvWait;
4287  {
4288  LOCK(pto->cs_inventory);
4289  vInv.reserve(pto->vInventoryToSend.size());
4290  vInvWait.reserve(pto->vInventoryToSend.size());
4291  BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
4292  {
4293  if (pto->setInventoryKnown.count(inv))
4294  continue;
4295 
4296  // trickle out tx inv to protect privacy
4297  if (inv.type == MSG_TX && !fSendTrickle)
4298  {
4299  // 1/4 of tx invs blast to all immediately
4300  static uint256 hashSalt;
4301  if (hashSalt == 0)
4302  hashSalt = GetRandHash();
4303  uint256 hashRand = inv.hash ^ hashSalt;
4304  hashRand = Hash(BEGIN(hashRand), END(hashRand));
4305  bool fTrickleWait = ((hashRand & 3) != 0);
4306 
4307  if (fTrickleWait)
4308  {
4309  vInvWait.push_back(inv);
4310  continue;
4311  }
4312  }
4313 
4314  // returns true if wasn't already contained in the set
4315  if (pto->setInventoryKnown.insert(inv).second)
4316  {
4317  vInv.push_back(inv);
4318  if (vInv.size() >= 1000)
4319  {
4320  pto->PushMessage("inv", vInv);
4321  vInv.clear();
4322  }
4323  }
4324  }
4325  pto->vInventoryToSend = vInvWait;
4326  }
4327  if (!vInv.empty())
4328  pto->PushMessage("inv", vInv);
4329 
4330 
4331  // Detect stalled peers. Require that blocks are in flight, we haven't
4332  // received a (requested) block in one minute, and that all blocks are
4333  // in flight for over two minutes, since we first had a chance to
4334  // process an incoming block.
4335  int64_t nNow = GetTimeMicros();
4336  if (!pto->fDisconnect && state.nBlocksInFlight &&
4337  state.nLastBlockReceive < state.nLastBlockProcess - BLOCK_DOWNLOAD_TIMEOUT*1000000 &&
4338  state.vBlocksInFlight.front().nTime < state.nLastBlockProcess - 2*BLOCK_DOWNLOAD_TIMEOUT*1000000) {
4339  LogPrintf("Peer %s is stalling block download, disconnecting\n", state.name.c_str());
4340  pto->fDisconnect = true;
4341  }
4342 
4343  //
4344  // Message: getdata (blocks)
4345  //
4346  vector<CInv> vGetData;
4347  while (!pto->fDisconnect && state.nBlocksToDownload && state.nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
4348  uint256 hash = state.vBlocksToDownload.front();
4349  vGetData.push_back(CInv(MSG_BLOCK, hash));
4350  MarkBlockAsInFlight(pto->GetId(), hash);
4351  LogPrint("net", "Requesting block %s from %s\n", hash.ToString().c_str(), state.name.c_str());
4352  if (vGetData.size() >= 1000)
4353  {
4354  pto->PushMessage("getdata", vGetData);
4355  vGetData.clear();
4356  }
4357  }
4358 
4359  //
4360  // Message: getdata (non-blocks)
4361  //
4362  while (!pto->fDisconnect && !pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
4363  {
4364  const CInv& inv = (*pto->mapAskFor.begin()).second;
4365  if (!AlreadyHave(inv))
4366  {
4367  if (fDebug)
4368  LogPrint("net", "sending getdata: %s\n", inv.ToString());
4369  vGetData.push_back(inv);
4370  if (vGetData.size() >= 1000)
4371  {
4372  pto->PushMessage("getdata", vGetData);
4373  vGetData.clear();
4374  }
4375  }
4376  pto->mapAskFor.erase(pto->mapAskFor.begin());
4377  }
4378  if (!vGetData.empty())
4379  pto->PushMessage("getdata", vGetData);
4380 
4381  }
4382  return true;
4383 }
4384 
4385 
4386 
4387 
4388 
4389 
4391 {
4392 public:
4395  // block headers
4396  std::map<uint256, CBlockIndex*>::iterator it1 = mapBlockIndex.begin();
4397  for (; it1 != mapBlockIndex.end(); it1++)
4398  delete (*it1).second;
4399  mapBlockIndex.clear();
4400 
4401  // orphan blocks
4402  std::map<uint256, COrphanBlock*>::iterator it2 = mapOrphanBlocks.begin();
4403  for (; it2 != mapOrphanBlocks.end(); it2++)
4404  delete (*it2).second;
4405  mapOrphanBlocks.clear();
4406 
4407  // orphan transactions
4408  mapOrphanTransactions.clear();
4410  }
const boost::filesystem::path & GetDataDir(bool fNetSpecific)
Definition: util.cpp:968
CClientUIInterface uiInterface
Definition: util.cpp:100
bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)
Definition: main.cpp:617
void PushMessage(const char *pszCommand)
Definition: net.h:579
uint64_t GetRand(uint64_t nMax)
Definition: util.cpp:186
bool IsDust(int64_t nMinRelayTxFee) const
Definition: core.h:153
bool CheckProofOfWork(uint256 hash, unsigned int nBits)
Check whether a block hash satisfies the proof-of-work requirement specified by nBits.
Definition: main2.cpp:243
int64_t GetValueOut() const
Definition: core.cpp:110
bool good() const
Definition: serialize.h:1315
void check(CCoinsViewCache *pcoins) const
Definition: txmempool.cpp:140
CDiskBlockPos GetBlockPos() const
Definition: main.h:784
void clear()
Definition: mruset.h:36
int nVersion
Definition: core.h:185
CBigNum GetBlockWork() const
Definition: main.h:825
void TraverseAndBuild(int height, unsigned int pos, const std::vector< uint256 > &vTxid, const std::vector< bool > &vMatch)
Definition: main.cpp:2584
bool fDisconnect
Definition: net.h:259
unsigned int nTxOffset
Definition: main.h:246
int nVersion
Definition: core.h:345
bool fLargeWorkInvalidChainFound
Definition: main.cpp:1263
CCriticalSection cs_filter
Definition: net.h:266
bool AreInputsStandard(const CTransaction &tx, CCoinsViewCache &mapInputs)
Check for standard transaction types.
Definition: main.cpp:646
void Add(std::vector< T > &vChecks)
Definition: checkqueue.h:184
bool AddOrphanTx(const CTransaction &tx, NodeId peer)
Definition: main.cpp:444
FILE * OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly)
Open a block file (blk?????.dat)
Definition: main.cpp:2729
std::string addrName
Definition: net.h:246
const_iterator begin() const
Definition: serialize.h:933
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
Definition: core.h:457
bool lookup(uint256 hash, CTransaction &result) const
Definition: txmempool.cpp:190
CScript scriptPubKey
Definition: core.h:125
virtual void SetBestChain(const CBlockLocator &locator)=0
CBlockIndex * pprev
Definition: main.h:705
int64_t GetBlockValue(int nHeight, int64_t nFees)
Definition: main2.cpp:14
const char * GetCommand() const
Definition: protocol.cpp:137
#define TRY_LOCK(cs, name)
Definition: sync.h:159
bool fImporting
Definition: main.cpp:47
Definition: init.h:14
int nMisbehavior
Definition: main.h:207
bool Flush()
Definition: coins.cpp:132
bool IsError() const
Definition: main.h:995
void SetBackend(CCoinsView &viewIn)
Definition: coins.cpp:69
void FileCommit(FILE *fileout)
Definition: util.cpp:1097
string strMiscWarning
Definition: util.cpp:96
void swap(CScriptCheck &check)
Definition: main.h:426
std::vector< CTxOut > vout
Definition: coins.h:76
unsigned int nTransactions
Definition: main.h:533
uint256 getuint256() const
Definition: bignum.h:231
Definition: core.h:394
bool fDebug
Definition: util.cpp:91
#define PAIRTYPE(t1, t2)
Definition: util.h:49
CAddress addr
Definition: net.h:245
uint64_t GetHash() const
Definition: netbase.cpp:1039
#define END(a)
Definition: util.h:43
#define strprintf
Definition: tinyformat.h:1011
bool ReadReindexing(bool &fReindex)
Definition: txdb.cpp:102
~CMainCleanup()
Definition: main.cpp:4394
An in-memory indexed chain of blocks.
Definition: main.h:1013
GetMinFee_mode
Definition: main.h:268
unsigned int ComputeMinWork(unsigned int nBase, int64_t nTime)
Calculate the minimum amount of work a received block needs, without knowing its direct parent...
Definition: main2.cpp:35
bool IsPayToScriptHash() const
Definition: script.cpp:1866
inv message data
Definition: protocol.h:128
bool ReadLastBlockFile(int &nFile)
Definition: txdb.cpp:107
int GetDepthInMainChainINTERNAL(CBlockIndex *&pindexRet) const
Definition: main.cpp:1023
std::map< COutPoint, CInPoint > mapNextTx
Definition: txmempool.h:64
bool TestNet()
Definition: chainparams.h:127
bool VerifyScript(const CScript &scriptSig, const CScript &scriptPubKey, const CTransaction &txTo, unsigned int nIn, unsigned int flags, int nHashType)
Definition: script.cpp:1608
std::pair< iterator, bool > insert(const key_type &x)
Definition: mruset.h:40
void AskFor(const CInv &inv)
Definition: net.h:482
virtual void Inventory(const uint256 &hash)=0
void StartShutdown()
Definition: init.cpp:103
bool CorruptionPossible() const
Definition: main.h:1005
void CheckForkWarningConditionsOnNewFork(CBlockIndex *pindexNewForkTip)
Definition: main.cpp:1312
int nHeight
Definition: coins.h:79
BloomFilter is a probabilistic filter which SPV clients provide so that we can filter the transaction...
Definition: bloom.h:43
bool IsKnownType() const
Definition: protocol.cpp:132
void ThreadScriptCheck()
Run an instance of the script checking thread.
Definition: main.cpp:1664
unsigned int GetSizeOfCompactSize(uint64_t nSize)
Definition: serialize.h:172
CCriticalSection cs_main
Definition: main.cpp:38
bool VerifyDB(int nCheckLevel, int nCheckDepth)
Verify consistency of the block and coin databases.
Definition: main.cpp:2812
string GetWarnings(string strFor)
Definition: main.cpp:3093
unsigned int nSize
Definition: main.h:626
uint256 hashLastGetBlocksEnd
Definition: net.h:283
CBlockIndex * GetLastCheckpoint(const std::map< uint256, CBlockIndex * > &mapBlockIndex)
uint256 GetHash() const
Definition: core.cpp:76
uint256 GetBestBlock()
Definition: coins.cpp:114
limitedmap< CInv, int64_t > mapAlreadyAskedFor(MAX_INV_SZ)
int64_t GetMinFee(const CTransaction &tx, unsigned int nBytes, bool fAllowFree, enum GetMinFee_mode mode)
Definition: main.cpp:847
bool AddToBlockIndex(CBlock &block, CValidationState &state, const CDiskBlockPos &pos)
Definition: main.cpp:2076
bool WriteBlockIndex(const CDiskBlockIndex &blockindex)
Definition: txdb.cpp:72
bool MoneyRange(int64_t nValue)
Definition: core.h:21
Double ended buffer combining vector and stream-like interfaces.
Definition: serialize.h:848
bool eof() const
Definition: serialize.h:1320
Data structure that represents a partial merkle tree.
Definition: main.h:529
int nSyncHeight
Definition: main.h:208
int nFile
Definition: main.h:711
CCriticalSection cs_inventory
Definition: net.h:296
RAII-style controller object for a CCheckQueue that guarantees the passed queue is finished before co...
Definition: checkqueue.h:17
bool SeenLocal(const CService &addr)
vote for a local address
Definition: net.cpp:282
std::vector< CAddress > vAddrToSend
Definition: net.h:288
pruned version of CTransaction: only retains metadata and unspent transaction outputs ...
Definition: coins.h:69
unsigned int GetSerializeSize(const T &obj)
Definition: serialize.h:1236
bool fReindex
Definition: main.cpp:48
bool Add(const CAddress &addr, const CNetAddr &source, int64_t nTimePenalty=0)
Definition: addrman.h:414
void AddAddressKnown(const CAddress &addr)
Definition: net.h:450
unsigned int n
Definition: core.h:28
std::string cleanSubVer
Definition: net.h:253
void CheckForkWarningConditions()
Definition: main.cpp:1266
bool LoadBlockIndexGuts()
Definition: txdb.cpp:185
std::string DateTimeStrFormat(const char *pszFormat, int64_t nTime)
Definition: util.cpp:1411
void RandAddSeedPerfmon()
Definition: util.cpp:159
std::string strStatusBar
Definition: alert.h:47
static int64_t nMinTxFee
Fees smaller than this (in satoshi) are considered zero fee (for transaction creation) ...
Definition: core.h:182
CAddrMan addrman
Definition: net.cpp:61
virtual void SyncTransaction(const uint256 &hash, const CTransaction &tx, const CBlock *pblock)=0
int64_t nPingUsecStart
Definition: net.h:303
void SetRecvVersion(int nVersionIn)
Definition: net.h:430
uint256 nChainWork
Definition: main.h:720
void RenameThread(const char *name)
Definition: util.cpp:1368
bool IsLocal() const
Definition: netbase.cpp:792
const string strMessageMagic
Definition: main.cpp:77
CChain chainActive
The currently-connected chain of blocks.
Definition: main.cpp:43
#define FLATDATA(obj)
Definition: serialize.h:318
Undo information for a CTxIn.
Definition: core.h:283
unsigned int nChainTx
Definition: main.h:727
size_type count(const key_type &k) const
Definition: mruset.h:35
void PushInventory(const CInv &inv)
Definition: net.h:473
bool GetCoins(const uint256 &txid, CCoins &coins)
Definition: coins.cpp:75
bool fBenchmark
Definition: main.cpp:49
void PrintBlockTree()
Print the loaded block tree.
Definition: main.cpp:2938
unsigned int nUndoSize
Definition: main.h:627
void insert(const uint256 &hash)
Definition: bloom.cpp:41
bool IsAvailable(unsigned int nPos) const
Definition: coins.h:229
std::deque< CInv > vRecvGetData
Definition: net.h:236
vector< CNode * > vNodes
Definition: net.cpp:74
unsigned int nChecksum
Definition: protocol.h:65
int ScriptSigArgsExpected(txnouttype t, const std::vector< std::vector< unsigned char > > &vSolutions)
Definition: script.cpp:1384
Definition: txmempool.h:21
CDataStream vRecv
Definition: net.h:191
bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
Definition: main.cpp:2188
bool Invalid(bool ret=false, unsigned char _chRejectCode=0, std::string _strRejectReason="")
Definition: main.h:975
std::set< uint256 > setKnown
Definition: net.h:291
uint256 BuildMerkleTree() const
Definition: core.cpp:228
int GetDepthInMainChain() const
Definition: main.h:485
CTransaction tx
Definition: main.cpp:67
FILE * OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
Definition: main.cpp:2706
void UpdateTime(CBlockHeader &block, const CBlockIndex *pindexPrev)
Definition: main.cpp:1404
bool VerifySignature(const CCoins &txFrom, const CTransaction &txTo, unsigned int nIn, unsigned int flags, int nHashType)
Verify a signature.
Definition: main.cpp:1449
CBlockLocator GetLocator(const CBlockIndex *pindex=NULL) const
Return a CBlockLocator that refers to a block in this chain (by default the tip). ...
Definition: main.cpp:395
#define CLIENT_VERSION_IS_RELEASE
Definition: clientversion.h:30
bool AcceptToMemoryPool(CTxMemPool &pool, CValidationState &state, const CTransaction &tx, bool fLimitFree, bool *pfMissingInputs, bool fRejectInsaneFee)
(try to) add transaction to memory pool
Definition: main.cpp:878
uint256 GetPoWHash() const
Definition: core.cpp:221
#define AssertLockHeld(cs)
Definition: sync.h:98
std::vector< CAddress > GetAddr()
Definition: addrman.h:481
bool SetLimit(uint64_t nPos=(uint64_t)(-1))
Definition: serialize.h:1381
uint64_t GetPos()
Definition: serialize.h:1348
class CMainCleanup instance_of_cmaincleanup
bool operator()() const
Definition: main.cpp:1442
int nCommonHeight
Definition: main.h:209
int GetBlocksToMaturity() const
Definition: main.cpp:1059
int nScriptCheckThreads
Definition: main.cpp:46
std::vector< uint256 > GetMerkleBranch(int nIndex) const
Definition: core.cpp:247
CBigNum & SetCompact(unsigned int nCompact)
Definition: bignum.h:295
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or NULL if none.
Definition: main.h:1024
#define LOCK2(cs1, cs2)
Definition: sync.h:158
std::deque< CNetMessage > vRecvMsg
Definition: net.h:237
uint64_t nLocalHostNonce
Definition: net.cpp:59
std::vector< uint256 > vHash
Definition: main.h:539
int nStartingHeight
Definition: net.h:284
int Height() const
Return the maximal height in the chain.
Definition: main.h:1055
bool fClient
Definition: net.h:255
std::string strSubVer
Definition: net.h:253
Used to relay blocks as header + vector to filtered nodes.
Definition: main.h:1096
CBlockTreeDB * pblocktree
Global variable that points to the active block tree (protected by cs_main)
Definition: main.cpp:437
unsigned int nTime
Definition: main.h:735
unsigned int CalcTreeWidth(int height)
Definition: main.h:545
bool TruncateFile(FILE *file, unsigned int length)
Definition: util.cpp:1114
uint256 hashPrev
Definition: main.cpp:60
bool fNoListen
Definition: util.cpp:97
bool GetBoolArg(const std::string &strArg, bool fDefault)
Return boolean argument or default value.
Definition: util.cpp:520
bool fLargeWorkForkFound
Definition: main.cpp:1262
#define LogPrintf(...)
Definition: util.h:118
bool fPingQueued
Definition: net.h:307
int64_t GetAdjustedTime()
Definition: util.cpp:1241
unsigned int nStatus
Definition: main.h:730
double getdouble() const
Definition: uint256.h:59
CBlockIndex * Next(const CBlockIndex *pindex) const
Find the successor of a block in this chain, or NULL if the given index is not found or is the tip...
Definition: main.h:1047
unsigned int nLockTime
Definition: core.h:188
void AddTimeData(const CNetAddr &ip, int64_t nTime)
Definition: util.cpp:1246
void EraseOrphansFor(NodeId peer)
Definition: main.cpp:491
Access to the block database (blocks/index/)
Definition: txdb.h:47
CScript COINBASE_FLAGS
Definition: main.cpp:75
CBlockHeader GetBlockHeader() const
Definition: main.h:802
int nVersion
Definition: coins.h:83
uint256 hashMerkleRoot
Definition: core.h:347
string SanitizeString(const string &str)
Definition: util.cpp:380
unsigned int GetSerializeSize(char a, int, int=0)
Definition: serialize.h:114
Abstract view on the open txout dataset.
Definition: coins.h:259
void PushGetBlocks(CNode *pnode, CBlockIndex *pindexBegin, uint256 hashEnd)
Definition: main.cpp:2419
bool fInbound
Definition: net.h:256
bool HaveCoins(const uint256 &txid)
Definition: coins.cpp:110
unsigned int nDataPos
Definition: main.h:714
int64_t GetBlockTime() const
Definition: core.h:387
bool IsInitialBlockDownload()
Check whether we are doing an initial block download (synchronizing from disk or network) ...
Definition: main.cpp:1246
bool fOneShot
Definition: net.h:254
An input of a transaction.
Definition: core.h:72
An alert is a combination of a serialized CUnsignedAlert and a signature.
Definition: alert.h:76
std::string itostr(int n)
Definition: util.h:212
bool fCoinBase
Definition: core.h:287
void AddressCurrentlyConnected(const CService &addr)
Definition: net.cpp:417
mruset< CAddress > setAddrKnown
Definition: net.h:289
#define MESSAGE_START_SIZE
Definition: chainparams.h:25
unsigned int GetSigOpCount(bool fAccurate) const
Definition: script.cpp:1818
CMainCleanup()
Definition: main.cpp:4393
bool HaveInputs(const CTransaction &tx)
Definition: coins.cpp:162
#define LOCK(cs)
Definition: sync.h:157
bool AcceptBlock(CBlock &block, CValidationState &state, CDiskBlockPos *dbp)
Definition: main.cpp:2295
std::vector< CTxOut > vout
Definition: core.h:187
size_type size() const
Definition: serialize.h:937
txnouttype
Definition: script.h:207
void UnloadBlockIndex()
Unload database information.
Definition: main.cpp:2886
int type
Definition: protocol.h:150
void RegisterNodeSignals(CNodeSignals &nodeSignals)
Register with a network node to receive its signals.
Definition: main.cpp:359
bool fTxIndex
Definition: main.cpp:50
bool SendMessages(CNode *pto, bool fSendTrickle)
Send queued protocol messages to be sent to a give node.
Definition: main.cpp:4163
CBlockHeader GetBlockHeader() const
Definition: core.h:427
CBlockIndex * pindexLastGetBlocksBegin
Definition: net.h:282
std::vector< CTxIn > vin
Definition: core.h:186
NodeId fromPeer
Definition: main.cpp:68
uint256 hashPrevBlock
Definition: core.h:346
bool ActivateBestChain(CValidationState &state)
Find the best known block, and make it the tip of the block chain.
Definition: main.cpp:2028
CMessageHeader hdr
Definition: net.h:188
bool IsPushOnly() const
Definition: script.cpp:1875
bool DoS(int level, bool ret=false, unsigned char chRejectCodeIn=0, std::string strRejectReasonIn="", bool corruptionIn=false)
Definition: main.h:963
int64_t GetMedianTime() const
Definition: main.cpp:2406
C++ wrapper for BIGNUM (OpenSSL bignum)
Definition: bignum.h:57
mruset< CInv > setInventoryKnown
Definition: net.h:294
void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length)
Definition: util.cpp:1145
A CService with information about it as peer.
Definition: protocol.h:91
unsigned int SendBufferSize()
Definition: net.h:55
unsigned int nBits
Definition: main.h:736
bool IsNull()
Definition: core.h:480
bool LoadBlockIndex()
Load the block tree and coins database from disk.
Definition: main.cpp:2894
uint256 hash
Definition: protocol.h:151
bool AcceptToMemoryPool(bool fLimitFree=true)
Definition: main.cpp:1067
const CTxOut & GetOutputFor(const CTxIn &input)
Definition: coins.cpp:143
uint256 hashMerkleRoot
Definition: main.h:734
void RelayTransaction(const CTransaction &tx, const uint256 &hash)
Definition: net.cpp:2106
bool Solver(const CScript &scriptPubKey, txnouttype &typeRet, vector< vector< unsigned char > > &vSolutionsRet)
Definition: script.cpp:1187
bool fSuccessfullyConnected
Definition: net.h:258
map< uint256, CAlert > mapAlerts
Definition: alert.cpp:25
std::map< uint256, CTxMemPoolEntry > mapTx
Definition: txmempool.h:63
bool WriteBlockFileInfo(int nFile, const CBlockFileInfo &fileinfo)
Definition: txdb.cpp:83
bool Error(std::string strRejectReasonIn="")
Definition: main.h:979
std::string ToString() const
Definition: netbase.cpp:1325
CTxOut txout
Definition: core.h:286
void UpdateCoins(const CTransaction &tx, CValidationState &state, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight, const uint256 &txhash)
Definition: main.cpp:1423
std::vector< uint256 > vMerkleTree
Definition: core.h:401
CCriticalSection cs_mapAlerts
Definition: alert.cpp:26
uint256 TraverseAndExtract(int height, unsigned int pos, unsigned int &nBitsUsed, unsigned int &nHashUsed, std::vector< uint256 > &vMatch)
Definition: main.cpp:2602
int GetTotalBlocksEstimate()
void PrintExceptionContinue(std::exception *pex, const char *pszThread)
Definition: util.cpp:928
uint256 Hash(const T1 pbegin, const T1 pend)
Definition: hash.h:20
An output of a transaction.
Definition: core.h:121
Used to marshal pointers into hashes for db storage.
Definition: main.h:883
bool fGetAddr
Definition: net.h:290
std::string GetCommand() const
Definition: protocol.cpp:41
int64_t GetTimeMillis()
Definition: util.h:304
bool WriteBlockToDisk(CBlock &block, CDiskBlockPos &pos)
Functions for disk access for blocks.
Definition: main.cpp:1145
std::vector< uint256 > vHave
Definition: core.h:459
int64_t GetTimeMicros()
Definition: util.h:310
bool ConnectBlock(CBlock &block, CValidationState &state, CBlockIndex *pindex, CCoinsViewCache &view, bool fJustCheck)
Definition: main.cpp:1669
bool EvalScript(vector< vector< unsigned char > > &stack, const CScript &script, const CTransaction &txTo, unsigned int nIn, unsigned int flags, int nHashType)
Definition: script.cpp:298
unsigned int nHeight
Definition: core.h:288
bool CheckBlock(int nHeight, const uint256 &hash)
Definition: checkpoints.cpp:94
bool WriteLastBlockFile(int nFile)
Definition: txdb.cpp:91
bool SetPos(uint64_t nPos)
Definition: serialize.h:1353
Queue for verifications that have to be performed.
Definition: checkqueue.h:28
bool IsNull() const
Definition: main.h:241
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: core.h:24
CCoinsViewCache * pcoinsTip
Global variable that points to the active CCoinsView (protected by cs_main)
Definition: main.cpp:436
void AddTransactionsUpdated(unsigned int n)
Definition: txmempool.cpp:66
std::vector< CTxInUndo > vprevout
Definition: core.h:325
bool Abort(const std::string &msg)
Definition: main.h:985
std::string GetHex() const
Definition: uint256.h:298
boost::signals2::signal< bool(CNode *, bool)> SendMessages
Definition: net.h:82
double GuessVerificationProgress(CBlockIndex *pindex, bool fSigchecks)
int64_t GetTime()
Definition: util.cpp:1220
bool IsRoutable() const
Definition: netbase.cpp:855
size_t nSendSize
Definition: net.h:230
void RegisterWallet(CWalletInterface *pwalletIn)
Register a wallet to receive updates from core.
Definition: main.cpp:156
bool DisconnectBlock(CBlock &block, CValidationState &state, CBlockIndex *pindex, CCoinsViewCache &view, bool *pfClean)
Functions for validating blocks and updating the block tree.
Definition: main.cpp:1543
map< uint256, COrphanTx > mapOrphanTransactions
Definition: main.cpp:70
bool ProcessMessages(CNode *pfrom)
Process protocol messages received from a given node.
Definition: main.cpp:4042
void PushVersion()
Definition: net.cpp:542
void remove(const CTransaction &tx, std::list< CTransaction > &removed, bool fRecursive=false)
Definition: txmempool.cpp:90
bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats)
Get statistics from node state.
Definition: main.cpp:344
CCriticalSection cs
Definition: txmempool.h:62
CTxMemPool mempool
Definition: main.cpp:40
unsigned int nPos
Definition: main.h:216
bool ReadFlag(const std::string &name, bool &fValue)
Definition: txdb.cpp:177
static const int CURRENT_VERSION
Definition: core.h:344
virtual const CBlock & GenesisBlock() const =0
boost::signals2::signal< bool(CNode *)> ProcessMessages
Definition: net.h:81
bool ReadBlockFileInfo(int nFile, CBlockFileInfo &fileinfo)
Definition: txdb.cpp:87
CBlockIndex * InsertBlockIndex(uint256 hash)
Create a new block index entry for a given block hash.
Definition: main.cpp:2737
bool ReadTxIndex(const uint256 &txid, CDiskTxPos &pos)
Definition: txdb.cpp:162
Closure representing one script verification Note that this stores references to the spending transac...
Definition: main.h:409
bool IsInvalid() const
Definition: main.h:992
bool fStartSync
Definition: net.h:285
void removeConflicts(const CTransaction &tx, std::list< CTransaction > &removed)
Definition: txmempool.cpp:115
int nVersion
Definition: main.h:733
std::vector< bool > vBits
Definition: main.h:536
const uint256 & GetTxHash(unsigned int nIndex) const
Definition: core.h:441
std::string GetRejectReason() const
Definition: main.h:1009
unsigned char GetRejectCode() const
Definition: main.h:1008
unsigned int nUndoPos
Definition: main.h:717
CScript scriptSig
Definition: core.h:76
bool IsStandardTx(const CTransaction &tx, string &reason)
Definition: main.cpp:530
CChain chainMostWork
The currently best known chain of headers (some of which may be invalid).
Definition: main.cpp:44
boost::signals2::signal< int()> GetHeight
Definition: net.h:80
unsigned int GetP2SHSigOpCount(const CTransaction &tx, CCoinsViewCache &inputs)
Count ECDSA signature operations in pay-to-script-hash inputs.
Definition: main.cpp:714
IMPLEMENT_SERIALIZE(READWRITE(FLATDATA(pchMessageStart));READWRITE(FLATDATA(pchCommand));READWRITE(nMessageSize);READWRITE(nChecksum);) public char pchMessageStart[MESSAGE_START_SIZE]
Definition: protocol.h:44
bool fCoinBase
Definition: coins.h:73
CBlockIndex * Genesis() const
Returns the index entry for the genesis block of this chain, or NULL if none.
Definition: main.h:1019
IP address (IPv6, or IPv4 using mapped IPv6 range (::FFFF:0:0/96))
Definition: netbase.h:45
#define BEGIN(a)
Definition: util.h:42
int size()
Definition: addrman.h:395
CService addrLocal
Definition: net.h:247
Capture information about block/transaction validation.
Definition: main.h:950
256-bit unsigned integer
Definition: uint256.h:532
void AddInventoryKnown(const CInv &inv)
Definition: net.h:465
unsigned int nTime
Definition: protocol.h:121
bool CheckBlock(const CBlock &block, CValidationState &state, bool fCheckPOW, bool fCheckMerkleRoot)
Definition: main.cpp:2229
bool IsReachable(enum Network net)
check whether a given network is one we can probably connect to
Definition: net.cpp:304
uint256 ExtractMatches(std::vector< uint256 > &vMatch)
Definition: main.cpp:2648
void SyncWithWallets(const uint256 &hash, const CTransaction &tx, const CBlock *pblock)
Push an updated transaction to all registered wallets.
Definition: main.cpp:183
unsigned int nTime
Definition: core.h:348
int64_t nTimeBestReceived
Definition: main.cpp:45
CCriticalSection cs_mapRelay
Definition: net.cpp:78
bool ReadBlockFromDisk(CBlock &block, const CDiskBlockPos &pos)
Definition: main.cpp:1171
uint256 GetHash() const
Definition: core.cpp:216
bool Spend(const COutPoint &out, CTxInUndo &undo)
Definition: coins.cpp:31
CBlockIndex * pindexBestForkBase
Definition: main.cpp:1264
double GetPriority(const CTransaction &tx, int nHeight)
Definition: coins.cpp:183
bool IsRelevantAndUpdate(const CTransaction &tx, const uint256 &hash)
Definition: bloom.cpp:103
bool ProcessBlock(CValidationState &state, CNode *pfrom, CBlock *pblock, CDiskBlockPos *dbp)
Process an incoming block.
Definition: main.cpp:2431
void FindByte(char ch)
Definition: serialize.h:1396
unsigned int GetLegacySigOpCount(const CTransaction &tx)
Count ECDSA signature operations the old-fashioned (pre-0.6) way.
Definition: main.cpp:700
The block chain is a tree shaped structure starting with the genesis block at the root...
Definition: main.h:698
const CChainParams & Params()
Return the currently selected parameters.
bool CheckInputs(const CTransaction &tx, CValidationState &state, CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, std::vector< CScriptCheck > *pvChecks)
Definition: main.cpp:1454
Undo information for a CBlock.
Definition: main.h:337
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:413
std::vector< CInv > vInventoryToSend
Definition: net.h:295
uint64_t nServices
Definition: net.h:227
bool addUnchecked(const uint256 &hash, const CTxMemPoolEntry &entry)
Definition: txmempool.cpp:73
uint256 hashContinue
Definition: net.h:281
Undo information for a CTransaction.
Definition: core.h:321
void * memcpy(void *a, const void *b, size_t c)
unsigned int nCoinCacheSize
Definition: main.cpp:51
std::string ToString() const
Definition: uint256.h:341
bool IsPruned() const
Definition: coins.h:235
CBlockIndex * FindFork(const CBlockLocator &locator) const
Find the last common block between this chain and a locator.
Definition: main.cpp:422
unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
Definition: main.cpp:508
int NodeId
Definition: net.h:75
std::string _(const char *psz)
Translation function: Call Translate signal on UI interface, which returns a boost::optional result...
Definition: ui_interface.h:125
void Misbehaving(NodeId pnode, int howmuch)
Increase a node's misbehavior score.
Definition: main.cpp:1346
NodeId GetId() const
Definition: net.h:407
boost::signals2::signal< void()> NotifyBlocksChanged
Block chain changed.
Definition: ui_interface.h:90
unsigned int nMessageSize
Definition: protocol.h:64
bool exists(uint256 hash)
Definition: txmempool.h:92
bool AbortNode(const std::string &strMessage)
Abort with a message.
Definition: main.cpp:2687
#define LIMITED_STRING(obj, n)
Definition: serialize.h:320
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
Definition: main.h:1042
static uint256 CheckMerkleBranch(uint256 hash, const std::vector< uint256 > &vMerkleBranch, int nIndex)
Definition: core.cpp:263
CBlockIndex * SetTip(CBlockIndex *pindex)
Set/initialize a chain with a given tip.
Definition: main.cpp:382
void UnregisterAllWallets()
Unregister all wallets from core.
Definition: main.cpp:174
bool WriteTxIndex(const std::vector< std::pair< uint256, CDiskTxPos > > &list)
Definition: txdb.cpp:166
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:1075
CMerkleBlock(const CBlock &block, CBloomFilter &filter)
Definition: main.cpp:2534
CAddress GetLocalAddress(const CNetAddr *paddrPeer)
Definition: net.cpp:136
static bool Ban(const CNetAddr &ip)
Definition: net.cpp:584
bool IsCoinBase() const
Definition: coins.h:132
bool IsStandard(const CScript &scriptPubKey, txnouttype &whichType)
Definition: script.cpp:1405
int64_t GetValueIn(const CTransaction &tx)
Amount of anoncoins coming in to a transaction Note that lightweight clients may not know anything be...
Definition: coins.cpp:150
bool fRelayTxes
Definition: net.h:264
int in_avail()
Definition: serialize.h:1045
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:81
static int64_t nMinRelayTxFee
Fees smaller than this (in satoshi) are considered zero fee (for relaying and mining) ...
Definition: core.h:183
virtual void UpdatedTransaction(const uint256 &hash)=0
bool IsCoinBase() const
Definition: core.h:228
virtual void EraseFromWallet(const uint256 &hash)=0
void UpdateEmptyFull()
Definition: bloom.cpp:172
bool WriteFlag(const std::string &name, bool fValue)
Definition: txdb.cpp:173
void UnregisterWallet(CWalletInterface *pwalletIn)
Unregister a wallet from core.
Definition: main.cpp:165
bool SetCoins(const uint256 &txid, const CCoins &coins)
Definition: coins.cpp:105
bool IsNull() const
Definition: core.h:34
int nVersion
Definition: core.h:289
int nVersion
Definition: net.h:248
CBlockIndex * pindexBestForkTip
Definition: main.cpp:1264
bool complete() const
Definition: net.h:201
std::vector< CTransaction > vtx
Definition: core.h:398
std::string GetArg(const std::string &strArg, const std::string &strDefault)
Return string argument or default value.
Definition: util.cpp:506
uint32_t nSequenceId
Definition: main.h:740
uint64_t nPingNonceSent
Definition: net.h:301
int64_t nPingUsecTime
Definition: net.h:305
bool SetBestBlock(const uint256 &hashBlock)
Definition: coins.cpp:120
unsigned int GetCacheSize()
Definition: coins.cpp:139
std::string ToString() const
Definition: netbase.cpp:908
CBloomFilter * pfilter
Definition: net.h:267
CDiskBlockPos GetUndoPos() const
Definition: main.h:793
vector< unsigned char > vchBlock
Definition: main.cpp:61
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: core.h:179
int nHeight
Definition: main.h:708
bool fNetworkNode
Definition: net.h:257
bool LoadExternalBlockFile(FILE *fileIn, CDiskBlockPos *dbp)
Import blocks from an external file.
Definition: main.cpp:3007
Information about a peer.
Definition: net.h:223
static const int CURRENT_VERSION
Definition: core.h:184
std::vector< int > vHeightInFlight
Definition: main.h:210
bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown=false)
Definition: main.cpp:2134
FILE * OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly)
Open an undo file (rev?????.dat)
Definition: main.cpp:2733
boost::signals2::signal< void(NodeId)> FinalizeNode
Definition: net.h:84
uint256 GetRandHash()
Definition: util.cpp:206
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:309
unsigned int nBits
Definition: core.h:349
bool CheckDiskSpace(uint64_t nAdditionalBytes)
Check whether enough disk space is available for an incoming block.
Definition: main.cpp:2695
virtual void ResendWalletTransactions()=0
std::string ToString() const
Definition: protocol.cpp:144
Wrapper around a FILE* that implements a ring buffer to deserialize from.
Definition: serialize.h:1266
int64_t GetBlockTime() const
Definition: main.h:820
void SetVersion(int n)
Definition: serialize.h:1049
bool InitBlockIndex()
Initialize a new block tree database + block data on disk.
Definition: main.cpp:2903
bool AppliesToMe() const
Definition: alert.cpp:125
std::vector< CTxUndo > vtxundo
Definition: main.h:340
int nFile
Definition: main.h:215
COutPoint prevout
Definition: core.h:75
multimap< uint256, COrphanBlock * > mapOrphanBlocksByPrev
Definition: main.cpp:64
bool Seek(uint64_t nPos)
Definition: serialize.h:1366
map< uint256, COrphanBlock * > mapOrphanBlocks
Definition: main.cpp:63
bool HasCanonicalPushes() const
Definition: script.cpp:1893
boost::signals2::signal< void(NodeId, const CNode *)> InitializeNode
Definition: net.h:83
int64_t GetMedianTimePast() const
Definition: main.h:843
CCoinsView that brings transactions from a memorypool into view.
Definition: txmempool.h:103
map< uint256, CBlockIndex * > mapBlockIndex
Definition: main.cpp:42
std::multimap< int64_t, CInv > mapAskFor
Definition: net.h:297
unsigned int GetNextWorkRequired(const CBlockIndex *pindexLast, const CBlockHeader *pblock)
Definition: main2.cpp:232
CCriticalSection cs_vNodes
Definition: net.cpp:75
map< uint256, set< uint256 > > mapOrphanTransactionsByPrev
Definition: main.cpp:71
unsigned int nTx
Definition: main.h:724
bool CheckTransaction(const CTransaction &tx, CValidationState &state)
Definition: main.cpp:783
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: core.h:340
Definition: main.h:271
const uint256 & HashGenesisBlock() const
Definition: chainparams.h:76
RAII wrapper for FILE*.
Definition: serialize.h:1154
map< string, string > mapArgs
Definition: util.cpp:89
bool IsValid() const
Definition: protocol.cpp:49
map< CInv, CDataStream > mapRelay
Definition: net.cpp:76
int atoi(const std::string &str)
Definition: util.h:235
bool empty() const
Definition: serialize.h:938
uint256 GetBlockHash() const
Definition: main.h:815
int64_t nValue
Definition: core.h:124
const_iterator end() const
Definition: serialize.h:935
void runCommand(std::string strCommand)
Definition: util.cpp:1361
void UnregisterNodeSignals(CNodeSignals &nodeSignals)
Unregister a network node.
Definition: main.cpp:368
uint256 hashBlock
Definition: main.cpp:59
uint256 CalcHash(int height, unsigned int pos, const std::vector< uint256 > &vTxid)
Definition: main.cpp:2567
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:2394
void PushAddress(const CAddress &addr)
Definition: net.h:455
CDataStream ssSend
Definition: net.h:229
Message header.
Definition: protocol.h:34
void Good(const CService &addr, int64_t nTime=GetAdjustedTime())
Definition: addrman.h:445
uint256 hash
Definition: core.h:27
bool WriteBestInvalidWork(const CBigNum &bnBestInvalidWork)
Definition: txdb.cpp:77
const uint256 * phashBlock
Definition: main.h:702
int nPriority
Definition: alert.h:43