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