]> Git Repo - VerusCoin.git/blame - src/main.cpp
Remove unnecessary IsCoinbase() check. Coinbases are guaranteed to have empty vjoinsplit.
[VerusCoin.git] / src / main.cpp
CommitLineData
0a61b0df 1// Copyright (c) 2009-2010 Satoshi Nakamoto
f914f1a7 2// Copyright (c) 2009-2014 The Bitcoin Core developers
c5b390b6 3// Distributed under the MIT software license, see the accompanying
3a25a2b9
F
4// file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
51ed9ec9 6#include "main.h"
319b1160 7
320f2cc7
SB
8#include "sodium.h"
9
51ed9ec9 10#include "addrman.h"
f35c6c4f 11#include "alert.h"
26c16d9d 12#include "arith_uint256.h"
319b1160 13#include "chainparams.h"
eb5fff9e 14#include "checkpoints.h"
319b1160 15#include "checkqueue.h"
9e851450 16#include "consensus/upgrades.h"
da29ecbc 17#include "consensus/validation.h"
5b3bc971 18#include "deprecation.h"
edd309e5 19#include "init.h"
afd4b94b 20#include "merkleblock.h"
a6df7ab5 21#include "metrics.h"
319b1160 22#include "net.h"
df852d2b 23#include "pow.h"
319b1160
GA
24#include "txdb.h"
25#include "txmempool.h"
ed6d0b5f 26#include "ui_interface.h"
937ba572 27#include "undo.h"
51ed9ec9 28#include "util.h"
217a5c92 29#include "utilmoneystr.h"
26c16d9d 30#include "validationinterface.h"
9ddb6ad0 31#include "wallet/asyncrpcoperation_sendmany.h"
06c19063 32#include "wallet/asyncrpcoperation_shieldcoinbase.h"
51ed9ec9 33
fa70084c 34#include <algorithm>
358ce266 35#include <sstream>
51ed9ec9
BD
36
37#include <boost/algorithm/string/replace.hpp>
38#include <boost/filesystem.hpp>
39#include <boost/filesystem/fstream.hpp>
36cba8f1 40#include <boost/math/distributions/poisson.hpp>
ad49c256 41#include <boost/thread.hpp>
7c68cc07 42#include <boost/static_assert.hpp>
0a61b0df 43
4dc5eb05 44using namespace std;
0a61b0df 45
9b59e3bd 46#if defined(NDEBUG)
7662d72b 47# error "Zcash cannot be compiled without assertions."
9b59e3bd
GM
48#endif
49
c5b390b6
MF
50/**
51 * Global state
52 */
0a61b0df 53
54CCriticalSection cs_main;
55
145d5be8 56BlockMap mapBlockIndex;
4c6d41b8 57CChain chainActive;
ad6e6017 58CBlockIndex *pindexBestHeader = NULL;
39d2e9e0 59static int64_t nTimeBestReceived = 0;
ff6a7af1
LD
60CWaitableCriticalSection csBestBlock;
61CConditionVariable cvBlockChange;
f9cae832 62int nScriptCheckThreads = 0;
1f015f6a 63bool fExperimentalMode = false;
66b02c93 64bool fImporting = false;
7fea4846 65bool fReindex = false;
2d1fa42e 66bool fTxIndex = false;
f9ec3f0f 67bool fHavePruned = false;
68bool fPruneMode = false;
3da434a2 69bool fIsBareMultisigStd = true;
3fcfbc8a 70bool fCheckBlockIndex = false;
a8cdaf5c 71bool fCheckpointsEnabled = true;
d212ba32 72bool fCoinbaseEnforcedProtectionEnabled = true;
fc684ad8 73size_t nCoinCacheUsage = 5000 * 300;
f9ec3f0f 74uint64_t nPruneTarget = 0;
4d9c7fe6 75bool fAlerts = DEFAULT_ALERTS;
0a61b0df 76
9bb37bf0
JG
77unsigned int expiryDelta = DEFAULT_TX_EXPIRY_DELTA;
78
037b4f14 79/** Fees smaller than this (in satoshi) are considered zero fee (for relaying and mining) */
ba0625f2 80CFeeRate minRelayTxFee = CFeeRate(DEFAULT_MIN_RELAY_TX_FEE);
13fc83c7
GA
81
82CTxMemPool mempool(::minRelayTxFee);
000dc551 83
c74332c6
GA
84struct COrphanTx {
85 CTransaction tx;
86 NodeId fromPeer;
87};
72b25b0f
CF
88map<uint256, COrphanTx> mapOrphanTransactions GUARDED_BY(cs_main);;
89map<uint256, set<uint256> > mapOrphanTransactionsByPrev GUARDED_BY(cs_main);;
90void EraseOrphansFor(NodeId peer) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
0a61b0df 91
9dcd524f
PW
92/**
93 * Returns true if there are nRequired or more blocks of minVersion or above
51aa2492 94 * in the last Consensus::Params::nMajorityWindow blocks, starting at pstart and going backwards.
9dcd524f 95 */
51aa2492 96static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned nRequired, const Consensus::Params& consensusParams);
3fcfbc8a 97static void CheckBlockIndex();
9dcd524f 98
c5b390b6 99/** Constant stuff for coinbase transactions we create: */
7bf8b7c2 100CScript COINBASE_FLAGS;
0a61b0df 101
0163f8fa 102const string strMessageMagic = "Zcash Signed Message:\n";
2bc4fd60 103
caca6aa4
PW
104// Internal stuff
105namespace {
e10dcf27 106
6b29ccc9
B
107 struct CBlockIndexWorkComparator
108 {
3fcfbc8a 109 bool operator()(CBlockIndex *pa, CBlockIndex *pb) const {
6b29ccc9
B
110 // First sort by most total work, ...
111 if (pa->nChainWork > pb->nChainWork) return false;
112 if (pa->nChainWork < pb->nChainWork) return true;
113
114 // ... then by earliest time received, ...
115 if (pa->nSequenceId < pb->nSequenceId) return false;
116 if (pa->nSequenceId > pb->nSequenceId) return true;
117
118 // Use pointer address as tie breaker (should only happen with blocks
119 // loaded from disk, as those all have id 0).
120 if (pa < pb) return false;
121 if (pa > pb) return true;
122
123 // Identical blocks.
124 return false;
125 }
126 };
127
128 CBlockIndex *pindexBestInvalid;
714a3e65 129
c5b390b6 130 /**
3fcfbc8a 131 * The set of all CBlockIndex entries with BLOCK_VALID_TRANSACTIONS (for itself and all ancestors) and
f9ec3f0f 132 * as good as our current tip or better. Entries may be failed, though, and pruning nodes may be
133 * missing the data for the block.
c5b390b6 134 */
e17bd583 135 set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexCandidates;
c5b390b6 136 /** Number of nodes with fSyncStarted. */
341735eb 137 int nSyncStarted = 0;
f9ec3f0f 138 /** All pairs A->B, where A (or one if its ancestors) misses transactions, but B has transactions.
139 * Pruned nodes may have entries where B is missing data.
140 */
341735eb 141 multimap<CBlockIndex*, CBlockIndex*> mapBlocksUnlinked;
6b29ccc9
B
142
143 CCriticalSection cs_LastBlockFile;
ed6d1a2c 144 std::vector<CBlockFileInfo> vinfoBlockFile;
6b29ccc9 145 int nLastBlockFile = 0;
f9ec3f0f 146 /** Global flag to indicate we should check to see if there are
147 * block/undo files that should be deleted. Set on startup
148 * or if we allocate more file space when we're in prune mode
149 */
150 bool fCheckForPruning = false;
6b29ccc9 151
c5b390b6
MF
152 /**
153 * Every received block is assigned a unique and increasing identifier, so we
154 * know which one to give priority in case of a fork.
155 */
6b29ccc9 156 CCriticalSection cs_nBlockSequenceId;
c5b390b6 157 /** Blocks loaded from disk are assigned id 0, so start the counter at 1. */
6b29ccc9
B
158 uint32_t nBlockSequenceId = 1;
159
c5b390b6 160 /**
b05a89b2
LD
161 * Sources of received blocks, saved to be able to send them reject
162 * messages or ban them when processing happens afterwards. Protected by
163 * cs_main.
c5b390b6 164 */
6b29ccc9
B
165 map<uint256, NodeId> mapBlockSource;
166
ec9b6c33
PT
167 /**
168 * Filter for transactions that were recently rejected by
169 * AcceptToMemoryPool. These are not rerequested until the chain tip
170 * changes, at which point the entire filter is reset. Protected by
171 * cs_main.
172 *
173 * Without this filter we'd be re-requesting txs from each of our peers,
174 * increasing bandwidth consumption considerably. For instance, with 100
175 * peers, half of which relay a tx we don't accept, that might be a 50x
176 * bandwidth increase. A flooding attacker attempting to roll-over the
177 * filter using minimum-sized, 60byte, transactions might manage to send
178 * 1000/sec if we have fast peers, so we pick 120,000 to give our peers a
179 * two minute window to send invs to us.
180 *
181 * Decreasing the false positive rate is fairly cheap, so we pick one in a
182 * million to make it highly unlikely for users to have issues with this
183 * filter.
184 *
185 * Memory used: 1.7MB
186 */
187 boost::scoped_ptr<CRollingBloomFilter> recentRejects;
188 uint256 hashRecentRejectsChainTip;
189
c5b390b6 190 /** Blocks that are in flight, and that are in the queue to be downloaded. Protected by cs_main. */
6b29ccc9
B
191 struct QueuedBlock {
192 uint256 hash;
c5b390b6
MF
193 CBlockIndex *pindex; //! Optional.
194 int64_t nTime; //! Time of "getdata" request in microseconds.
91613034 195 bool fValidatedHeaders; //! Whether this block has validated headers at the time of request.
8ba7f842 196 int64_t nTimeDisconnect; //! The timeout for this block request (for disconnecting a slow peer)
6b29ccc9
B
197 };
198 map<uint256, pair<NodeId, list<QueuedBlock>::iterator> > mapBlocksInFlight;
e10dcf27 199
91613034
PW
200 /** Number of blocks in flight with validated headers. */
201 int nQueuedValidatedHeaders = 0;
202
c5b390b6 203 /** Number of preferable block download peers. */
b4ee0bdd 204 int nPreferredDownload = 0;
51ce901a 205
c5b390b6 206 /** Dirty block index entries. */
51ce901a
PW
207 set<CBlockIndex*> setDirtyBlockIndex;
208
c5b390b6 209 /** Dirty block file entries. */
51ce901a 210 set<int> setDirtyFileInfo;
e10dcf27 211} // anon namespace
0a61b0df 212
501da250
EL
213//////////////////////////////////////////////////////////////////////////////
214//
215// Registration of network node signals.
216//
217
b2864d2f 218namespace {
75f51f2a
PW
219
220struct CBlockReject {
221 unsigned char chRejectCode;
222 string strRejectReason;
223 uint256 hashBlock;
224};
225
c5b390b6
MF
226/**
227 * Maintain validation-specific state about nodes, protected by cs_main, instead
228 * by CNode's own locks. This simplifies asynchronous operation, where
229 * processing of incoming data is done after the ProcessMessage call returns,
230 * and we're no longer holding the node's locks.
231 */
b2864d2f 232struct CNodeState {
9c273790
PW
233 //! The peer's address
234 CService address;
235 //! Whether we have a fully established connection.
236 bool fCurrentlyConnected;
c5b390b6 237 //! Accumulated misbehaviour score for this peer.
b2864d2f 238 int nMisbehavior;
c5b390b6 239 //! Whether this peer should be disconnected and banned (unless whitelisted).
b2864d2f 240 bool fShouldBan;
c5b390b6 241 //! String name of this peer (debugging/logging purposes).
b2864d2f 242 std::string name;
c5b390b6 243 //! List of asynchronously-determined block rejections to notify this peer about.
75f51f2a 244 std::vector<CBlockReject> rejects;
c5b390b6 245 //! The best known block we know this peer has announced.
aa815647 246 CBlockIndex *pindexBestKnownBlock;
c5b390b6 247 //! The hash of the last unknown block this peer has announced.
aa815647 248 uint256 hashLastUnknownBlock;
c5b390b6 249 //! The last full block we both have.
341735eb 250 CBlockIndex *pindexLastCommonBlock;
c5b390b6 251 //! Whether we've started headers synchronization with this peer.
341735eb 252 bool fSyncStarted;
c5b390b6 253 //! Since when we're stalling block download progress (in microseconds), or 0.
341735eb 254 int64_t nStallingSince;
f59d8f0b
PW
255 list<QueuedBlock> vBlocksInFlight;
256 int nBlocksInFlight;
8ba7f842 257 int nBlocksInFlightValidHeaders;
c5b390b6 258 //! Whether we consider this a preferred download peer.
b4ee0bdd 259 bool fPreferredDownload;
b2864d2f
PW
260
261 CNodeState() {
9c273790 262 fCurrentlyConnected = false;
b2864d2f
PW
263 nMisbehavior = 0;
264 fShouldBan = false;
aa815647 265 pindexBestKnownBlock = NULL;
4f152496 266 hashLastUnknownBlock.SetNull();
341735eb
PW
267 pindexLastCommonBlock = NULL;
268 fSyncStarted = false;
269 nStallingSince = 0;
f59d8f0b 270 nBlocksInFlight = 0;
8ba7f842 271 nBlocksInFlightValidHeaders = 0;
b4ee0bdd 272 fPreferredDownload = false;
b2864d2f
PW
273 }
274};
275
c5b390b6 276/** Map maintaining per-node state. Requires cs_main. */
b2864d2f
PW
277map<NodeId, CNodeState> mapNodeState;
278
279// Requires cs_main.
280CNodeState *State(NodeId pnode) {
281 map<NodeId, CNodeState>::iterator it = mapNodeState.find(pnode);
282 if (it == mapNodeState.end())
283 return NULL;
284 return &it->second;
285}
286
287int GetHeight()
4c6d41b8
PW
288{
289 LOCK(cs_main);
290 return chainActive.Height();
291}
292
b4ee0bdd
PW
293void UpdatePreferredDownload(CNode* node, CNodeState* state)
294{
295 nPreferredDownload -= state->fPreferredDownload;
296
297 // Whether this node should be marked as a preferred download node.
298 state->fPreferredDownload = (!node->fInbound || node->fWhitelisted) && !node->fOneShot && !node->fClient;
299
300 nPreferredDownload += state->fPreferredDownload;
301}
302
8ba7f842 303// Returns time at which to timeout block request (nTime in microseconds)
82737933 304int64_t GetBlockTimeout(int64_t nTime, int nValidatedQueuedBefore, const Consensus::Params &consensusParams)
8ba7f842 305{
82737933 306 return nTime + 500000 * consensusParams.nPowTargetSpacing * (4 + nValidatedQueuedBefore);
8ba7f842
SD
307}
308
b2864d2f
PW
309void InitializeNode(NodeId nodeid, const CNode *pnode) {
310 LOCK(cs_main);
311 CNodeState &state = mapNodeState.insert(std::make_pair(nodeid, CNodeState())).first->second;
312 state.name = pnode->addrName;
9c273790 313 state.address = pnode->addr;
b2864d2f
PW
314}
315
316void FinalizeNode(NodeId nodeid) {
317 LOCK(cs_main);
f59d8f0b
PW
318 CNodeState *state = State(nodeid);
319
341735eb
PW
320 if (state->fSyncStarted)
321 nSyncStarted--;
322
9c273790
PW
323 if (state->nMisbehavior == 0 && state->fCurrentlyConnected) {
324 AddressCurrentlyConnected(state->address);
325 }
326
f59d8f0b
PW
327 BOOST_FOREACH(const QueuedBlock& entry, state->vBlocksInFlight)
328 mapBlocksInFlight.erase(entry.hash);
c74332c6 329 EraseOrphansFor(nodeid);
b4ee0bdd 330 nPreferredDownload -= state->fPreferredDownload;
f59d8f0b 331
b2864d2f
PW
332 mapNodeState.erase(nodeid);
333}
f59d8f0b
PW
334
335// Requires cs_main.
304892fc
SD
336// Returns a bool indicating whether we requested this block.
337bool MarkBlockAsReceived(const uint256& hash) {
f59d8f0b
PW
338 map<uint256, pair<NodeId, list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash);
339 if (itInFlight != mapBlocksInFlight.end()) {
340 CNodeState *state = State(itInFlight->second.first);
91613034 341 nQueuedValidatedHeaders -= itInFlight->second.second->fValidatedHeaders;
8ba7f842 342 state->nBlocksInFlightValidHeaders -= itInFlight->second.second->fValidatedHeaders;
f59d8f0b
PW
343 state->vBlocksInFlight.erase(itInFlight->second.second);
344 state->nBlocksInFlight--;
341735eb 345 state->nStallingSince = 0;
f59d8f0b 346 mapBlocksInFlight.erase(itInFlight);
304892fc 347 return true;
f59d8f0b 348 }
304892fc 349 return false;
f59d8f0b
PW
350}
351
352// Requires cs_main.
82737933 353void MarkBlockAsInFlight(NodeId nodeid, const uint256& hash, const Consensus::Params& consensusParams, CBlockIndex *pindex = NULL) {
f59d8f0b
PW
354 CNodeState *state = State(nodeid);
355 assert(state != NULL);
356
357 // Make sure it's not listed somewhere already.
358 MarkBlockAsReceived(hash);
359
8ba7f842 360 int64_t nNow = GetTimeMicros();
82737933 361 QueuedBlock newentry = {hash, pindex, nNow, pindex != NULL, GetBlockTimeout(nNow, nQueuedValidatedHeaders, consensusParams)};
91613034 362 nQueuedValidatedHeaders += newentry.fValidatedHeaders;
f59d8f0b
PW
363 list<QueuedBlock>::iterator it = state->vBlocksInFlight.insert(state->vBlocksInFlight.end(), newentry);
364 state->nBlocksInFlight++;
8ba7f842 365 state->nBlocksInFlightValidHeaders += newentry.fValidatedHeaders;
f59d8f0b
PW
366 mapBlocksInFlight[hash] = std::make_pair(nodeid, it);
367}
368
aa815647
PW
369/** Check whether the last unknown block a peer advertized is not yet known. */
370void ProcessBlockAvailability(NodeId nodeid) {
371 CNodeState *state = State(nodeid);
372 assert(state != NULL);
373
4f152496 374 if (!state->hashLastUnknownBlock.IsNull()) {
145d5be8 375 BlockMap::iterator itOld = mapBlockIndex.find(state->hashLastUnknownBlock);
aa815647
PW
376 if (itOld != mapBlockIndex.end() && itOld->second->nChainWork > 0) {
377 if (state->pindexBestKnownBlock == NULL || itOld->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
378 state->pindexBestKnownBlock = itOld->second;
4f152496 379 state->hashLastUnknownBlock.SetNull();
aa815647
PW
380 }
381 }
382}
383
384/** Update tracking information about which blocks a peer is assumed to have. */
385void UpdateBlockAvailability(NodeId nodeid, const uint256 &hash) {
386 CNodeState *state = State(nodeid);
387 assert(state != NULL);
388
389 ProcessBlockAvailability(nodeid);
390
145d5be8 391 BlockMap::iterator it = mapBlockIndex.find(hash);
aa815647
PW
392 if (it != mapBlockIndex.end() && it->second->nChainWork > 0) {
393 // An actually better block was announced.
394 if (state->pindexBestKnownBlock == NULL || it->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
395 state->pindexBestKnownBlock = it->second;
396 } else {
397 // An unknown block was announced; just assume that the latest one is the best one.
398 state->hashLastUnknownBlock = hash;
399 }
400}
401
341735eb
PW
402/** Find the last common ancestor two blocks have.
403 * Both pa and pb must be non-NULL. */
404CBlockIndex* LastCommonAncestor(CBlockIndex* pa, CBlockIndex* pb) {
405 if (pa->nHeight > pb->nHeight) {
406 pa = pa->GetAncestor(pb->nHeight);
407 } else if (pb->nHeight > pa->nHeight) {
408 pb = pb->GetAncestor(pa->nHeight);
409 }
410
411 while (pa != pb && pa && pb) {
412 pa = pa->pprev;
413 pb = pb->pprev;
414 }
415
416 // Eventually all chain branches meet at the genesis block.
417 assert(pa == pb);
418 return pa;
419}
420
421/** Update pindexLastCommonBlock and add not-in-flight missing successors to vBlocks, until it has
422 * at most count entries. */
423void FindNextBlocksToDownload(NodeId nodeid, unsigned int count, std::vector<CBlockIndex*>& vBlocks, NodeId& nodeStaller) {
424 if (count == 0)
425 return;
426
427 vBlocks.reserve(vBlocks.size() + count);
428 CNodeState *state = State(nodeid);
429 assert(state != NULL);
430
431 // Make sure pindexBestKnownBlock is up to date, we'll need it.
432 ProcessBlockAvailability(nodeid);
433
434 if (state->pindexBestKnownBlock == NULL || state->pindexBestKnownBlock->nChainWork < chainActive.Tip()->nChainWork) {
435 // This peer has nothing interesting.
436 return;
437 }
438
439 if (state->pindexLastCommonBlock == NULL) {
440 // Bootstrap quickly by guessing a parent of our best tip is the forking point.
441 // Guessing wrong in either direction is not a problem.
442 state->pindexLastCommonBlock = chainActive[std::min(state->pindexBestKnownBlock->nHeight, chainActive.Height())];
443 }
444
445 // If the peer reorganized, our previous pindexLastCommonBlock may not be an ancestor
b05a89b2 446 // of its current tip anymore. Go back enough to fix that.
341735eb
PW
447 state->pindexLastCommonBlock = LastCommonAncestor(state->pindexLastCommonBlock, state->pindexBestKnownBlock);
448 if (state->pindexLastCommonBlock == state->pindexBestKnownBlock)
449 return;
450
451 std::vector<CBlockIndex*> vToFetch;
452 CBlockIndex *pindexWalk = state->pindexLastCommonBlock;
e11b2ce4
PW
453 // Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last
454 // linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to
455 // download that next block if the window were 1 larger.
456 int nWindowEnd = state->pindexLastCommonBlock->nHeight + BLOCK_DOWNLOAD_WINDOW;
457 int nMaxHeight = std::min<int>(state->pindexBestKnownBlock->nHeight, nWindowEnd + 1);
341735eb
PW
458 NodeId waitingfor = -1;
459 while (pindexWalk->nHeight < nMaxHeight) {
460 // Read up to 128 (or more, if more blocks than that are needed) successors of pindexWalk (towards
461 // pindexBestKnownBlock) into vToFetch. We fetch 128, because CBlockIndex::GetAncestor may be as expensive
462 // as iterating over ~100 CBlockIndex* entries anyway.
463 int nToFetch = std::min(nMaxHeight - pindexWalk->nHeight, std::max<int>(count - vBlocks.size(), 128));
464 vToFetch.resize(nToFetch);
465 pindexWalk = state->pindexBestKnownBlock->GetAncestor(pindexWalk->nHeight + nToFetch);
466 vToFetch[nToFetch - 1] = pindexWalk;
467 for (unsigned int i = nToFetch - 1; i > 0; i--) {
468 vToFetch[i - 1] = vToFetch[i]->pprev;
469 }
470
471 // Iterate over those blocks in vToFetch (in forward direction), adding the ones that
c938fb1f 472 // are not yet downloaded and not in flight to vBlocks. In the meantime, update
a5876065
SD
473 // pindexLastCommonBlock as long as all ancestors are already downloaded, or if it's
474 // already part of our chain (and therefore don't need it even if pruned).
341735eb 475 BOOST_FOREACH(CBlockIndex* pindex, vToFetch) {
34970223
PW
476 if (!pindex->IsValid(BLOCK_VALID_TREE)) {
477 // We consider the chain that this peer is on invalid.
478 return;
479 }
a5876065 480 if (pindex->nStatus & BLOCK_HAVE_DATA || chainActive.Contains(pindex)) {
341735eb
PW
481 if (pindex->nChainTx)
482 state->pindexLastCommonBlock = pindex;
483 } else if (mapBlocksInFlight.count(pindex->GetBlockHash()) == 0) {
484 // The block is not already downloaded, and not yet in flight.
e11b2ce4 485 if (pindex->nHeight > nWindowEnd) {
341735eb
PW
486 // We reached the end of the window.
487 if (vBlocks.size() == 0 && waitingfor != nodeid) {
488 // We aren't able to fetch anything, but we would be if the download window was one larger.
489 nodeStaller = waitingfor;
490 }
491 return;
492 }
493 vBlocks.push_back(pindex);
494 if (vBlocks.size() == count) {
495 return;
496 }
497 } else if (waitingfor == -1) {
498 // This is the first already-in-flight block.
499 waitingfor = mapBlocksInFlight[pindex->GetBlockHash()].first;
500 }
501 }
502 }
503}
504
e10dcf27 505} // anon namespace
b2864d2f
PW
506
507bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats) {
508 LOCK(cs_main);
509 CNodeState *state = State(nodeid);
510 if (state == NULL)
511 return false;
512 stats.nMisbehavior = state->nMisbehavior;
aa815647 513 stats.nSyncHeight = state->pindexBestKnownBlock ? state->pindexBestKnownBlock->nHeight : -1;
ad6e6017
PW
514 stats.nCommonHeight = state->pindexLastCommonBlock ? state->pindexLastCommonBlock->nHeight : -1;
515 BOOST_FOREACH(const QueuedBlock& queue, state->vBlocksInFlight) {
516 if (queue.pindex)
517 stats.vHeightInFlight.push_back(queue.pindex->nHeight);
518 }
b2864d2f
PW
519 return true;
520}
521
501da250
EL
522void RegisterNodeSignals(CNodeSignals& nodeSignals)
523{
4c6d41b8 524 nodeSignals.GetHeight.connect(&GetHeight);
501da250
EL
525 nodeSignals.ProcessMessages.connect(&ProcessMessages);
526 nodeSignals.SendMessages.connect(&SendMessages);
b2864d2f
PW
527 nodeSignals.InitializeNode.connect(&InitializeNode);
528 nodeSignals.FinalizeNode.connect(&FinalizeNode);
501da250 529}
64c7ee7e 530
501da250
EL
531void UnregisterNodeSignals(CNodeSignals& nodeSignals)
532{
4c6d41b8 533 nodeSignals.GetHeight.disconnect(&GetHeight);
501da250
EL
534 nodeSignals.ProcessMessages.disconnect(&ProcessMessages);
535 nodeSignals.SendMessages.disconnect(&SendMessages);
b2864d2f
PW
536 nodeSignals.InitializeNode.disconnect(&InitializeNode);
537 nodeSignals.FinalizeNode.disconnect(&FinalizeNode);
501da250 538}
64c7ee7e 539
6db83db3 540CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator)
541{
70e7fba0 542 // Find the first block the caller has in the main chain
e4daecda 543 BOOST_FOREACH(const uint256& hash, locator.vHave) {
145d5be8 544 BlockMap::iterator mi = mapBlockIndex.find(hash);
70e7fba0
MH
545 if (mi != mapBlockIndex.end())
546 {
547 CBlockIndex* pindex = (*mi).second;
6db83db3 548 if (chain.Contains(pindex))
70e7fba0 549 return pindex;
89f20450
PW
550 if (pindex->GetAncestor(chain.Height()) == chain.Tip()) {
551 return chain.Tip();
552 }
70e7fba0
MH
553 }
554 }
6db83db3 555 return chain.Genesis();
77339e5a
PW
556}
557
ae8bfd12 558CCoinsViewCache *pcoinsTip = NULL;
d979e6e3 559CBlockTreeDB *pblocktree = NULL;
450cbb09 560
0a61b0df 561//////////////////////////////////////////////////////////////////////////////
562//
563// mapOrphanTransactions
564//
565
72b25b0f 566bool AddOrphanTx(const CTransaction& tx, NodeId peer) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
0a61b0df 567{
805344dc 568 uint256 hash = tx.GetHash();
0a61b0df 569 if (mapOrphanTransactions.count(hash))
77b99cf7
GA
570 return false;
571
77b99cf7
GA
572 // Ignore big transactions, to avoid a
573 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
574 // large transaction with a missing parent then we assume
575 // it will rebroadcast it later, after the parent transaction(s)
576 // have been mined or received.
577 // 10,000 orphans, each of which is at most 5,000 bytes big is
578 // at most 500 megabytes of orphans:
a8e5ae92 579 unsigned int sz = GetSerializeSize(tx, SER_NETWORK, tx.nVersion);
159bc481 580 if (sz > 5000)
77b99cf7 581 {
7d9d134b 582 LogPrint("mempool", "ignoring large orphan tx (size: %u, hash: %s)\n", sz, hash.ToString());
77b99cf7
GA
583 return false;
584 }
142e6041 585
c74332c6
GA
586 mapOrphanTransactions[hash].tx = tx;
587 mapOrphanTransactions[hash].fromPeer = peer;
223b6f1b 588 BOOST_FOREACH(const CTxIn& txin, tx.vin)
159bc481 589 mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash);
77b99cf7 590
c74332c6
GA
591 LogPrint("mempool", "stored orphan tx %s (mapsz %u prevsz %u)\n", hash.ToString(),
592 mapOrphanTransactions.size(), mapOrphanTransactionsByPrev.size());
77b99cf7 593 return true;
0a61b0df 594}
595
72b25b0f 596void static EraseOrphanTx(uint256 hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
0a61b0df 597{
c74332c6 598 map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.find(hash);
89d91f6a 599 if (it == mapOrphanTransactions.end())
0a61b0df 600 return;
c74332c6 601 BOOST_FOREACH(const CTxIn& txin, it->second.tx.vin)
0a61b0df 602 {
89d91f6a 603 map<uint256, set<uint256> >::iterator itPrev = mapOrphanTransactionsByPrev.find(txin.prevout.hash);
def2fdb4
GA
604 if (itPrev == mapOrphanTransactionsByPrev.end())
605 continue;
89d91f6a
WL
606 itPrev->second.erase(hash);
607 if (itPrev->second.empty())
608 mapOrphanTransactionsByPrev.erase(itPrev);
0a61b0df 609 }
89d91f6a 610 mapOrphanTransactions.erase(it);
0a61b0df 611}
612
c74332c6
GA
613void EraseOrphansFor(NodeId peer)
614{
615 int nErased = 0;
616 map<uint256, COrphanTx>::iterator iter = mapOrphanTransactions.begin();
617 while (iter != mapOrphanTransactions.end())
618 {
619 map<uint256, COrphanTx>::iterator maybeErase = iter++; // increment to avoid iterator becoming invalid
620 if (maybeErase->second.fromPeer == peer)
621 {
805344dc 622 EraseOrphanTx(maybeErase->second.tx.GetHash());
c74332c6
GA
623 ++nErased;
624 }
625 }
626 if (nErased > 0) LogPrint("mempool", "Erased %d orphan tx from peer %d\n", nErased, peer);
627}
628
629
72b25b0f 630unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
142e6041 631{
7bd9c3a3 632 unsigned int nEvicted = 0;
142e6041
GA
633 while (mapOrphanTransactions.size() > nMaxOrphans)
634 {
635 // Evict a random orphan:
f718aedd 636 uint256 randomhash = GetRandHash();
c74332c6 637 map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
142e6041
GA
638 if (it == mapOrphanTransactions.end())
639 it = mapOrphanTransactions.begin();
640 EraseOrphanTx(it->first);
641 ++nEvicted;
642 }
643 return nEvicted;
644}
0a61b0df 645
646
072099d7 647bool IsStandardTx(const CTransaction& tx, string& reason, const int nHeight)
000dc551 648{
72540cee
JG
649 bool overwinterActive = NetworkUpgradeActive(nHeight, Params().GetConsensus(), Consensus::UPGRADE_OVERWINTER);
650 bool saplingActive = NetworkUpgradeActive(nHeight, Params().GetConsensus(), Consensus::UPGRADE_SAPLING);
072099d7 651
72540cee
JG
652 if (saplingActive) {
653 // Sapling standard rules apply
654 if (tx.nVersion > CTransaction::SAPLING_MAX_CURRENT_VERSION || tx.nVersion < CTransaction::SAPLING_MIN_CURRENT_VERSION) {
655 reason = "sapling-version";
656 return false;
657 }
658 } else if (overwinterActive) {
072099d7
S
659 // Overwinter standard rules apply
660 if (tx.nVersion > CTransaction::OVERWINTER_MAX_CURRENT_VERSION || tx.nVersion < CTransaction::OVERWINTER_MIN_CURRENT_VERSION) {
661 reason = "overwinter-version";
662 return false;
663 }
664 } else {
665 // Sprout standard rules apply
666 if (tx.nVersion > CTransaction::SPROUT_MAX_CURRENT_VERSION || tx.nVersion < CTransaction::SPROUT_MIN_CURRENT_VERSION) {
667 reason = "version";
668 return false;
669 }
980bfe6e 670 }
dae3e10a 671
05df3fc6 672 BOOST_FOREACH(const CTxIn& txin, tx.vin)
e679ec96 673 {
4d79098a
PT
674 // Biggest 'standard' txin is a 15-of-15 P2SH multisig with compressed
675 // keys. (remember the 520 byte limit on redeemScript size) That works
675bcd58 676 // out to a (15*(33+1))+3=513 byte redeemScript, 513+1+15*(73+1)+3=1627
4d79098a
PT
677 // bytes of scriptSig, which we round off to 1650 bytes for some minor
678 // future-proofing. That's also enough to spend a 20-of-20
679 // CHECKMULTISIG scriptPubKey, though such a scriptPubKey is not
680 // considered standard)
681 if (txin.scriptSig.size() > 1650) {
980bfe6e 682 reason = "scriptsig-size";
922e8e29 683 return false;
980bfe6e
JG
684 }
685 if (!txin.scriptSig.IsPushOnly()) {
686 reason = "scriptsig-not-pushonly";
922e8e29 687 return false;
87fe71e1 688 }
e679ec96 689 }
a7934247
JG
690
691 unsigned int nDataOut = 0;
692 txnouttype whichType;
05df3fc6 693 BOOST_FOREACH(const CTxOut& txout, tx.vout) {
a7934247 694 if (!::IsStandard(txout.scriptPubKey, whichType)) {
980bfe6e 695 reason = "scriptpubkey";
922e8e29 696 return false;
980bfe6e 697 }
3da434a2 698
a7934247
JG
699 if (whichType == TX_NULL_DATA)
700 nDataOut++;
3da434a2
JG
701 else if ((whichType == TX_MULTISIG) && (!fIsBareMultisigStd)) {
702 reason = "bare-multisig";
703 return false;
704 } else if (txout.IsDust(::minRelayTxFee)) {
980bfe6e 705 reason = "dust";
65ce2156 706 return false;
980bfe6e 707 }
65ce2156 708 }
980bfe6e 709
a7934247
JG
710 // only one OP_RETURN txout is permitted
711 if (nDataOut > 1) {
b34e88a8 712 reason = "multi-op-return";
a7934247
JG
713 return false;
714 }
715
e679ec96
GA
716 return true;
717}
718
51ed9ec9 719bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)
05df3fc6 720{
05df3fc6
EL
721 if (tx.nLockTime == 0)
722 return true;
51ed9ec9 723 if ((int64_t)tx.nLockTime < ((int64_t)tx.nLockTime < LOCKTIME_THRESHOLD ? (int64_t)nBlockHeight : nBlockTime))
05df3fc6
EL
724 return true;
725 BOOST_FOREACH(const CTxIn& txin, tx.vin)
726 if (!txin.IsFinal())
727 return false;
728 return true;
729}
730
9bb37bf0
JG
731bool IsExpiredTx(const CTransaction &tx, int nBlockHeight)
732{
733 if (tx.nExpiryHeight == 0 || tx.IsCoinBase()) {
734 return false;
735 }
736 return static_cast<uint32_t>(nBlockHeight) > tx.nExpiryHeight;
737}
738
a1d3c6fb 739bool CheckFinalTx(const CTransaction &tx, int flags)
75a4d512
PT
740{
741 AssertLockHeld(cs_main);
a1d3c6fb
MF
742
743 // By convention a negative value for flags indicates that the
744 // current network-enforced consensus rules should be used. In
745 // a future soft-fork scenario that would mean checking which
746 // rules would be enforced for the next block and setting the
747 // appropriate flags. At the present time no soft-forks are
748 // scheduled, so no flags are set.
749 flags = std::max(flags, 0);
750
751 // CheckFinalTx() uses chainActive.Height()+1 to evaluate
752 // nLockTime because when IsFinalTx() is called within
753 // CBlock::AcceptBlock(), the height of the block *being*
754 // evaluated is what is used. Thus if we want to know if a
755 // transaction can be part of the *next* block, we need to call
756 // IsFinalTx() with one more than chainActive.Height().
757 const int nBlockHeight = chainActive.Height() + 1;
758
759 // Timestamps on the other hand don't get any special treatment,
760 // because we can't know what timestamp the next block will have,
761 // and there aren't timestamp applications where it matters.
762 // However this changes once median past time-locks are enforced:
763 const int64_t nBlockTime = (flags & LOCKTIME_MEDIAN_TIME_PAST)
764 ? chainActive.Tip()->GetMedianTimePast()
765 : GetAdjustedTime();
766
767 return IsFinalTx(tx, nBlockHeight, nBlockTime);
75a4d512
PT
768}
769
c5b390b6
MF
770/**
771 * Check transaction inputs to mitigate two
772 * potential denial-of-service attacks:
db954a65 773 *
c5b390b6
MF
774 * 1. scriptSigs with extra data stuffed into them,
775 * not consumed by scriptPubKey (or P2SH script)
776 * 2. P2SH scripts with a crazy number of expensive
777 * CHECKSIG/CHECKMULTISIG operations
778 */
be126699 779bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs, uint32_t consensusBranchId)
e679ec96 780{
05df3fc6 781 if (tx.IsCoinBase())
575bdcde 782 return true; // Coinbases don't use vin normally
8d7849b6 783
05df3fc6 784 for (unsigned int i = 0; i < tx.vin.size(); i++)
e679ec96 785 {
05df3fc6 786 const CTxOut& prev = mapInputs.GetOutputFor(tx.vin[i]);
e679ec96
GA
787
788 vector<vector<unsigned char> > vSolutions;
2a45a494
GA
789 txnouttype whichType;
790 // get the scriptPubKey corresponding to this input:
8d7849b6 791 const CScript& prevScript = prev.scriptPubKey;
2a45a494 792 if (!Solver(prevScript, whichType, vSolutions))
922e8e29 793 return false;
39f0d968 794 int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
c0a0a93d
JG
795 if (nArgsExpected < 0)
796 return false;
39f0d968
GA
797
798 // Transactions with extra stuff in their scriptSigs are
799 // non-standard. Note that this EvalScript() call will
800 // be quick, because if there are any operations
7f3b4e95 801 // beside "push data" in the scriptSig
bd2b73bb 802 // IsStandardTx() will have already returned false
7f3b4e95 803 // and this method isn't called.
39f0d968 804 vector<vector<unsigned char> > stack;
be126699 805 if (!EvalScript(stack, tx.vin[i].scriptSig, SCRIPT_VERIFY_NONE, BaseSignatureChecker(), consensusBranchId))
39f0d968
GA
806 return false;
807
e679ec96
GA
808 if (whichType == TX_SCRIPTHASH)
809 {
922e8e29 810 if (stack.empty())
e679ec96 811 return false;
2a45a494 812 CScript subscript(stack.back().begin(), stack.back().end());
39f0d968
GA
813 vector<vector<unsigned char> > vSolutions2;
814 txnouttype whichType2;
7f3b4e95
GA
815 if (Solver(subscript, whichType2, vSolutions2))
816 {
817 int tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
818 if (tmpExpected < 0)
819 return false;
820 nArgsExpected += tmpExpected;
821 }
822 else
823 {
824 // Any other Script with less than 15 sigops OK:
825 unsigned int sigops = subscript.GetSigOpCount(true);
826 // ... extra data left on the stack after execution is OK, too:
827 return (sigops <= MAX_P2SH_SIGOPS);
828 }
e679ec96 829 }
39f0d968 830
c0a0a93d 831 if (stack.size() != (unsigned int)nArgsExpected)
39f0d968 832 return false;
e679ec96
GA
833 }
834
835 return true;
836}
837
05df3fc6 838unsigned int GetLegacySigOpCount(const CTransaction& tx)
922e8e29 839{
7bd9c3a3 840 unsigned int nSigOps = 0;
05df3fc6 841 BOOST_FOREACH(const CTxIn& txin, tx.vin)
922e8e29
GA
842 {
843 nSigOps += txin.scriptSig.GetSigOpCount(false);
844 }
05df3fc6 845 BOOST_FOREACH(const CTxOut& txout, tx.vout)
922e8e29
GA
846 {
847 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
848 }
849 return nSigOps;
850}
0a61b0df 851
d0867acb 852unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& inputs)
05df3fc6
EL
853{
854 if (tx.IsCoinBase())
855 return 0;
856
857 unsigned int nSigOps = 0;
858 for (unsigned int i = 0; i < tx.vin.size(); i++)
859 {
860 const CTxOut &prevout = inputs.GetOutputFor(tx.vin[i]);
861 if (prevout.scriptPubKey.IsPayToScriptHash())
862 nSigOps += prevout.scriptPubKey.GetSigOpCount(tx.vin[i].scriptSig);
863 }
864 return nSigOps;
865}
0a61b0df 866
072099d7
S
867/**
868 * Check a transaction contextually against a set of consensus rules valid at a given block height.
869 *
870 * Notes:
871 * 1. AcceptToMemoryPool calls CheckTransaction and this function.
872 * 2. ProcessNewBlock calls AcceptBlock, which calls CheckBlock (which calls CheckTransaction)
873 * and ContextualCheckBlock (which calls this function).
874 */
875bool ContextualCheckTransaction(const CTransaction& tx, CValidationState &state, const int nHeight, const int dosLevel)
876{
987b8ee6
JG
877 bool overwinterActive = NetworkUpgradeActive(nHeight, Params().GetConsensus(), Consensus::UPGRADE_OVERWINTER);
878 bool saplingActive = NetworkUpgradeActive(nHeight, Params().GetConsensus(), Consensus::UPGRADE_SAPLING);
879 bool isSprout = !overwinterActive;
072099d7
S
880
881 // If Sprout rules apply, reject transactions which are intended for Overwinter and beyond
882 if (isSprout && tx.fOverwintered) {
883 return state.DoS(dosLevel, error("ContextualCheckTransaction(): overwinter is not active yet"),
884 REJECT_INVALID, "tx-overwinter-not-active");
885 }
886
987b8ee6
JG
887 if (saplingActive) {
888 // Reject transactions with valid version but missing overwintered flag
889 if (tx.nVersion >= SAPLING_MIN_TX_VERSION && !tx.fOverwintered) {
890 return state.DoS(dosLevel, error("ContextualCheckTransaction(): overwintered flag must be set"),
891 REJECT_INVALID, "tx-overwintered-flag-not-set");
892 }
893
894 // Reject transactions with non-Sapling version group ID
895 if (tx.fOverwintered && tx.nVersionGroupId != SAPLING_VERSION_GROUP_ID) {
896 return state.DoS(dosLevel, error("CheckTransaction(): invalid Sapling tx version"),
897 REJECT_INVALID, "bad-sapling-tx-version-group-id");
898 }
899
900 // Reject transactions with invalid version
901 if (tx.fOverwintered && tx.nVersion < SAPLING_MIN_TX_VERSION ) {
902 return state.DoS(100, error("CheckTransaction(): Sapling version too low"),
903 REJECT_INVALID, "bad-tx-sapling-version-too-low");
904 }
905
906 // Reject transactions with invalid version
907 if (tx.fOverwintered && tx.nVersion > SAPLING_MAX_TX_VERSION ) {
908 return state.DoS(100, error("CheckTransaction(): Sapling version too high"),
909 REJECT_INVALID, "bad-tx-sapling-version-too-high");
910 }
911 } else if (overwinterActive) {
072099d7
S
912 // Reject transactions with valid version but missing overwinter flag
913 if (tx.nVersion >= OVERWINTER_MIN_TX_VERSION && !tx.fOverwintered) {
914 return state.DoS(dosLevel, error("ContextualCheckTransaction(): overwinter flag must be set"),
915 REJECT_INVALID, "tx-overwinter-flag-not-set");
916 }
917
987b8ee6
JG
918 // Reject transactions with non-Overwinter version group ID
919 if (tx.fOverwintered && tx.nVersionGroupId != OVERWINTER_VERSION_GROUP_ID) {
920 return state.DoS(dosLevel, error("CheckTransaction(): invalid Overwinter tx version"),
921 REJECT_INVALID, "bad-overwinter-tx-version-group-id");
922 }
923
072099d7
S
924 // Reject transactions with invalid version
925 if (tx.fOverwintered && tx.nVersion > OVERWINTER_MAX_TX_VERSION ) {
926 return state.DoS(100, error("CheckTransaction(): overwinter version too high"),
927 REJECT_INVALID, "bad-tx-overwinter-version-too-high");
928 }
987b8ee6 929 }
072099d7 930
987b8ee6
JG
931 // Rules that apply to Overwinter or later:
932 if (overwinterActive) {
072099d7
S
933 // Reject transactions intended for Sprout
934 if (!tx.fOverwintered) {
935 return state.DoS(dosLevel, error("ContextualCheckTransaction: overwinter is active"),
936 REJECT_INVALID, "tx-overwinter-active");
937 }
9bb37bf0
JG
938
939 // Check that all transactions are unexpired
940 if (IsExpiredTx(tx, nHeight)) {
473a1132
DH
941 // Don't increase banscore if the transaction only just expired
942 int expiredDosLevel = IsExpiredTx(tx, nHeight - 1) ? dosLevel : 0;
943 return state.DoS(expiredDosLevel, error("ContextualCheckTransaction(): transaction is expired"), REJECT_INVALID, "tx-overwinter-expired");
9bb37bf0 944 }
072099d7
S
945 }
946
15ec5525
JG
947 // Rules that apply before Sapling:
948 if (!saplingActive) {
949 // Size limits
950 BOOST_STATIC_ASSERT(MAX_BLOCK_SIZE > MAX_TX_SIZE_BEFORE_SAPLING); // sanity
951 if (::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION) > MAX_TX_SIZE_BEFORE_SAPLING)
952 return state.DoS(100, error("ContextualCheckTransaction(): size limits failed"),
953 REJECT_INVALID, "bad-txns-oversize");
954 }
955
6eea48bf 956 if (!tx.vjoinsplit.empty()) {
be126699
JG
957 auto consensusBranchId = CurrentEpochBranchId(nHeight, Params().GetConsensus());
958 // Empty output script.
959 CScript scriptCode;
960 uint256 dataToBeSigned;
961 try {
962 dataToBeSigned = SignatureHash(scriptCode, tx, NOT_AN_INPUT, SIGHASH_ALL, 0, consensusBranchId);
963 } catch (std::logic_error ex) {
964 return state.DoS(100, error("CheckTransaction(): error computing signature hash"),
965 REJECT_INVALID, "error-computing-signature-hash");
966 }
967
968 BOOST_STATIC_ASSERT(crypto_sign_PUBLICKEYBYTES == 32);
969
970 // We rely on libsodium to check that the signature is canonical.
971 // https://github.com/jedisct1/libsodium/commit/62911edb7ff2275cccd74bf1c8aefcc4d76924e0
972 if (crypto_sign_verify_detached(&tx.joinSplitSig[0],
973 dataToBeSigned.begin(), 32,
974 tx.joinSplitPubKey.begin()
975 ) != 0) {
976 return state.DoS(100, error("CheckTransaction(): invalid joinsplit signature"),
977 REJECT_INVALID, "bad-txns-invalid-joinsplit-signature");
978 }
979 }
072099d7
S
980 return true;
981}
982
983
6fb8d0c2
JG
984bool CheckTransaction(const CTransaction& tx, CValidationState &state,
985 libzcash::ProofVerifier& verifier)
948d4e6c 986{
a6df7ab5
JG
987 // Don't count coinbase transactions because mining skews the count
988 if (!tx.IsCoinBase()) {
989 transactionsValidated.increment();
990 }
991
948d4e6c
TH
992 if (!CheckTransactionWithoutProofVerification(tx, state)) {
993 return false;
994 } else {
995 // Ensure that zk-SNARKs verify
b7e4abd6 996 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
bc59f537 997 if (!joinsplit.Verify(*pzcashParams, verifier, tx.joinSplitPubKey)) {
b7e4abd6
SB
998 return state.DoS(100, error("CheckTransaction(): joinsplit does not verify"),
999 REJECT_INVALID, "bad-txns-joinsplit-verification-failed");
948d4e6c
TH
1000 }
1001 }
1002 return true;
1003 }
1004}
1005
1006bool CheckTransactionWithoutProofVerification(const CTransaction& tx, CValidationState &state)
a790fa46 1007{
1008 // Basic checks that don't depend on any context
69761d82 1009
072099d7
S
1010 /**
1011 * Previously:
1012 * 1. The consensus rule below was:
1013 * if (tx.nVersion < SPROUT_MIN_TX_VERSION) { ... }
1014 * which checked if tx.nVersion fell within the range:
1015 * INT32_MIN <= tx.nVersion < SPROUT_MIN_TX_VERSION
1016 * 2. The parser allowed tx.nVersion to be negative
1017 *
1018 * Now:
1019 * 1. The consensus rule checks to see if tx.Version falls within the range:
1020 * 0 <= tx.nVersion < SPROUT_MIN_TX_VERSION
1021 * 2. The previous consensus rule checked for negative values within the range:
1022 * INT32_MIN <= tx.nVersion < 0
1023 * This is unnecessary for Overwinter transactions since the parser now
1024 * interprets the sign bit as fOverwintered, so tx.nVersion is always >=0,
1025 * and when Overwinter is not active ContextualCheckTransaction rejects
1026 * transactions with fOverwintered set. When fOverwintered is set,
1027 * this function and ContextualCheckTransaction will together check to
1028 * ensure tx.nVersion avoids the following ranges:
1029 * 0 <= tx.nVersion < OVERWINTER_MIN_TX_VERSION
1030 * OVERWINTER_MAX_TX_VERSION < tx.nVersion <= INT32_MAX
1031 */
1032 if (!tx.fOverwintered && tx.nVersion < SPROUT_MIN_TX_VERSION) {
7ac924cd 1033 return state.DoS(100, error("CheckTransaction(): version too low"),
cb124619 1034 REJECT_INVALID, "bad-txns-version-too-low");
7ac924cd 1035 }
072099d7
S
1036 else if (tx.fOverwintered) {
1037 if (tx.nVersion < OVERWINTER_MIN_TX_VERSION) {
1038 return state.DoS(100, error("CheckTransaction(): overwinter version too low"),
1039 REJECT_INVALID, "bad-tx-overwinter-version-too-low");
1040 }
987b8ee6
JG
1041 if (tx.nVersionGroupId != OVERWINTER_VERSION_GROUP_ID &&
1042 tx.nVersionGroupId != SAPLING_VERSION_GROUP_ID) {
072099d7
S
1043 return state.DoS(100, error("CheckTransaction(): unknown tx version group id"),
1044 REJECT_INVALID, "bad-tx-version-group-id");
1045 }
1046 if (tx.nExpiryHeight >= TX_EXPIRY_HEIGHT_THRESHOLD) {
1047 return state.DoS(100, error("CheckTransaction(): expiry height is too high"),
1048 REJECT_INVALID, "bad-tx-expiry-height-too-high");
1049 }
1050 }
7ac924cd 1051
4b4662b0
EOW
1052 // Transactions containing empty `vin` must have either non-empty
1053 // `vjoinsplit` or non-empty `vShieldedSpend`.
66798551 1054 if (tx.vin.empty() && tx.vjoinsplit.empty() && tx.vShieldedSpend.empty())
5262fde0 1055 return state.DoS(10, error("CheckTransaction(): vin empty"),
14e7ffcc 1056 REJECT_INVALID, "bad-txns-vin-empty");
4b4662b0
EOW
1057 // Transactions containing empty `vout` must have either non-empty
1058 // `vjoinsplit` or non-empty `vShieldedOutput`.
1059 if (tx.vout.empty() && tx.vjoinsplit.empty() && tx.vShieldedOutput.empty())
5262fde0 1060 return state.DoS(10, error("CheckTransaction(): vout empty"),
14e7ffcc 1061 REJECT_INVALID, "bad-txns-vout-empty");
69761d82 1062
a790fa46 1063 // Size limits
25fee350
JG
1064 BOOST_STATIC_ASSERT(MAX_BLOCK_SIZE >= MAX_TX_SIZE_AFTER_SAPLING); // sanity
1065 BOOST_STATIC_ASSERT(MAX_TX_SIZE_AFTER_SAPLING > MAX_TX_SIZE_BEFORE_SAPLING); // sanity
1066 if (::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION) > MAX_TX_SIZE_AFTER_SAPLING)
5262fde0 1067 return state.DoS(100, error("CheckTransaction(): size limits failed"),
14e7ffcc 1068 REJECT_INVALID, "bad-txns-oversize");
a790fa46 1069
1070 // Check for negative or overflow output values
a372168e 1071 CAmount nValueOut = 0;
05df3fc6 1072 BOOST_FOREACH(const CTxOut& txout, tx.vout)
a790fa46 1073 {
1074 if (txout.nValue < 0)
5262fde0 1075 return state.DoS(100, error("CheckTransaction(): txout.nValue negative"),
14e7ffcc 1076 REJECT_INVALID, "bad-txns-vout-negative");
a790fa46 1077 if (txout.nValue > MAX_MONEY)
5262fde0 1078 return state.DoS(100, error("CheckTransaction(): txout.nValue too high"),
14e7ffcc 1079 REJECT_INVALID, "bad-txns-vout-toolarge");
a790fa46 1080 nValueOut += txout.nValue;
1081 if (!MoneyRange(nValueOut))
5262fde0 1082 return state.DoS(100, error("CheckTransaction(): txout total out of range"),
14e7ffcc 1083 REJECT_INVALID, "bad-txns-txouttotal-toolarge");
a790fa46 1084 }
1085
b7e4abd6
SB
1086 // Ensure that joinsplit values are well-formed
1087 BOOST_FOREACH(const JSDescription& joinsplit, tx.vjoinsplit)
69761d82 1088 {
b7e4abd6
SB
1089 if (joinsplit.vpub_old < 0) {
1090 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_old negative"),
69761d82 1091 REJECT_INVALID, "bad-txns-vpub_old-negative");
6ad4db22 1092 }
69761d82 1093
b7e4abd6
SB
1094 if (joinsplit.vpub_new < 0) {
1095 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_new negative"),
69761d82 1096 REJECT_INVALID, "bad-txns-vpub_new-negative");
6ad4db22 1097 }
69761d82 1098
b7e4abd6
SB
1099 if (joinsplit.vpub_old > MAX_MONEY) {
1100 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_old too high"),
69761d82 1101 REJECT_INVALID, "bad-txns-vpub_old-toolarge");
6ad4db22 1102 }
69761d82 1103
b7e4abd6
SB
1104 if (joinsplit.vpub_new > MAX_MONEY) {
1105 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_new too high"),
69761d82 1106 REJECT_INVALID, "bad-txns-vpub_new-toolarge");
6ad4db22
TH
1107 }
1108
b7e4abd6
SB
1109 if (joinsplit.vpub_new != 0 && joinsplit.vpub_old != 0) {
1110 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_new and joinsplit.vpub_old both nonzero"),
6ad4db22
TH
1111 REJECT_INVALID, "bad-txns-vpubs-both-nonzero");
1112 }
69761d82 1113
d7eeb745 1114 nValueOut += joinsplit.vpub_old;
6ad4db22 1115 if (!MoneyRange(nValueOut)) {
69761d82
SB
1116 return state.DoS(100, error("CheckTransaction(): txout total out of range"),
1117 REJECT_INVALID, "bad-txns-txouttotal-toolarge");
6ad4db22 1118 }
69761d82
SB
1119 }
1120
d7eeb745
SB
1121 // Ensure input values do not exceed MAX_MONEY
1122 // We have not resolved the txin values at this stage,
1123 // but we do know what the joinsplits claim to add
1124 // to the value pool.
1125 {
1126 CAmount nValueIn = 0;
1127 for (std::vector<JSDescription>::const_iterator it(tx.vjoinsplit.begin()); it != tx.vjoinsplit.end(); ++it)
1128 {
1129 nValueIn += it->vpub_new;
1130
1131 if (!MoneyRange(it->vpub_new) || !MoneyRange(nValueIn)) {
1132 return state.DoS(100, error("CheckTransaction(): txin total out of range"),
1133 REJECT_INVALID, "bad-txns-txintotal-toolarge");
1134 }
1135 }
1136 }
1137
69761d82 1138
33208fb5
MC
1139 // Check for duplicate inputs
1140 set<COutPoint> vInOutPoints;
05df3fc6 1141 BOOST_FOREACH(const CTxIn& txin, tx.vin)
33208fb5
MC
1142 {
1143 if (vInOutPoints.count(txin.prevout))
5262fde0 1144 return state.DoS(100, error("CheckTransaction(): duplicate inputs"),
14e7ffcc 1145 REJECT_INVALID, "bad-txns-inputs-duplicate");
33208fb5
MC
1146 vInOutPoints.insert(txin.prevout);
1147 }
1148
b7e4abd6 1149 // Check for duplicate joinsplit nullifiers in this transaction
69761d82 1150 {
66798551
SB
1151 set<uint256> vJoinSplitNullifiers;
1152 BOOST_FOREACH(const JSDescription& joinsplit, tx.vjoinsplit)
1153 {
1154 BOOST_FOREACH(const uint256& nf, joinsplit.nullifiers)
1155 {
1156 if (vJoinSplitNullifiers.count(nf))
1157 return state.DoS(100, error("CheckTransaction(): duplicate nullifiers"),
1158 REJECT_INVALID, "bad-joinsplits-nullifiers-duplicate");
1159
1160 vJoinSplitNullifiers.insert(nf);
1161 }
1162 }
1163 }
1164
1165 // Check for duplicate sapling nullifiers in this transaction
1166 {
1167 set<uint256> vSaplingNullifiers;
1168 BOOST_FOREACH(const SpendDescription& spend_desc, tx.vShieldedSpend)
69761d82 1169 {
66798551 1170 if (vSaplingNullifiers.count(spend_desc.nullifier))
bfeaf004 1171 return state.DoS(100, error("CheckTransaction(): duplicate nullifiers"),
66798551 1172 REJECT_INVALID, "bad-spend-description-nullifiers-duplicate");
69761d82 1173
66798551 1174 vSaplingNullifiers.insert(spend_desc.nullifier);
69761d82
SB
1175 }
1176 }
1177
05df3fc6 1178 if (tx.IsCoinBase())
a790fa46 1179 {
b7e4abd6 1180 // There should be no joinsplits in a coinbase transaction
8675d94b 1181 if (tx.vjoinsplit.size() > 0)
b7e4abd6
SB
1182 return state.DoS(100, error("CheckTransaction(): coinbase has joinsplits"),
1183 REJECT_INVALID, "bad-cb-has-joinsplits");
69761d82 1184
81209825
EOW
1185 // A coinbase transaction cannot have spend descriptions or output descriptions
1186 if (tx.vShieldedSpend.size() > 0)
1187 return state.DoS(100, error("CheckTransaction(): coinbase has spend descriptions"),
1188 REJECT_INVALID, "bad-cb-has-spend-description");
1189 if (tx.vShieldedOutput.size() > 0)
1190 return state.DoS(100, error("CheckTransaction(): coinbase has output descriptions"),
1191 REJECT_INVALID, "bad-cb-has-output-description");
1192
05df3fc6 1193 if (tx.vin[0].scriptSig.size() < 2 || tx.vin[0].scriptSig.size() > 100)
5262fde0 1194 return state.DoS(100, error("CheckTransaction(): coinbase script size"),
14e7ffcc 1195 REJECT_INVALID, "bad-cb-length");
a790fa46 1196 }
1197 else
1198 {
05df3fc6 1199 BOOST_FOREACH(const CTxIn& txin, tx.vin)
a790fa46 1200 if (txin.prevout.IsNull())
5262fde0 1201 return state.DoS(10, error("CheckTransaction(): prevout is null"),
14e7ffcc 1202 REJECT_INVALID, "bad-txns-prevout-null");
a790fa46 1203 }
1204
1205 return true;
1206}
1207
a372168e 1208CAmount GetMinRelayFee(const CTransaction& tx, unsigned int nBytes, bool fAllowFree)
76970091 1209{
2a72d459
LD
1210 {
1211 LOCK(mempool.cs);
805344dc 1212 uint256 hash = tx.GetHash();
2a72d459 1213 double dPriorityDelta = 0;
a372168e 1214 CAmount nFeeDelta = 0;
2a72d459
LD
1215 mempool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta);
1216 if (dPriorityDelta > 0 || nFeeDelta > 0)
1217 return 0;
1218 }
1219
a372168e 1220 CAmount nMinFee = ::minRelayTxFee.GetFee(nBytes);
76970091
JG
1221
1222 if (fAllowFree)
1223 {
87cce04c
MC
1224 // There is a free transaction area in blocks created by most miners,
1225 // * If we are relaying we allow transactions up to DEFAULT_BLOCK_PRIORITY_SIZE - 1000
16b3ff66
GA
1226 // to be considered to fall into this category. We don't want to encourage sending
1227 // multiple transactions instead of one big transaction to avoid fees.
b33d1f5e 1228 if (nBytes < (DEFAULT_BLOCK_PRIORITY_SIZE - 1000))
87cce04c 1229 nMinFee = 0;
76970091
JG
1230 }
1231
76970091
JG
1232 if (!MoneyRange(nMinFee))
1233 nMinFee = MAX_MONEY;
1234 return nMinFee;
1235}
1236
450cbb09 1237
319b1160 1238bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransaction &tx, bool fLimitFree,
1371e6f5 1239 bool* pfMissingInputs, bool fRejectAbsurdFee)
0a61b0df 1240{
e07c943c 1241 AssertLockHeld(cs_main);
0a61b0df 1242 if (pfMissingInputs)
1243 *pfMissingInputs = false;
1244
be126699
JG
1245 int nextBlockHeight = chainActive.Height() + 1;
1246 auto consensusBranchId = CurrentEpochBranchId(nextBlockHeight, Params().GetConsensus());
1247
da6d9391
S
1248 // Node operator can choose to reject tx by number of transparent inputs
1249 static_assert(std::numeric_limits<size_t>::max() >= std::numeric_limits<int64_t>::max(), "size_t too small");
1250 size_t limit = (size_t) GetArg("-mempooltxinputlimit", 0);
31afbcc5
JG
1251 if (NetworkUpgradeActive(nextBlockHeight, Params().GetConsensus(), Consensus::UPGRADE_OVERWINTER)) {
1252 limit = 0;
1253 }
da6d9391
S
1254 if (limit > 0) {
1255 size_t n = tx.vin.size();
1256 if (n > limit) {
1257 LogPrint("mempool", "Dropping txid %s : too many transparent inputs %zu > limit %zu\n", tx.GetHash().ToString(), n, limit );
1258 return false;
1259 }
1260 }
1261
6fb8d0c2
JG
1262 auto verifier = libzcash::ProofVerifier::Strict();
1263 if (!CheckTransaction(tx, state, verifier))
4f1ee565 1264 return error("AcceptToMemoryPool: CheckTransaction failed");
a790fa46 1265
072099d7
S
1266 // DoS level set to 10 to be more forgiving.
1267 // Check transaction contextually against the set of consensus rules which apply in the next block to be mined.
072099d7
S
1268 if (!ContextualCheckTransaction(tx, state, nextBlockHeight, 10)) {
1269 return error("AcceptToMemoryPool: ContextualCheckTransaction failed");
1270 }
1271
0a61b0df 1272 // Coinbase is only valid in a block, not as a loose transaction
d01903e7 1273 if (tx.IsCoinBase())
4f1ee565 1274 return state.DoS(100, error("AcceptToMemoryPool: coinbase as individual tx"),
358ce266 1275 REJECT_INVALID, "coinbase");
f1e1fb4b 1276
d9ace8ab 1277 // Rather not work on nonstandard transactions (unless -testnet/-regtest)
980bfe6e 1278 string reason;
072099d7 1279 if (Params().RequireStandard() && !IsStandardTx(tx, reason, nextBlockHeight))
358ce266 1280 return state.DoS(0,
5262fde0 1281 error("AcceptToMemoryPool: nonstandard transaction: %s", reason),
358ce266 1282 REJECT_NONSTANDARD, reason);
97ee01ad 1283
0ea28bae
PT
1284 // Only accept nLockTime-using transactions that can be mined in the next
1285 // block; we don't want our mempool filled up with transactions that can't
1286 // be mined yet.
a1d3c6fb
MF
1287 if (!CheckFinalTx(tx, STANDARD_LOCKTIME_VERIFY_FLAGS))
1288 return state.DoS(0, false, REJECT_NONSTANDARD, "non-final");
0ea28bae 1289
450cbb09 1290 // is it already in the memory pool?
805344dc 1291 uint256 hash = tx.GetHash();
319b1160
GA
1292 if (pool.exists(hash))
1293 return false;
0a61b0df 1294
1295 // Check for conflicts with in-memory transactions
319b1160
GA
1296 {
1297 LOCK(pool.cs); // protect pool.mapNextTx
c23617fe 1298 for (unsigned int i = 0; i < tx.vin.size(); i++)
0a61b0df 1299 {
d01903e7 1300 COutPoint outpoint = tx.vin[i].prevout;
98e84aae 1301 if (pool.mapNextTx.count(outpoint))
0a61b0df 1302 {
98e84aae 1303 // Disable replacement feature for now
cd057bfd 1304 return false;
0a61b0df 1305 }
1306 }
b7e4abd6 1307 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
cc01120a 1308 BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
28d20bdb 1309 if (pool.nullifierExists(nf, SPROUT)) {
d66877af 1310 return false;
9669920f 1311 }
d66877af
SB
1312 }
1313 }
cab341e1 1314 for (const SpendDescription &spendDescription : tx.vShieldedSpend) {
28d20bdb 1315 if (pool.nullifierExists(spendDescription.nullifier, SAPLING)) {
cab341e1 1316 return false;
9669920f 1317 }
cab341e1 1318 }
319b1160 1319 }
0a61b0df 1320
0a61b0df 1321 {
4afc0b54 1322 CCoinsView dummy;
7c70438d 1323 CCoinsViewCache view(&dummy);
4afc0b54 1324
a372168e 1325 CAmount nValueIn = 0;
4afc0b54 1326 {
319b1160 1327 LOCK(pool.cs);
7c70438d 1328 CCoinsViewMemPool viewMemPool(pcoinsTip, pool);
4afc0b54 1329 view.SetBackend(viewMemPool);
450cbb09
PW
1330
1331 // do we already have it?
1332 if (view.HaveCoins(hash))
33a53bc1 1333 return false;
450cbb09
PW
1334
1335 // do all inputs exist?
c2ed184f 1336 // Note that this does not check for the presence of actual outputs (see the next check for that),
7e6d23b1 1337 // and only helps with filling in pfMissingInputs (to determine missing vs spent).
450cbb09
PW
1338 BOOST_FOREACH(const CTxIn txin, tx.vin) {
1339 if (!view.HaveCoins(txin.prevout.hash)) {
1340 if (pfMissingInputs)
1341 *pfMissingInputs = true;
1342 return false;
1343 }
e679ec96
GA
1344 }
1345
c2ed184f 1346 // are the actual inputs available?
05df3fc6 1347 if (!view.HaveInputs(tx))
5262fde0 1348 return state.Invalid(error("AcceptToMemoryPool: inputs already spent"),
14e7ffcc 1349 REJECT_DUPLICATE, "bad-txns-inputs-spent");
13e5cce4 1350
b7e4abd6 1351 // are the joinsplit's requirements met?
ee964faf 1352 if (!view.HaveJoinSplitRequirements(tx))
b7e4abd6
SB
1353 return state.Invalid(error("AcceptToMemoryPool: joinsplit requirements not met"),
1354 REJECT_DUPLICATE, "bad-txns-joinsplit-requirements-not-met");
a8ac403d 1355
4afc0b54
PW
1356 // Bring the best block into scope
1357 view.GetBestBlock();
1358
171ca774
GA
1359 nValueIn = view.GetValueIn(tx);
1360
4afc0b54
PW
1361 // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
1362 view.SetBackend(dummy);
1363 }
13c51f20 1364
922e8e29 1365 // Check for non-standard pay-to-script-hash in inputs
be126699 1366 if (Params().RequireStandard() && !AreInputsStandard(tx, view, consensusBranchId))
4f1ee565 1367 return error("AcceptToMemoryPool: nonstandard transaction input");
e679ec96 1368
9ee09dc6
PT
1369 // Check that the transaction doesn't have an excessive number of
1370 // sigops, making it impossible to mine. Since the coinbase transaction
23f34359 1371 // itself can contain sigops MAX_STANDARD_TX_SIGOPS is less than
9ee09dc6
PT
1372 // MAX_BLOCK_SIGOPS; we still consider this an invalid rather than
1373 // merely non-standard transaction.
1374 unsigned int nSigOps = GetLegacySigOpCount(tx);
1375 nSigOps += GetP2SHSigOpCount(tx, view);
23f34359 1376 if (nSigOps > MAX_STANDARD_TX_SIGOPS)
9ee09dc6 1377 return state.DoS(0,
5262fde0 1378 error("AcceptToMemoryPool: too many sigops %s, %d > %d",
23f34359 1379 hash.ToString(), nSigOps, MAX_STANDARD_TX_SIGOPS),
9ee09dc6 1380 REJECT_NONSTANDARD, "bad-txns-too-many-sigops");
137d0685 1381
a372168e
MF
1382 CAmount nValueOut = tx.GetValueOut();
1383 CAmount nFees = nValueIn-nValueOut;
4d707d51
GA
1384 double dPriority = view.GetPriority(tx, chainActive.Height());
1385
a4b25180
SD
1386 // Keep track of transactions that spend a coinbase, which we re-scan
1387 // during reorgs to ensure COINBASE_MATURITY is still met.
1388 bool fSpendsCoinbase = false;
1389 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
1390 const CCoins *coins = view.AccessCoins(txin.prevout.hash);
1391 if (coins->IsCoinBase()) {
1392 fSpendsCoinbase = true;
1393 break;
1394 }
1395 }
1396
34a64fe0
JG
1397 // Grab the branch ID we expect this transaction to commit to. We don't
1398 // yet know if it does, but if the entry gets added to the mempool, then
1399 // it has passed ContextualCheckInputs and therefore this is correct.
1400 auto consensusBranchId = CurrentEpochBranchId(chainActive.Height() + 1, Params().GetConsensus());
1401
1402 CTxMemPoolEntry entry(tx, nFees, GetTime(), dPriority, chainActive.Height(), mempool.HasNoInputsOf(tx), fSpendsCoinbase, consensusBranchId);
4d707d51 1403 unsigned int nSize = entry.GetTxSize();
8d7849b6 1404
9ddb6ad0
S
1405 // Accept a tx if it contains joinsplits and has at least the default fee specified by z_sendmany.
1406 if (tx.vjoinsplit.size() > 0 && nFees >= ASYNC_RPC_OPERATION_DEFAULT_MINERS_FEE) {
1407 // In future we will we have more accurate and dynamic computation of fees for tx with joinsplits.
1408 } else {
1409 // Don't accept it if it can't get into a block
1410 CAmount txMinFee = GetMinRelayFee(tx, nSize, true);
1411 if (fLimitFree && nFees < txMinFee)
1412 return state.DoS(0, error("AcceptToMemoryPool: not enough fees %s, %d < %d",
1413 hash.ToString(), nFees, txMinFee),
1414 REJECT_INSUFFICIENTFEE, "insufficient fee");
1415 }
922e8e29 1416
1c52aad5 1417 // Require that free transactions have sufficient priority to be mined in the next block.
a5150a15 1418 if (GetBoolArg("-relaypriority", false) && nFees < ::minRelayTxFee.GetFee(nSize) && !AllowFree(view.GetPriority(tx, chainActive.Height() + 1))) {
1c52aad5
PW
1419 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "insufficient priority");
1420 }
1421
bf7835c2 1422 // Continuously rate-limit free (really, very-low-fee) transactions
88abf703 1423 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
b49f1398 1424 // be annoying or make others' transactions take longer to confirm.
13fc83c7 1425 if (fLimitFree && nFees < ::minRelayTxFee.GetFee(nSize))
97ee01ad 1426 {
98e84aae 1427 static CCriticalSection csFreeLimiter;
5de8b54c 1428 static double dFreeCount;
98e84aae
WL
1429 static int64_t nLastTime;
1430 int64_t nNow = GetTime();
1431
1432 LOCK(csFreeLimiter);
ce99358f 1433
98e84aae
WL
1434 // Use an exponentially decaying ~10-minute window:
1435 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
1436 nLastTime = nNow;
1437 // -limitfreerelay unit is thousand-bytes-per-minute
1438 // At default rate it would take over a month to fill 1GB
1439 if (dFreeCount >= GetArg("-limitfreerelay", 15)*10*1000)
5262fde0 1440 return state.DoS(0, error("AcceptToMemoryPool: free transaction rejected by rate limiter"),
1c52aad5 1441 REJECT_INSUFFICIENTFEE, "rate limited free transaction");
319b1160 1442 LogPrint("mempool", "Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
98e84aae 1443 dFreeCount += nSize;
97ee01ad 1444 }
8d7849b6 1445
8b15afd3
S
1446 if (fRejectAbsurdFee && nFees > ::minRelayTxFee.GetFee(nSize) * 10000) {
1447 string errmsg = strprintf("absurdly high fees %s, %d > %d",
1448 hash.ToString(),
1449 nFees, ::minRelayTxFee.GetFee(nSize) * 10000);
1450 LogPrint("mempool", errmsg.c_str());
1451 return state.Error("AcceptToMemoryPool: " + errmsg);
1452 }
9d14e689 1453
8d7849b6
GA
1454 // Check against previous transactions
1455 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
6514771a 1456 PrecomputedTransactionData txdata(tx);
be126699 1457 if (!ContextualCheckInputs(tx, state, view, true, STANDARD_SCRIPT_VERIFY_FLAGS, true, txdata, Params().GetConsensus(), consensusBranchId))
8d7849b6 1458 {
bf7835c2 1459 return error("AcceptToMemoryPool: ConnectInputs failed %s", hash.ToString());
8d7849b6 1460 }
7c041b3b
PT
1461
1462 // Check again against just the consensus-critical mandatory script
1463 // verification flags, in case of bugs in the standard flags that cause
1464 // transactions to pass as valid when they're actually invalid. For
1465 // instance the STRICTENC flag was incorrectly allowing certain
1466 // CHECKSIG NOT scripts to pass, even though they were invalid.
1467 //
1468 // There is a similar check in CreateNewBlock() to prevent creating
1469 // invalid blocks, however allowing such transactions into the mempool
1470 // can be exploited as a DoS attack.
be126699 1471 if (!ContextualCheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, txdata, Params().GetConsensus(), consensusBranchId))
7c041b3b 1472 {
4f1ee565 1473 return error("AcceptToMemoryPool: BUG! PLEASE REPORT THIS! ConnectInputs failed against MANDATORY but not STANDARD flags %s", hash.ToString());
7c041b3b
PT
1474 }
1475
cd057bfd 1476 // Store transaction in memory
b649e039 1477 pool.addUnchecked(hash, entry, !IsInitialBlockDownload());
d640a3ce
TH
1478 }
1479
0d27dad8 1480 SyncWithWallets(tx, NULL);
d640a3ce 1481
cd057bfd 1482 return true;
d640a3ce
TH
1483}
1484
c5b390b6 1485/** Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock */
450cbb09 1486bool GetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock, bool fAllowSlow)
c73ba23e 1487{
450cbb09 1488 CBlockIndex *pindexSlow = NULL;
01878c9c
AM
1489
1490 LOCK(cs_main);
1491
1492 if (mempool.lookup(hash, txOut))
c73ba23e 1493 {
01878c9c
AM
1494 return true;
1495 }
450cbb09 1496
01878c9c
AM
1497 if (fTxIndex) {
1498 CDiskTxPos postx;
1499 if (pblocktree->ReadTxIndex(hash, postx)) {
1500 CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);
1501 if (file.IsNull())
1502 return error("%s: OpenBlockFile failed", __func__);
1503 CBlockHeader header;
1504 try {
1505 file >> header;
1506 fseek(file.Get(), postx.nTxOffset, SEEK_CUR);
1507 file >> txOut;
1508 } catch (const std::exception& e) {
1509 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
2d1fa42e 1510 }
01878c9c 1511 hashBlock = header.GetHash();
805344dc 1512 if (txOut.GetHash() != hash)
01878c9c
AM
1513 return error("%s: txid mismatch", __func__);
1514 return true;
2d1fa42e 1515 }
01878c9c 1516 }
2d1fa42e 1517
01878c9c
AM
1518 if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
1519 int nHeight = -1;
1520 {
1521 CCoinsViewCache &view = *pcoinsTip;
1522 const CCoins* coins = view.AccessCoins(hash);
1523 if (coins)
1524 nHeight = coins->nHeight;
c73ba23e 1525 }
01878c9c
AM
1526 if (nHeight > 0)
1527 pindexSlow = chainActive[nHeight];
c73ba23e 1528 }
0a61b0df 1529
450cbb09
PW
1530 if (pindexSlow) {
1531 CBlock block;
7db120d5 1532 if (ReadBlockFromDisk(block, pindexSlow)) {
450cbb09 1533 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
805344dc 1534 if (tx.GetHash() == hash) {
450cbb09
PW
1535 txOut = tx;
1536 hashBlock = pindexSlow->GetBlockHash();
1537 return true;
1538 }
1539 }
1540 }
1541 }
0a61b0df 1542
450cbb09
PW
1543 return false;
1544}
0a61b0df 1545
1546
1547
1548
1549
1550
1551//////////////////////////////////////////////////////////////////////////////
1552//
1553// CBlock and CBlockIndex
1554//
1555
e6973430 1556bool WriteBlockToDisk(CBlock& block, CDiskBlockPos& pos, const CMessageHeader::MessageStartChars& messageStart)
226f8219
EL
1557{
1558 // Open history file to append
eee030f6 1559 CAutoFile fileout(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
fef24cab 1560 if (fileout.IsNull())
5262fde0 1561 return error("WriteBlockToDisk: OpenBlockFile failed");
226f8219
EL
1562
1563 // Write index header
b8a65793 1564 unsigned int nSize = GetSerializeSize(fileout, block);
e6973430 1565 fileout << FLATDATA(messageStart) << nSize;
226f8219
EL
1566
1567 // Write block
a8738238 1568 long fileOutPos = ftell(fileout.Get());
226f8219 1569 if (fileOutPos < 0)
5262fde0 1570 return error("WriteBlockToDisk: ftell failed");
226f8219
EL
1571 pos.nPos = (unsigned int)fileOutPos;
1572 fileout << block;
1573
226f8219
EL
1574 return true;
1575}
1576
80313994
EL
1577bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos)
1578{
1579 block.SetNull();
1580
1581 // Open history file to read
eee030f6 1582 CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
fef24cab 1583 if (filein.IsNull())
f5791c6a 1584 return error("ReadBlockFromDisk: OpenBlockFile failed for %s", pos.ToString());
80313994
EL
1585
1586 // Read block
1587 try {
1588 filein >> block;
1589 }
27df4123 1590 catch (const std::exception& e) {
f5791c6a 1591 return error("%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.ToString());
80313994
EL
1592 }
1593
1594 // Check the header
fdda3c50
JG
1595 if (!(CheckEquihashSolution(&block, Params()) &&
1596 CheckProofOfWork(block.GetHash(), block.nBits, Params().GetConsensus())))
f5791c6a 1597 return error("ReadBlockFromDisk: Errors in block header at %s", pos.ToString());
80313994
EL
1598
1599 return true;
1600}
1601
7db120d5 1602bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex)
0a61b0df 1603{
7db120d5 1604 if (!ReadBlockFromDisk(block, pindex->GetBlockPos()))
0a61b0df 1605 return false;
7db120d5 1606 if (block.GetHash() != pindex->GetBlockHash())
f5791c6a
WL
1607 return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s",
1608 pindex->ToString(), pindex->GetBlockPos().ToString());
0a61b0df 1609 return true;
1610}
1611
935bd0a4 1612CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams)
0a61b0df 1613{
45e3deea 1614 CAmount nSubsidy = 12.5 * COIN;
bcb34c08
JG
1615
1616 // Mining slow start
1617 // The subsidy is ramped up linearly, skipping the middle payout of
1618 // MAX_SUBSIDY/2 to keep the monetary curve consistent with no slow start.
1619 if (nHeight < consensusParams.nSubsidySlowStartInterval / 2) {
1620 nSubsidy /= consensusParams.nSubsidySlowStartInterval;
1621 nSubsidy *= nHeight;
1622 return nSubsidy;
1623 } else if (nHeight < consensusParams.nSubsidySlowStartInterval) {
1624 nSubsidy /= consensusParams.nSubsidySlowStartInterval;
1625 nSubsidy *= (nHeight+1);
1626 return nSubsidy;
1627 }
1628
1629 assert(nHeight > consensusParams.SubsidySlowStartShift());
1630 int halvings = (nHeight - consensusParams.SubsidySlowStartShift()) / consensusParams.nSubsidyHalvingInterval;
c5a9d2ca 1631 // Force block reward to zero when right shift is undefined.
1632 if (halvings >= 64)
935bd0a4 1633 return 0;
0a61b0df 1634
45e3deea 1635 // Subsidy is cut in half every 840,000 blocks which will occur approximately every 4 years.
c5a9d2ca 1636 nSubsidy >>= halvings;
935bd0a4 1637 return nSubsidy;
0a61b0df 1638}
1639
0a61b0df 1640bool IsInitialBlockDownload()
1641{
11982d36 1642 const CChainParams& chainParams = Params();
55a1db4f 1643 LOCK(cs_main);
a8cdaf5c
CF
1644 if (fImporting || fReindex)
1645 return true;
1646 if (fCheckpointsEnabled && chainActive.Height() < Checkpoints::GetTotalBlocksEstimate(chainParams.Checkpoints()))
0a61b0df 1647 return true;
9ec75c5e
RDP
1648 static bool lockIBDState = false;
1649 if (lockIBDState)
1650 return false;
1651 bool state = (chainActive.Height() < pindexBestHeader->nHeight - 24 * 6 ||
33d6825c 1652 pindexBestHeader->GetBlockTime() < GetTime() - chainParams.MaxTipAge());
9ec75c5e
RDP
1653 if (!state)
1654 lockIBDState = true;
1655 return state;
0a61b0df 1656}
1657
39d2e9e0
PG
1658static bool fLargeWorkForkFound = false;
1659static bool fLargeWorkInvalidChainFound = false;
1660static CBlockIndex *pindexBestForkTip = NULL;
1661static CBlockIndex *pindexBestForkBase = NULL;
b8585384
MC
1662
1663void CheckForkWarningConditions()
1664{
e07c943c 1665 AssertLockHeld(cs_main);
55ed3f14
MC
1666 // Before we get past initial download, we cannot reliably alert about forks
1667 // (we assume we don't get stuck on a fork before the last checkpoint)
1668 if (IsInitialBlockDownload())
1669 return;
1670
d4388ed5 1671 // If our best fork is no longer within 288 blocks (+/- 12 hours if no one mines it)
b8585384 1672 // of our head, drop it
d4388ed5 1673 if (pindexBestForkTip && chainActive.Height() - pindexBestForkTip->nHeight >= 288)
b8585384
MC
1674 pindexBestForkTip = NULL;
1675
092b58d1 1676 if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > chainActive.Tip()->nChainWork + (GetBlockProof(*chainActive.Tip()) * 6)))
b8585384 1677 {
730b1ed1 1678 if (!fLargeWorkForkFound && pindexBestForkBase)
f89faa25 1679 {
e01a7939
GA
1680 std::string warning = std::string("'Warning: Large-work fork detected, forking after block ") +
1681 pindexBestForkBase->phashBlock->ToString() + std::string("'");
1682 CAlert::Notify(warning, true);
f89faa25 1683 }
730b1ed1 1684 if (pindexBestForkTip && pindexBestForkBase)
f65e7092 1685 {
30c1db1c 1686 LogPrintf("%s: 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", __func__,
7d9d134b
WL
1687 pindexBestForkBase->nHeight, pindexBestForkBase->phashBlock->ToString(),
1688 pindexBestForkTip->nHeight, pindexBestForkTip->phashBlock->ToString());
f65e7092
MC
1689 fLargeWorkForkFound = true;
1690 }
1691 else
1692 {
57c074e1
TH
1693 std::string warning = std::string("Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.");
1694 LogPrintf("%s: %s\n", warning.c_str(), __func__);
1695 CAlert::Notify(warning, true);
f65e7092
MC
1696 fLargeWorkInvalidChainFound = true;
1697 }
1698 }
1699 else
1700 {
b8585384 1701 fLargeWorkForkFound = false;
f65e7092
MC
1702 fLargeWorkInvalidChainFound = false;
1703 }
b8585384
MC
1704}
1705
1706void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip)
1707{
e07c943c 1708 AssertLockHeld(cs_main);
b8585384
MC
1709 // If we are on a fork that is sufficiently large, set a warning flag
1710 CBlockIndex* pfork = pindexNewForkTip;
4c6d41b8 1711 CBlockIndex* plonger = chainActive.Tip();
b8585384
MC
1712 while (pfork && pfork != plonger)
1713 {
1714 while (plonger && plonger->nHeight > pfork->nHeight)
1715 plonger = plonger->pprev;
1716 if (pfork == plonger)
1717 break;
1718 pfork = pfork->pprev;
1719 }
1720
7e6d23b1 1721 // We define a condition where we should warn the user about as a fork of at least 7 blocks
4e3ac9b0 1722 // with a tip within 72 blocks (+/- 3 hours if no one mines it) of ours
b8585384
MC
1723 // We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network
1724 // hash rate operating on the fork.
1725 // or a chain that is entirely longer than ours and invalid (note that this should be detected by both)
1726 // We define it this way because it allows us to only store the highest fork tip (+ base) which meets
1727 // the 7-block condition and from this always have the most-likely-to-cause-warning fork
1728 if (pfork && (!pindexBestForkTip || (pindexBestForkTip && pindexNewForkTip->nHeight > pindexBestForkTip->nHeight)) &&
092b58d1 1729 pindexNewForkTip->nChainWork - pfork->nChainWork > (GetBlockProof(*pfork) * 7) &&
4c6d41b8 1730 chainActive.Height() - pindexNewForkTip->nHeight < 72)
b8585384
MC
1731 {
1732 pindexBestForkTip = pindexNewForkTip;
1733 pindexBestForkBase = pfork;
1734 }
1735
1736 CheckForkWarningConditions();
1737}
1738
f59d8f0b 1739// Requires cs_main.
75f51f2a
PW
1740void Misbehaving(NodeId pnode, int howmuch)
1741{
1742 if (howmuch == 0)
1743 return;
1744
1745 CNodeState *state = State(pnode);
1746 if (state == NULL)
1747 return;
1748
1749 state->nMisbehavior += howmuch;
dc942e6f
PW
1750 int banscore = GetArg("-banscore", 100);
1751 if (state->nMisbehavior >= banscore && state->nMisbehavior - howmuch < banscore)
75f51f2a 1752 {
30c1db1c 1753 LogPrintf("%s: %s (%d -> %d) BAN THRESHOLD EXCEEDED\n", __func__, state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
75f51f2a
PW
1754 state->fShouldBan = true;
1755 } else
30c1db1c 1756 LogPrintf("%s: %s (%d -> %d)\n", __func__, state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
75f51f2a
PW
1757}
1758
64c7ee7e 1759void static InvalidChainFound(CBlockIndex* pindexNew)
0a61b0df 1760{
85eb2cef 1761 if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
85eb2cef 1762 pindexBestInvalid = pindexNew;
beb36e80 1763
30c1db1c 1764 LogPrintf("%s: invalid block=%s height=%d log2_work=%.8g date=%s\n", __func__,
7d9d134b 1765 pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
1657c4bc 1766 log(pindexNew->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
7d9d134b 1767 pindexNew->GetBlockTime()));
4a374102
RN
1768 CBlockIndex *tip = chainActive.Tip();
1769 assert (tip);
30c1db1c 1770 LogPrintf("%s: current best=%s height=%d log2_work=%.8g date=%s\n", __func__,
4a374102
RN
1771 tip->GetBlockHash().ToString(), chainActive.Height(), log(tip->nChainWork.getdouble())/log(2.0),
1772 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", tip->GetBlockTime()));
b8585384 1773 CheckForkWarningConditions();
0a61b0df 1774}
1775
75f51f2a
PW
1776void static InvalidBlockFound(CBlockIndex *pindex, const CValidationState &state) {
1777 int nDoS = 0;
1778 if (state.IsInvalid(nDoS)) {
1779 std::map<uint256, NodeId>::iterator it = mapBlockSource.find(pindex->GetBlockHash());
1780 if (it != mapBlockSource.end() && State(it->second)) {
307f7d48 1781 CBlockReject reject = {state.GetRejectCode(), state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), pindex->GetBlockHash()};
75f51f2a
PW
1782 State(it->second)->rejects.push_back(reject);
1783 if (nDoS > 0)
1784 Misbehaving(it->second, nDoS);
857c61df 1785 }
75f51f2a
PW
1786 }
1787 if (!state.CorruptionPossible()) {
1788 pindex->nStatus |= BLOCK_FAILED_VALID;
51ce901a 1789 setDirtyBlockIndex.insert(pindex);
e17bd583 1790 setBlockIndexCandidates.erase(pindex);
75f51f2a
PW
1791 InvalidChainFound(pindex);
1792 }
857c61df
PW
1793}
1794
8cb98d91 1795void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, CTxUndo &txundo, int nHeight)
450cbb09 1796{
450cbb09 1797 // mark inputs spent
05df3fc6 1798 if (!tx.IsCoinBase()) {
ab15b2ec 1799 txundo.vprevout.reserve(tx.vin.size());
f28aec01 1800 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
c444c620 1801 CCoinsModifier coins = inputs.ModifyCoins(txin.prevout.hash);
1802 unsigned nPos = txin.prevout.n;
1803
1804 if (nPos >= coins->vout.size() || coins->vout[nPos].IsNull())
1805 assert(false);
1806 // mark an outpoint spent, and construct undo information
1807 txundo.vprevout.push_back(CTxInUndo(coins->vout[nPos]));
1808 coins->Spend(nPos);
1809 if (coins->vout.size() == 0) {
1810 CTxInUndo& undo = txundo.vprevout.back();
1811 undo.nHeight = coins->nHeight;
1812 undo.fCoinBase = coins->fCoinBase;
1813 undo.nVersion = coins->nVersion;
1814 }
450cbb09
PW
1815 }
1816 }
1817
bfeaf004 1818 // spend nullifiers
685e936c 1819 inputs.SetNullifiers(tx, true);
d66877af 1820
450cbb09 1821 // add outputs
805344dc 1822 inputs.ModifyCoins(tx.GetHash())->FromTx(tx, nHeight);
450cbb09
PW
1823}
1824
8cb98d91 1825void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, int nHeight)
d7621ccf 1826{
1827 CTxUndo txundo;
8cb98d91 1828 UpdateCoins(tx, inputs, txundo, nHeight);
d7621ccf 1829}
1830
307f7d48 1831bool CScriptCheck::operator()() {
2800ce73 1832 const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
be126699 1833 if (!VerifyScript(scriptSig, scriptPubKey, nFlags, CachingTransactionSignatureChecker(ptxTo, nIn, amount, cacheStore, *txdata), consensusBranchId, &error)) {
805344dc 1834 return ::error("CScriptCheck(): %s:%d VerifySignature failed: %s", ptxTo->GetHash().ToString(), nIn, ScriptErrorString(error));
307f7d48 1835 }
2800ce73
PW
1836 return true;
1837}
1838
e079f010 1839int GetSpendHeight(const CCoinsViewCache& inputs)
0a61b0df 1840{
e079f010
JT
1841 LOCK(cs_main);
1842 CBlockIndex* pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second;
1843 return pindexPrev->nHeight + 1;
1844}
f9cae832 1845
e079f010
JT
1846namespace Consensus {
1847bool CheckTxInputs(const CTransaction& tx, CValidationState& state, const CCoinsViewCache& inputs, int nSpendHeight, const Consensus::Params& consensusParams)
1848{
13c51f20
PW
1849 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1850 // for an attacker to attempt to split the network.
05df3fc6 1851 if (!inputs.HaveInputs(tx))
805344dc 1852 return state.Invalid(error("CheckInputs(): %s inputs unavailable", tx.GetHash().ToString()));
13c51f20 1853
b7e4abd6 1854 // are the JoinSplit's requirements met?
ee964faf 1855 if (!inputs.HaveJoinSplitRequirements(tx))
805344dc 1856 return state.Invalid(error("CheckInputs(): %s JoinSplit requirements not met", tx.GetHash().ToString()));
a8ac403d 1857
a372168e
MF
1858 CAmount nValueIn = 0;
1859 CAmount nFees = 0;
05df3fc6 1860 for (unsigned int i = 0; i < tx.vin.size(); i++)
0a61b0df 1861 {
05df3fc6 1862 const COutPoint &prevout = tx.vin[i].prevout;
629d75fa
PW
1863 const CCoins *coins = inputs.AccessCoins(prevout.hash);
1864 assert(coins);
0a61b0df 1865
629d75fa 1866 if (coins->IsCoinBase()) {
e079f010
JT
1867 // Ensure that coinbases are matured
1868 if (nSpendHeight - coins->nHeight < COINBASE_MATURITY) {
1869 return state.Invalid(
1870 error("CheckInputs(): tried to spend coinbase at depth %d", nSpendHeight - coins->nHeight),
1871 REJECT_INVALID, "bad-txns-premature-spend-of-coinbase");
1872 }
1873
1d38795f 1874 // Ensure that coinbases cannot be spent to transparent outputs
c0dde76d 1875 // Disabled on regtest
d212ba32
SB
1876 if (fCoinbaseEnforcedProtectionEnabled &&
1877 consensusParams.fCoinbaseMustBeProtected &&
1878 !tx.vout.empty()) {
358ce266 1879 return state.Invalid(
1d38795f
SB
1880 error("CheckInputs(): tried to spend coinbase with transparent outputs"),
1881 REJECT_INVALID, "bad-txns-coinbase-spend-has-transparent-outputs");
1882 }
450cbb09 1883 }
0a61b0df 1884
4add41a2 1885 // Check for negative or overflow input values
629d75fa
PW
1886 nValueIn += coins->vout[prevout.n].nValue;
1887 if (!MoneyRange(coins->vout[prevout.n].nValue) || !MoneyRange(nValueIn))
5262fde0 1888 return state.DoS(100, error("CheckInputs(): txin values out of range"),
14e7ffcc 1889 REJECT_INVALID, "bad-txns-inputvalues-outofrange");
4add41a2
GA
1890
1891 }
450cbb09 1892
942bc467 1893 nValueIn += tx.GetJoinSplitValueIn();
f512cf7c
SB
1894 if (!MoneyRange(nValueIn))
1895 return state.DoS(100, error("CheckInputs(): vpub_old values out of range"),
1896 REJECT_INVALID, "bad-txns-inputvalues-outofrange");
1897
0733c1bd 1898 if (nValueIn < tx.GetValueOut())
5262fde0 1899 return state.DoS(100, error("CheckInputs(): %s value in (%s) < value out (%s)",
805344dc 1900 tx.GetHash().ToString(), FormatMoney(nValueIn), FormatMoney(tx.GetValueOut())),
14e7ffcc 1901 REJECT_INVALID, "bad-txns-in-belowout");
450cbb09
PW
1902
1903 // Tally transaction fees
a372168e 1904 CAmount nTxFee = nValueIn - tx.GetValueOut();
450cbb09 1905 if (nTxFee < 0)
805344dc 1906 return state.DoS(100, error("CheckInputs(): %s nTxFee < 0", tx.GetHash().ToString()),
14e7ffcc 1907 REJECT_INVALID, "bad-txns-fee-negative");
450cbb09
PW
1908 nFees += nTxFee;
1909 if (!MoneyRange(nFees))
5262fde0 1910 return state.DoS(100, error("CheckInputs(): nFees out of range"),
14e7ffcc 1911 REJECT_INVALID, "bad-txns-fee-outofrange");
e079f010
JT
1912 return true;
1913}
1914}// namespace Consensus
1915
d55e5e77
JG
1916bool ContextualCheckInputs(
1917 const CTransaction& tx,
1918 CValidationState &state,
1919 const CCoinsViewCache &inputs,
1920 bool fScriptChecks,
1921 unsigned int flags,
1922 bool cacheStore,
1923 PrecomputedTransactionData& txdata,
1924 const Consensus::Params& consensusParams,
1925 uint32_t consensusBranchId,
1926 std::vector<CScriptCheck> *pvChecks)
e079f010 1927{
e079f010
JT
1928 if (!tx.IsCoinBase())
1929 {
30006a2e
JG
1930 if (!Consensus::CheckTxInputs(tx, state, inputs, GetSpendHeight(inputs), consensusParams)) {
1931 return false;
1932 }
1933
e079f010
JT
1934 if (pvChecks)
1935 pvChecks->reserve(tx.vin.size());
450cbb09 1936
4add41a2
GA
1937 // The first loop above does all the inexpensive checks.
1938 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1939 // Helps prevent CPU exhaustion attacks.
4add41a2 1940
450cbb09 1941 // Skip ECDSA signature verification when connecting blocks
729b1806 1942 // before the last block chain checkpoint. This is safe because block merkle hashes are
450cbb09 1943 // still computed and checked, and any change will be caught at the next checkpoint.
1d70f4bd 1944 if (fScriptChecks) {
05df3fc6
EL
1945 for (unsigned int i = 0; i < tx.vin.size(); i++) {
1946 const COutPoint &prevout = tx.vin[i].prevout;
629d75fa
PW
1947 const CCoins* coins = inputs.AccessCoins(prevout.hash);
1948 assert(coins);
8d7849b6 1949
b14bd4df 1950 // Verify signature
be126699 1951 CScriptCheck check(*coins, tx, i, flags, cacheStore, consensusBranchId, &txdata);
f9cae832
PW
1952 if (pvChecks) {
1953 pvChecks->push_back(CScriptCheck());
1954 check.swap(pvChecks->back());
97e7901a 1955 } else if (!check()) {
f80cffa2
PT
1956 if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
1957 // Check whether the failure was caused by a
1958 // non-mandatory script verification check, such as
1959 // non-standard DER encodings or non-null dummy
1960 // arguments; if so, don't trigger DoS protection to
1961 // avoid splitting the network between upgraded and
1962 // non-upgraded nodes.
838e7a29 1963 CScriptCheck check2(*coins, tx, i,
be126699 1964 flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheStore, consensusBranchId, &txdata);
838e7a29 1965 if (check2())
307f7d48 1966 return state.Invalid(false, REJECT_NONSTANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError())));
97e7901a 1967 }
f80cffa2
PT
1968 // Failures of other flags indicate a transaction that is
1969 // invalid in new blocks, e.g. a invalid P2SH. We DoS ban
1970 // such nodes as they are not following the protocol. That
1971 // said during an upgrade careful thought should be taken
1972 // as to the correct behavior - we may want to continue
1973 // peering with non-upgraded nodes even after a soft-fork
1974 // super-majority vote has passed.
307f7d48 1975 return state.DoS(100,false, REJECT_INVALID, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check.GetScriptError())));
97e7901a 1976 }
2a45a494 1977 }
0a61b0df 1978 }
0a61b0df 1979 }
1980
0a61b0df 1981 return true;
1982}
1983
87fb3108 1984namespace {
1985
e6973430 1986bool UndoWriteToDisk(const CBlockUndo& blockundo, CDiskBlockPos& pos, const uint256& hashBlock, const CMessageHeader::MessageStartChars& messageStart)
87fb3108 1987{
1988 // Open history file to append
1989 CAutoFile fileout(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
1990 if (fileout.IsNull())
5262fde0 1991 return error("%s: OpenUndoFile failed", __func__);
87fb3108 1992
1993 // Write index header
b8a65793 1994 unsigned int nSize = GetSerializeSize(fileout, blockundo);
e6973430 1995 fileout << FLATDATA(messageStart) << nSize;
87fb3108 1996
1997 // Write undo data
1998 long fileOutPos = ftell(fileout.Get());
1999 if (fileOutPos < 0)
5262fde0 2000 return error("%s: ftell failed", __func__);
87fb3108 2001 pos.nPos = (unsigned int)fileOutPos;
2002 fileout << blockundo;
2003
2004 // calculate & write checksum
2005 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
2006 hasher << hashBlock;
2007 hasher << blockundo;
2008 fileout << hasher.GetHash();
2009
2010 return true;
2011}
2012
2013bool UndoReadFromDisk(CBlockUndo& blockundo, const CDiskBlockPos& pos, const uint256& hashBlock)
2014{
2015 // Open history file to read
2016 CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
2017 if (filein.IsNull())
5262fde0 2018 return error("%s: OpenBlockFile failed", __func__);
87fb3108 2019
2020 // Read block
2021 uint256 hashChecksum;
2022 try {
2023 filein >> blockundo;
2024 filein >> hashChecksum;
2025 }
2026 catch (const std::exception& e) {
5262fde0 2027 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
87fb3108 2028 }
2029
2030 // Verify checksum
2031 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
2032 hasher << hashBlock;
2033 hasher << blockundo;
2034 if (hashChecksum != hasher.GetHash())
5262fde0 2035 return error("%s: Checksum mismatch", __func__);
87fb3108 2036
2037 return true;
2038}
2039
27afcd89
CF
2040/** Abort with a message */
2041bool AbortNode(const std::string& strMessage, const std::string& userMessage="")
2042{
2043 strMiscWarning = strMessage;
2044 LogPrintf("*** %s\n", strMessage);
2045 uiInterface.ThreadSafeMessageBox(
45bfa137 2046 userMessage.empty() ? _("Error: A fatal internal error occurred, see debug.log for details") : userMessage,
27afcd89
CF
2047 "", CClientUIInterface::MSG_ERROR);
2048 StartShutdown();
2049 return false;
2050}
2051
2052bool AbortNode(CValidationState& state, const std::string& strMessage, const std::string& userMessage="")
2053{
2054 AbortNode(strMessage, userMessage);
2055 return state.Error(strMessage);
2056}
2057
87fb3108 2058} // anon namespace
0a61b0df 2059
eb1c2cd3
DK
2060/**
2061 * Apply the undo operation of a CTxInUndo to the given chain state.
2062 * @param undo The undo object.
2063 * @param view The coins view to which to apply the changes.
2064 * @param out The out point that corresponds to the tx input.
2065 * @return True on success.
2066 */
2067static bool ApplyTxInUndo(const CTxInUndo& undo, CCoinsViewCache& view, const COutPoint& out)
2068{
2069 bool fClean = true;
2070
2071 CCoinsModifier coins = view.ModifyCoins(out.hash);
2072 if (undo.nHeight != 0) {
2073 // undo data contains height: this is the last output of the prevout tx being spent
2074 if (!coins->IsPruned())
2075 fClean = fClean && error("%s: undo data overwriting existing transaction", __func__);
2076 coins->Clear();
2077 coins->fCoinBase = undo.fCoinBase;
2078 coins->nHeight = undo.nHeight;
2079 coins->nVersion = undo.nVersion;
2080 } else {
2081 if (coins->IsPruned())
2082 fClean = fClean && error("%s: undo data adding output to missing transaction", __func__);
2083 }
2084 if (coins->IsAvailable(out.n))
2085 fClean = fClean && error("%s: undo data overwriting existing output", __func__);
2086 if (coins->vout.size() < out.n+1)
2087 coins->vout.resize(out.n+1);
2088 coins->vout[out.n] = undo.txout;
2089
2090 return fClean;
2091}
2092
5c363ed6 2093bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool* pfClean)
0a61b0df 2094{
84674082 2095 assert(pindex->GetBlockHash() == view.GetBestBlock());
0a61b0df 2096
2cbd71da
PW
2097 if (pfClean)
2098 *pfClean = false;
2099
2100 bool fClean = true;
2101
450cbb09 2102 CBlockUndo blockUndo;
8539361e
PW
2103 CDiskBlockPos pos = pindex->GetUndoPos();
2104 if (pos.IsNull())
5262fde0 2105 return error("DisconnectBlock(): no undo data available");
e035c6a7 2106 if (!UndoReadFromDisk(blockUndo, pos, pindex->pprev->GetBlockHash()))
5262fde0 2107 return error("DisconnectBlock(): failure reading undo data");
0a61b0df 2108
5c363ed6 2109 if (blockUndo.vtxundo.size() + 1 != block.vtx.size())
5262fde0 2110 return error("DisconnectBlock(): block and undo data inconsistent");
450cbb09
PW
2111
2112 // undo transactions in reverse order
5c363ed6
EL
2113 for (int i = block.vtx.size() - 1; i >= 0; i--) {
2114 const CTransaction &tx = block.vtx[i];
805344dc 2115 uint256 hash = tx.GetHash();
450cbb09 2116
170e02de 2117 // Check that all outputs are available and match the outputs in the block itself
eb1c2cd3 2118 // exactly.
f28aec01 2119 {
f28aec01
PW
2120 CCoinsModifier outs = view.ModifyCoins(hash);
2121 outs->ClearUnspendable();
450cbb09 2122
f28aec01 2123 CCoins outsBlock(tx, pindex->nHeight);
f8b7aa86
GM
2124 // The CCoins serialization does not serialize negative numbers.
2125 // No network rules currently depend on the version here, so an inconsistency is harmless
2126 // but it must be corrected before txout nversion ever influences a network rule.
2127 if (outsBlock.nVersion < 0)
f28aec01
PW
2128 outs->nVersion = outsBlock.nVersion;
2129 if (*outs != outsBlock)
5262fde0 2130 fClean = fClean && error("DisconnectBlock(): added transaction mismatch? database corrupted");
450cbb09
PW
2131
2132 // remove outputs
f28aec01
PW
2133 outs->Clear();
2134 }
450cbb09 2135
bfeaf004 2136 // unspend nullifiers
685e936c 2137 view.SetNullifiers(tx, false);
d66877af 2138
450cbb09
PW
2139 // restore inputs
2140 if (i > 0) { // not coinbases
2141 const CTxUndo &txundo = blockUndo.vtxundo[i-1];
2cbd71da 2142 if (txundo.vprevout.size() != tx.vin.size())
5262fde0 2143 return error("DisconnectBlock(): transaction and undo data inconsistent");
450cbb09
PW
2144 for (unsigned int j = tx.vin.size(); j-- > 0;) {
2145 const COutPoint &out = tx.vin[j].prevout;
2146 const CTxInUndo &undo = txundo.vprevout[j];
eb1c2cd3
DK
2147 if (!ApplyTxInUndo(undo, view, out))
2148 fClean = false;
450cbb09
PW
2149 }
2150 }
2151 }
2152
1f8be05b
SB
2153 // set the old best Sprout anchor back
2154 view.PopAnchor(blockUndo.old_sprout_tree_root, SPROUT);
2155
2156 // set the old best Sapling anchor back
2157 // We can get this from the `hashFinalSaplingRoot` of the last block
2158 // However, this is only reliable if the last block was on or after
2159 // the Sapling activation height. Otherwise, the last anchor was the
2160 // empty root.
2161 if (NetworkUpgradeActive(pindex->pprev->nHeight, Params().GetConsensus(), Consensus::UPGRADE_SAPLING)) {
2162 view.PopAnchor(pindex->pprev->hashFinalSaplingRoot, SAPLING);
2163 } else {
2164 view.PopAnchor(ZCSaplingIncrementalMerkleTree::empty_root(), SAPLING);
2165 }
a8ac403d 2166
450cbb09 2167 // move best block pointer to prevout block
84674082 2168 view.SetBestBlock(pindex->pprev->GetBlockHash());
450cbb09 2169
2cbd71da
PW
2170 if (pfClean) {
2171 *pfClean = fClean;
2172 return true;
2cbd71da 2173 }
eb1c2cd3
DK
2174
2175 return fClean;
0a61b0df 2176}
2177
1eb57879 2178void static FlushBlockFile(bool fFinalize = false)
44d40f26
PW
2179{
2180 LOCK(cs_LastBlockFile);
2181
a8a4b967 2182 CDiskBlockPos posOld(nLastBlockFile, 0);
44d40f26
PW
2183
2184 FILE *fileOld = OpenBlockFile(posOld);
b19388dd 2185 if (fileOld) {
1eb57879 2186 if (fFinalize)
ed6d1a2c 2187 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nSize);
b19388dd
PK
2188 FileCommit(fileOld);
2189 fclose(fileOld);
2190 }
44d40f26
PW
2191
2192 fileOld = OpenUndoFile(posOld);
b19388dd 2193 if (fileOld) {
1eb57879 2194 if (fFinalize)
ed6d1a2c 2195 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nUndoSize);
b19388dd
PK
2196 FileCommit(fileOld);
2197 fclose(fileOld);
2198 }
44d40f26
PW
2199}
2200
ef3988ca 2201bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
5382bcf8 2202
f9cae832
PW
2203static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
2204
21eb5ada 2205void ThreadScriptCheck() {
7662d72b 2206 RenameThread("zcash-scriptch");
f9cae832 2207 scriptcheckqueue.Thread();
f9cae832
PW
2208}
2209
36cba8f1
GA
2210//
2211// Called periodically asynchronously; alerts if it smells like
2212// we're being fed a bad chain (blocks being generated much
2213// too slowly or too quickly).
2214//
fce474c9
GA
2215void PartitionCheck(bool (*initialDownloadCheck)(), CCriticalSection& cs, const CBlockIndex *const &bestHeader,
2216 int64_t nPowTargetSpacing)
36cba8f1 2217{
fce474c9 2218 if (bestHeader == NULL || initialDownloadCheck()) return;
36cba8f1
GA
2219
2220 static int64_t lastAlertTime = 0;
2221 int64_t now = GetAdjustedTime();
2222 if (lastAlertTime > now-60*60*24) return; // Alert at most once per day
2223
2224 const int SPAN_HOURS=4;
2225 const int SPAN_SECONDS=SPAN_HOURS*60*60;
2226 int BLOCKS_EXPECTED = SPAN_SECONDS / nPowTargetSpacing;
2227
2228 boost::math::poisson_distribution<double> poisson(BLOCKS_EXPECTED);
2229
2230 std::string strWarning;
2231 int64_t startTime = GetAdjustedTime()-SPAN_SECONDS;
2232
2233 LOCK(cs);
fce474c9
GA
2234 const CBlockIndex* i = bestHeader;
2235 int nBlocks = 0;
2236 while (i->GetBlockTime() >= startTime) {
2237 ++nBlocks;
2238 i = i->pprev;
c938fb1f 2239 if (i == NULL) return; // Ran out of chain, we must not be fully synced
fce474c9 2240 }
36cba8f1
GA
2241
2242 // How likely is it to find that many by chance?
2243 double p = boost::math::pdf(poisson, nBlocks);
2244
2245 LogPrint("partitioncheck", "%s : Found %d blocks in the last %d hours\n", __func__, nBlocks, SPAN_HOURS);
2246 LogPrint("partitioncheck", "%s : likelihood: %g\n", __func__, p);
2247
2248 // Aim for one false-positive about every fifty years of normal running:
2249 const int FIFTY_YEARS = 50*365*24*60*60;
2250 double alertThreshold = 1.0 / (FIFTY_YEARS / SPAN_SECONDS);
2251
2252 if (p <= alertThreshold && nBlocks < BLOCKS_EXPECTED)
2253 {
2254 // Many fewer blocks than expected: alert!
2255 strWarning = strprintf(_("WARNING: check your network connection, %d blocks received in the last %d hours (%d expected)"),
2256 nBlocks, SPAN_HOURS, BLOCKS_EXPECTED);
2257 }
2258 else if (p <= alertThreshold && nBlocks > BLOCKS_EXPECTED)
2259 {
2260 // Many more blocks than expected: alert!
2261 strWarning = strprintf(_("WARNING: abnormally high number of blocks generated, %d blocks received in the last %d hours (%d expected)"),
2262 nBlocks, SPAN_HOURS, BLOCKS_EXPECTED);
2263 }
2264 if (!strWarning.empty())
2265 {
2266 strMiscWarning = strWarning;
2267 CAlert::Notify(strWarning, true);
2268 lastAlertTime = now;
2269 }
2270}
2271
d70bc52e
PW
2272static int64_t nTimeVerify = 0;
2273static int64_t nTimeConnect = 0;
2274static int64_t nTimeIndex = 0;
2275static int64_t nTimeCallbacks = 0;
2276static int64_t nTimeTotal = 0;
2277
df08a626 2278bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool fJustCheck)
0a61b0df 2279{
4e382177 2280 const CChainParams& chainparams = Params();
b39a07dc 2281 AssertLockHeld(cs_main);
6fb8d0c2 2282
bfa832c7
PW
2283 bool fExpensiveChecks = true;
2284 if (fCheckpointsEnabled) {
2285 CBlockIndex *pindexLastCheckpoint = Checkpoints::GetLastCheckpoint(chainparams.Checkpoints());
2286 if (pindexLastCheckpoint && pindexLastCheckpoint->GetAncestor(pindex->nHeight) == pindex) {
2287 // This block is an ancestor of a checkpoint: disable script checks
2288 fExpensiveChecks = false;
2289 }
2290 }
2291
6fb8d0c2
JG
2292 auto verifier = libzcash::ProofVerifier::Strict();
2293 auto disabledVerifier = libzcash::ProofVerifier::Disabled();
2294
2295 // Check it again to verify JoinSplit proofs, and in case a previous version let a bad block in
2296 if (!CheckBlock(block, state, fExpensiveChecks ? verifier : disabledVerifier, !fJustCheck, !fJustCheck))
0a61b0df 2297 return false;
2298
450cbb09 2299 // verify that the view's current state corresponds to the previous block
4f152496 2300 uint256 hashPrevBlock = pindex->pprev == NULL ? uint256() : pindex->pprev->GetBlockHash();
84674082 2301 assert(hashPrevBlock == view.GetBestBlock());
450cbb09 2302
8301ff50
PW
2303 // Special case for the genesis block, skipping connection of its transactions
2304 // (its coinbase is unspendable)
4e382177 2305 if (block.GetHash() == chainparams.GetConsensus().hashGenesisBlock) {
6a7acc29 2306 if (!fJustCheck) {
1b178a7f 2307 view.SetBestBlock(pindex->GetBlockHash());
6a7acc29
JG
2308 // Before the genesis block, there was an empty tree
2309 ZCIncrementalMerkleTree tree;
08f07288 2310 pindex->hashSproutAnchor = tree.root();
0bc1e2c4 2311 // The genesis block contained no JoinSplits
e814be60 2312 pindex->hashFinalSproutRoot = pindex->hashSproutAnchor;
6a7acc29 2313 }
8301ff50
PW
2314 return true;
2315 }
2316
a206b0ea
PW
2317 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
2318 // unless those are already completely spent.
b3be1ef5 2319 BOOST_FOREACH(const CTransaction& tx, block.vtx) {
805344dc 2320 const CCoins* coins = view.AccessCoins(tx.GetHash());
b3be1ef5
SB
2321 if (coins && !coins->IsPruned())
2322 return state.DoS(100, error("ConnectBlock(): tried to overwrite transaction"),
2323 REJECT_INVALID, "bad-txns-BIP30");
450cbb09 2324 }
a206b0ea 2325
de609b8c 2326 unsigned int flags = SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY;
ef0f4225 2327
de609b8c 2328 // DERSIG (BIP66) is also always enforced, but does not have a flag.
5e82e1c8 2329
8adf48dc
PW
2330 CBlockUndo blockundo;
2331
6fb8d0c2 2332 CCheckQueueControl<CScriptCheck> control(fExpensiveChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
f9cae832 2333
d70bc52e 2334 int64_t nTimeStart = GetTimeMicros();
a372168e 2335 CAmount nFees = 0;
8a28bb6d 2336 int nInputs = 0;
7bd9c3a3 2337 unsigned int nSigOps = 0;
f3ae51dc 2338 CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size()));
2d1fa42e 2339 std::vector<std::pair<uint256, CDiskTxPos> > vPos;
f3ae51dc 2340 vPos.reserve(block.vtx.size());
ab15b2ec 2341 blockundo.vtxundo.reserve(block.vtx.size() - 1);
a8ac403d
SB
2342
2343 // Construct the incremental merkle tree at the current
2344 // block position,
1f8be05b 2345 auto old_sprout_tree_root = view.GetBestAnchor(SPROUT);
b6961fc1 2346 // saving the top anchor in the block index as we go.
6a7acc29 2347 if (!fJustCheck) {
1f8be05b 2348 pindex->hashSproutAnchor = old_sprout_tree_root;
6a7acc29 2349 }
1f8be05b 2350 ZCIncrementalMerkleTree sprout_tree;
a8ac403d
SB
2351 // This should never fail: we should always be able to get the root
2352 // that is on the tip of our chain
1f8be05b 2353 assert(view.GetSproutAnchorAt(old_sprout_tree_root, sprout_tree));
a8ac403d
SB
2354
2355 {
2356 // Consistency check: the root of the tree we're given should
2357 // match what we asked for.
1f8be05b 2358 assert(sprout_tree.root() == old_sprout_tree_root);
a8ac403d
SB
2359 }
2360
1f8be05b
SB
2361 ZCSaplingIncrementalMerkleTree sapling_tree;
2362 assert(view.GetSaplingAnchorAt(view.GetBestAnchor(SAPLING), sapling_tree));
2363
be126699
JG
2364 // Grab the consensus branch ID for the block's height
2365 auto consensusBranchId = CurrentEpochBranchId(pindex->nHeight, Params().GetConsensus());
2366
6514771a
PW
2367 std::vector<PrecomputedTransactionData> txdata;
2368 txdata.reserve(block.vtx.size()); // Required so that pointers to individual PrecomputedTransactionData don't get invalidated
f3ae51dc 2369 for (unsigned int i = 0; i < block.vtx.size(); i++)
0a61b0df 2370 {
f3ae51dc 2371 const CTransaction &tx = block.vtx[i];
64dd46fd 2372
8a28bb6d 2373 nInputs += tx.vin.size();
05df3fc6 2374 nSigOps += GetLegacySigOpCount(tx);
137d0685 2375 if (nSigOps > MAX_BLOCK_SIGOPS)
5262fde0 2376 return state.DoS(100, error("ConnectBlock(): too many sigops"),
14e7ffcc 2377 REJECT_INVALID, "bad-blk-sigops");
137d0685 2378
8d7849b6
GA
2379 if (!tx.IsCoinBase())
2380 {
05df3fc6 2381 if (!view.HaveInputs(tx))
5262fde0 2382 return state.DoS(100, error("ConnectBlock(): inputs missing/spent"),
14e7ffcc 2383 REJECT_INVALID, "bad-txns-inputs-missingorspent");
922e8e29 2384
b7e4abd6 2385 // are the JoinSplit's requirements met?
ee964faf 2386 if (!view.HaveJoinSplitRequirements(tx))
b7e4abd6
SB
2387 return state.DoS(100, error("ConnectBlock(): JoinSplit requirements not met"),
2388 REJECT_INVALID, "bad-txns-joinsplit-requirements-not-met");
a8ac403d 2389
b3be1ef5
SB
2390 // Add in sigops done by pay-to-script-hash inputs;
2391 // this is to prevent a "rogue miner" from creating
2392 // an incredibly-expensive-to-validate block.
2393 nSigOps += GetP2SHSigOpCount(tx, view);
2394 if (nSigOps > MAX_BLOCK_SIGOPS)
2395 return state.DoS(100, error("ConnectBlock(): too many sigops"),
2396 REJECT_INVALID, "bad-blk-sigops");
f762d449
PW
2397 }
2398
6514771a 2399 txdata.emplace_back(tx);
922e8e29 2400
f762d449
PW
2401 if (!tx.IsCoinBase())
2402 {
0733c1bd 2403 nFees += view.GetValueIn(tx)-tx.GetValueOut();
8adf48dc 2404
f9cae832 2405 std::vector<CScriptCheck> vChecks;
be126699 2406 if (!ContextualCheckInputs(tx, state, view, fExpensiveChecks, flags, false, txdata[i], chainparams.GetConsensus(), consensusBranchId, nScriptCheckThreads ? &vChecks : NULL))
40634605 2407 return false;
f9cae832 2408 control.Add(vChecks);
8d7849b6
GA
2409 }
2410
ab15b2ec
PW
2411 CTxUndo undoDummy;
2412 if (i > 0) {
2413 blockundo.vtxundo.push_back(CTxUndo());
2414 }
8cb98d91 2415 UpdateCoins(tx, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight);
8a28bb6d 2416
b7e4abd6 2417 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
4bc00dc1
DH
2418 BOOST_FOREACH(const uint256 &note_commitment, joinsplit.commitments) {
2419 // Insert the note commitments into our temporary tree.
a8ac403d 2420
1f8be05b 2421 sprout_tree.append(note_commitment);
a8ac403d
SB
2422 }
2423 }
2424
1f8be05b
SB
2425 BOOST_FOREACH(const OutputDescription &outputDescription, tx.vShieldedOutput) {
2426 sapling_tree.append(outputDescription.cm);
2427 }
2428
805344dc 2429 vPos.push_back(std::make_pair(tx.GetHash(), pos));
2d1fa42e 2430 pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
0a61b0df 2431 }
a8ac403d 2432
1f8be05b
SB
2433 view.PushSproutAnchor(sprout_tree);
2434 view.PushSaplingAnchor(sapling_tree);
0bc1e2c4 2435 if (!fJustCheck) {
1f8be05b
SB
2436 pindex->hashFinalSproutRoot = sprout_tree.root();
2437 }
2438 blockundo.old_sprout_tree_root = old_sprout_tree_root;
2439
2440 // If Sapling is active, block.hashFinalSaplingRoot must be the
2441 // same as the root of the Sapling tree
2442 if (NetworkUpgradeActive(pindex->nHeight, chainparams.GetConsensus(), Consensus::UPGRADE_SAPLING)) {
2443 if (block.hashFinalSaplingRoot != sapling_tree.root()) {
2444 return state.DoS(100,
2445 error("ConnectBlock(): block's hashFinalSaplingRoot is incorrect"),
2446 REJECT_INVALID, "bad-sapling-root-in-block");
2447 }
0bc1e2c4 2448 }
a8ac403d 2449
d70bc52e
PW
2450 int64_t nTime1 = GetTimeMicros(); nTimeConnect += nTime1 - nTimeStart;
2451 LogPrint("bench", " - Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin) [%.2fs]\n", (unsigned)block.vtx.size(), 0.001 * (nTime1 - nTimeStart), 0.001 * (nTime1 - nTimeStart) / block.vtx.size(), nInputs <= 1 ? 0 : 0.001 * (nTime1 - nTimeStart) / (nInputs-1), nTimeConnect * 0.000001);
e679ec96 2452
935bd0a4
JT
2453 CAmount blockReward = nFees + GetBlockSubsidy(pindex->nHeight, chainparams.GetConsensus());
2454 if (block.vtx[0].GetValueOut() > blockReward)
358ce266 2455 return state.DoS(100,
5262fde0 2456 error("ConnectBlock(): coinbase pays too much (actual=%d vs limit=%d)",
935bd0a4 2457 block.vtx[0].GetValueOut(), blockReward),
2b45345a 2458 REJECT_INVALID, "bad-cb-amount");
9e957fb3 2459
f9cae832 2460 if (!control.Wait())
ef3988ca 2461 return state.DoS(100, false);
d70bc52e
PW
2462 int64_t nTime2 = GetTimeMicros(); nTimeVerify += nTime2 - nTimeStart;
2463 LogPrint("bench", " - Verify %u txins: %.2fms (%.3fms/txin) [%.2fs]\n", nInputs - 1, 0.001 * (nTime2 - nTimeStart), nInputs <= 1 ? 0 : 0.001 * (nTime2 - nTimeStart) / (nInputs-1), nTimeVerify * 0.000001);
f9cae832 2464
3cd01fdf
LD
2465 if (fJustCheck)
2466 return true;
2467
5382bcf8 2468 // Write undo information to disk
942b33a1 2469 if (pindex->GetUndoPos().IsNull() || !pindex->IsValid(BLOCK_VALID_SCRIPTS))
5382bcf8 2470 {
857c61df
PW
2471 if (pindex->GetUndoPos().IsNull()) {
2472 CDiskBlockPos pos;
ef3988ca 2473 if (!FindUndoPos(state, pindex->nFile, pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40))
5262fde0 2474 return error("ConnectBlock(): FindUndoPos failed");
e6973430 2475 if (!UndoWriteToDisk(blockundo, pos, pindex->pprev->GetBlockHash(), chainparams.MessageStart()))
27afcd89 2476 return AbortNode(state, "Failed to write undo data");
857c61df
PW
2477
2478 // update nUndoPos in block index
2479 pindex->nUndoPos = pos.nPos;
2480 pindex->nStatus |= BLOCK_HAVE_UNDO;
2481 }
2482
828940b1 2483 // Now that all consensus rules have been validated, set nCachedBranchId.
9e851450
JG
2484 // Move this if BLOCK_VALID_CONSENSUS is ever altered.
2485 static_assert(BLOCK_VALID_CONSENSUS == BLOCK_VALID_SCRIPTS,
828940b1 2486 "nCachedBranchId must be set after all consensus rules have been validated.");
9e851450
JG
2487 if (IsActivationHeightForAnyUpgrade(pindex->nHeight, Params().GetConsensus())) {
2488 pindex->nStatus |= BLOCK_ACTIVATES_UPGRADE;
828940b1 2489 pindex->nCachedBranchId = CurrentEpochBranchId(pindex->nHeight, chainparams.GetConsensus());
9e851450 2490 } else if (pindex->pprev) {
828940b1 2491 pindex->nCachedBranchId = pindex->pprev->nCachedBranchId;
9e851450
JG
2492 }
2493
942b33a1 2494 pindex->RaiseValidity(BLOCK_VALID_SCRIPTS);
51ce901a 2495 setDirtyBlockIndex.insert(pindex);
0a61b0df 2496 }
2497
2d1fa42e 2498 if (fTxIndex)
ef3988ca 2499 if (!pblocktree->WriteTxIndex(vPos))
27afcd89 2500 return AbortNode(state, "Failed to write transaction index");
2d1fa42e 2501
729b1806 2502 // add this block to the view's block chain
c9d1a81c 2503 view.SetBestBlock(pindex->GetBlockHash());
450cbb09 2504
d70bc52e
PW
2505 int64_t nTime3 = GetTimeMicros(); nTimeIndex += nTime3 - nTime2;
2506 LogPrint("bench", " - Index writing: %.2fms [%.2fs]\n", 0.001 * (nTime3 - nTime2), nTimeIndex * 0.000001);
2507
202e0194
PW
2508 // Watch for changes to the previous coinbase transaction.
2509 static uint256 hashPrevBestCoinBase;
26c16d9d 2510 GetMainSignals().UpdatedTransaction(hashPrevBestCoinBase);
805344dc 2511 hashPrevBestCoinBase = block.vtx[0].GetHash();
202e0194 2512
d70bc52e
PW
2513 int64_t nTime4 = GetTimeMicros(); nTimeCallbacks += nTime4 - nTime3;
2514 LogPrint("bench", " - Callbacks: %.2fms [%.2fs]\n", 0.001 * (nTime4 - nTime3), nTimeCallbacks * 0.000001);
2515
0a61b0df 2516 return true;
2517}
2518
a2069500 2519enum FlushStateMode {
f9ec3f0f 2520 FLUSH_STATE_NONE,
a2069500
PW
2521 FLUSH_STATE_IF_NEEDED,
2522 FLUSH_STATE_PERIODIC,
2523 FLUSH_STATE_ALWAYS
2524};
2525
51ce901a
PW
2526/**
2527 * Update the on-disk chain state.
f9ec3f0f 2528 * The caches and indexes are flushed depending on the mode we're called with
2529 * if they're too large, if it's been a while since the last write,
2530 * or always and in all cases if we're in prune mode and are deleting files.
51ce901a 2531 */
a2069500 2532bool static FlushStateToDisk(CValidationState &state, FlushStateMode mode) {
f9ec3f0f 2533 LOCK2(cs_main, cs_LastBlockFile);
75f51f2a 2534 static int64_t nLastWrite = 0;
67708acf
PW
2535 static int64_t nLastFlush = 0;
2536 static int64_t nLastSetChain = 0;
f9ec3f0f 2537 std::set<int> setFilesToPrune;
2538 bool fFlushForPrune = false;
e4134579 2539 try {
dfe55bdc 2540 if (fPruneMode && fCheckForPruning && !fReindex) {
f9ec3f0f 2541 FindFilesToPrune(setFilesToPrune);
c2080403 2542 fCheckForPruning = false;
f9ec3f0f 2543 if (!setFilesToPrune.empty()) {
2544 fFlushForPrune = true;
2545 if (!fHavePruned) {
2546 pblocktree->WriteFlag("prunedblockfiles", true);
2547 fHavePruned = true;
2548 }
2549 }
2550 }
67708acf
PW
2551 int64_t nNow = GetTimeMicros();
2552 // Avoid writing/flushing immediately after startup.
2553 if (nLastWrite == 0) {
2554 nLastWrite = nNow;
2555 }
2556 if (nLastFlush == 0) {
2557 nLastFlush = nNow;
2558 }
2559 if (nLastSetChain == 0) {
2560 nLastSetChain = nNow;
2561 }
2562 size_t cacheSize = pcoinsTip->DynamicMemoryUsage();
2563 // The cache is large and close to the limit, but we have time now (not in the middle of a block processing).
2564 bool fCacheLarge = mode == FLUSH_STATE_PERIODIC && cacheSize * (10.0/9) > nCoinCacheUsage;
2565 // The cache is over the limit, we have to write now.
2566 bool fCacheCritical = mode == FLUSH_STATE_IF_NEEDED && cacheSize > nCoinCacheUsage;
2567 // It's been a while since we wrote the block index to disk. Do this frequently, so we don't need to redownload after a crash.
2568 bool fPeriodicWrite = mode == FLUSH_STATE_PERIODIC && nNow > nLastWrite + (int64_t)DATABASE_WRITE_INTERVAL * 1000000;
2569 // It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage.
2570 bool fPeriodicFlush = mode == FLUSH_STATE_PERIODIC && nNow > nLastFlush + (int64_t)DATABASE_FLUSH_INTERVAL * 1000000;
2571 // Combine all conditions that result in a full cache flush.
2572 bool fDoFullFlush = (mode == FLUSH_STATE_ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush || fFlushForPrune;
2573 // Write blocks and block index to disk.
2574 if (fDoFullFlush || fPeriodicWrite) {
86a5f4b5
AM
2575 // Depend on nMinDiskSpace to ensure we can write block index
2576 if (!CheckDiskSpace(0))
c117d9e9 2577 return state.Error("out of disk space");
51ce901a 2578 // First make sure all block and undo data is flushed to disk.
44d40f26 2579 FlushBlockFile();
51ce901a 2580 // Then update all block file information (which may refer to block and undo files).
63d1ae55
PW
2581 {
2582 std::vector<std::pair<int, const CBlockFileInfo*> > vFiles;
2583 vFiles.reserve(setDirtyFileInfo.size());
2584 for (set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) {
2585 vFiles.push_back(make_pair(*it, &vinfoBlockFile[*it]));
2586 setDirtyFileInfo.erase(it++);
2587 }
2588 std::vector<const CBlockIndex*> vBlocks;
2589 vBlocks.reserve(setDirtyBlockIndex.size());
2590 for (set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) {
2591 vBlocks.push_back(*it);
2592 setDirtyBlockIndex.erase(it++);
2593 }
2594 if (!pblocktree->WriteBatchSync(vFiles, nLastBlockFile, vBlocks)) {
27afcd89 2595 return AbortNode(state, "Files to write to block index database");
51ce901a 2596 }
51ce901a 2597 }
f9ec3f0f 2598 // Finally remove any pruned files
c2080403 2599 if (fFlushForPrune)
f9ec3f0f 2600 UnlinkPrunedFiles(setFilesToPrune);
67708acf
PW
2601 nLastWrite = nNow;
2602 }
2603 // Flush best chain related state. This can only be done if the blocks / block index write was also done.
2604 if (fDoFullFlush) {
86a5f4b5
AM
2605 // Typical CCoins structures on disk are around 128 bytes in size.
2606 // Pushing a new one to the database can cause it to be written
2607 // twice (once in the log, and once in the tables). This is already
2608 // an overestimation, as most will delete an existing entry or
2609 // overwrite one. Still, use a conservative safety factor of 2.
2610 if (!CheckDiskSpace(128 * 2 * 2 * pcoinsTip->GetCacheSize()))
2611 return state.Error("out of disk space");
67708acf
PW
2612 // Flush the chainstate (which may refer to block index entries).
2613 if (!pcoinsTip->Flush())
27afcd89 2614 return AbortNode(state, "Failed to write to coin database");
67708acf
PW
2615 nLastFlush = nNow;
2616 }
2617 if ((mode == FLUSH_STATE_ALWAYS || mode == FLUSH_STATE_PERIODIC) && nNow > nLastSetChain + (int64_t)DATABASE_WRITE_INTERVAL * 1000000) {
51ce901a 2618 // Update best block in wallet (so we can detect restored wallets).
67708acf
PW
2619 GetMainSignals().SetBestChain(chainActive.GetLocator());
2620 nLastSetChain = nNow;
44d40f26 2621 }
e4134579 2622 } catch (const std::runtime_error& e) {
27afcd89 2623 return AbortNode(state, std::string("System error while flushing: ") + e.what());
e4134579 2624 }
0ec16f35
PW
2625 return true;
2626}
450cbb09 2627
51ce901a
PW
2628void FlushStateToDisk() {
2629 CValidationState state;
a2069500 2630 FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
51ce901a
PW
2631}
2632
f9ec3f0f 2633void PruneAndFlush() {
2634 CValidationState state;
2635 fCheckForPruning = true;
2636 FlushStateToDisk(state, FLUSH_STATE_NONE);
2637}
2638
c5b390b6 2639/** Update chainActive and related internal data structures. */
0ec16f35 2640void static UpdateTip(CBlockIndex *pindexNew) {
11982d36 2641 const CChainParams& chainParams = Params();
4c6d41b8 2642 chainActive.SetTip(pindexNew);
0a61b0df 2643
0a61b0df 2644 // New best block
0a61b0df 2645 nTimeBestReceived = GetTime();
319b1160 2646 mempool.AddTransactionsUpdated(1);
ff6a7af1 2647
b3ed4236 2648 LogPrintf("%s: new best=%s height=%d log2_work=%.8g tx=%lu date=%s progress=%f cache=%.1fMiB(%utx)\n", __func__,
0ec16f35 2649 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), log(chainActive.Tip()->nChainWork.getdouble())/log(2.0), (unsigned long)chainActive.Tip()->nChainTx,
7d9d134b 2650 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
b3ed4236 2651 Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), chainActive.Tip()), pcoinsTip->DynamicMemoryUsage() * (1.0 / (1<<20)), pcoinsTip->GetCacheSize());
0a61b0df 2652
ff6a7af1
LD
2653 cvBlockChange.notify_all();
2654
2a919e39 2655 // Check the version of the last 100 blocks to see if we need to upgrade:
dbca89b7
GA
2656 static bool fWarned = false;
2657 if (!IsInitialBlockDownload() && !fWarned)
2a919e39
GA
2658 {
2659 int nUpgraded = 0;
4c6d41b8 2660 const CBlockIndex* pindex = chainActive.Tip();
2a919e39
GA
2661 for (int i = 0; i < 100 && pindex != NULL; i++)
2662 {
2663 if (pindex->nVersion > CBlock::CURRENT_VERSION)
2664 ++nUpgraded;
2665 pindex = pindex->pprev;
2666 }
2667 if (nUpgraded > 0)
30c1db1c 2668 LogPrintf("%s: %d of last 100 blocks above version %d\n", __func__, nUpgraded, (int)CBlock::CURRENT_VERSION);
2a919e39 2669 if (nUpgraded > 100/2)
dbca89b7 2670 {
07cf4264 2671 // strMiscWarning is read by GetWarnings(), called by the JSON-RPC code to warn the user:
7e6d23b1 2672 strMiscWarning = _("Warning: This version is obsolete; upgrade required!");
dbca89b7
GA
2673 CAlert::Notify(strMiscWarning, true);
2674 fWarned = true;
2675 }
2a919e39 2676 }
75f51f2a 2677}
2a919e39 2678
34a64fe0
JG
2679/**
2680 * Disconnect chainActive's tip. You probably want to call mempool.removeForReorg and
2681 * mempool.removeWithoutBranchId after this, with cs_main held.
2682 */
89f20450 2683bool static DisconnectTip(CValidationState &state, bool fBare = false) {
75f51f2a
PW
2684 CBlockIndex *pindexDelete = chainActive.Tip();
2685 assert(pindexDelete);
75f51f2a
PW
2686 // Read block from disk.
2687 CBlock block;
2688 if (!ReadBlockFromDisk(block, pindexDelete))
27afcd89 2689 return AbortNode(state, "Failed to read block");
75f51f2a 2690 // Apply the block atomically to the chain state.
98d2f090
SB
2691 uint256 sproutAnchorBeforeDisconnect = pcoinsTip->GetBestAnchor(SPROUT);
2692 uint256 saplingAnchorBeforeDisconnect = pcoinsTip->GetBestAnchor(SAPLING);
75f51f2a 2693 int64_t nStart = GetTimeMicros();
d237f62c 2694 {
7c70438d 2695 CCoinsViewCache view(pcoinsTip);
75f51f2a 2696 if (!DisconnectBlock(block, state, pindexDelete, view))
5262fde0 2697 return error("DisconnectTip(): DisconnectBlock %s failed", pindexDelete->GetBlockHash().ToString());
75f51f2a 2698 assert(view.Flush());
d237f62c 2699 }
d70bc52e 2700 LogPrint("bench", "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
98d2f090
SB
2701 uint256 sproutAnchorAfterDisconnect = pcoinsTip->GetBestAnchor(SPROUT);
2702 uint256 saplingAnchorAfterDisconnect = pcoinsTip->GetBestAnchor(SAPLING);
75f51f2a 2703 // Write the chain state to disk, if necessary.
a2069500 2704 if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
75f51f2a 2705 return false;
89f20450
PW
2706
2707 if (!fBare) {
2708 // Resurrect mempool transactions from the disconnected block.
2709 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
2710 // ignore validation errors in resurrected transactions
2711 list<CTransaction> removed;
2712 CValidationState stateDummy;
2713 if (tx.IsCoinBase() || !AcceptToMemoryPool(mempool, stateDummy, tx, false, NULL))
2714 mempool.remove(tx, removed, true);
2715 }
98d2f090 2716 if (sproutAnchorBeforeDisconnect != sproutAnchorAfterDisconnect) {
89f20450
PW
2717 // The anchor may not change between block disconnects,
2718 // in which case we don't want to evict from the mempool yet!
98d2f090
SB
2719 mempool.removeWithAnchor(sproutAnchorBeforeDisconnect, SPROUT);
2720 }
2721 if (saplingAnchorBeforeDisconnect != saplingAnchorAfterDisconnect) {
89f20450
PW
2722 // The anchor may not change between block disconnects,
2723 // in which case we don't want to evict from the mempool yet!
98d2f090 2724 mempool.removeWithAnchor(saplingAnchorBeforeDisconnect, SAPLING);
89f20450 2725 }
89f20450
PW
2726 }
2727
75f51f2a
PW
2728 // Update chainActive and related variables.
2729 UpdateTip(pindexDelete->pprev);
de42390f
JG
2730 // Get the current commitment tree
2731 ZCIncrementalMerkleTree newTree;
18322f07 2732 assert(pcoinsTip->GetSproutAnchorAt(pcoinsTip->GetBestAnchor(SPROUT), newTree));
93a18a36
GA
2733 // Let wallets know transactions went from 1-confirmed to
2734 // 0-confirmed or conflicted:
2735 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
d38da59b 2736 SyncWithWallets(tx, NULL);
93a18a36 2737 }
769e031c 2738 // Update cached incremental witnesses
de42390f 2739 GetMainSignals().ChainTip(pindexDelete, &block, newTree, false);
75f51f2a 2740 return true;
0ec16f35 2741}
d237f62c 2742
d70bc52e
PW
2743static int64_t nTimeReadFromDisk = 0;
2744static int64_t nTimeConnectTotal = 0;
2745static int64_t nTimeFlush = 0;
2746static int64_t nTimeChainState = 0;
2747static int64_t nTimePostConnect = 0;
2748
db954a65 2749/**
c5b390b6
MF
2750 * Connect a new block to chainActive. pblock is either NULL or a pointer to a CBlock
2751 * corresponding to pindexNew, to bypass loading it again from disk.
34a64fe0 2752 * You probably want to call mempool.removeWithoutBranchId after this, with cs_main held.
c5b390b6 2753 */
92bb6f2f 2754bool static ConnectTip(CValidationState &state, CBlockIndex *pindexNew, CBlock *pblock) {
75f51f2a 2755 assert(pindexNew->pprev == chainActive.Tip());
75f51f2a 2756 // Read block from disk.
d70bc52e 2757 int64_t nTime1 = GetTimeMicros();
75f51f2a 2758 CBlock block;
92bb6f2f
PW
2759 if (!pblock) {
2760 if (!ReadBlockFromDisk(block, pindexNew))
27afcd89 2761 return AbortNode(state, "Failed to read block");
92bb6f2f
PW
2762 pblock = &block;
2763 }
de42390f
JG
2764 // Get the current commitment tree
2765 ZCIncrementalMerkleTree oldTree;
18322f07 2766 assert(pcoinsTip->GetSproutAnchorAt(pcoinsTip->GetBestAnchor(SPROUT), oldTree));
75f51f2a 2767 // Apply the block atomically to the chain state.
d70bc52e
PW
2768 int64_t nTime2 = GetTimeMicros(); nTimeReadFromDisk += nTime2 - nTime1;
2769 int64_t nTime3;
2770 LogPrint("bench", " - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * 0.001, nTimeReadFromDisk * 0.000001);
0a61b0df 2771 {
7c70438d 2772 CCoinsViewCache view(pcoinsTip);
24e88964 2773 bool rv = ConnectBlock(*pblock, state, pindexNew, view);
26c16d9d 2774 GetMainSignals().BlockChecked(*pblock, state);
24e88964 2775 if (!rv) {
75f51f2a
PW
2776 if (state.IsInvalid())
2777 InvalidBlockFound(pindexNew, state);
5262fde0 2778 return error("ConnectTip(): ConnectBlock %s failed", pindexNew->GetBlockHash().ToString());
7851033d 2779 }
2af5a650 2780 mapBlockSource.erase(pindexNew->GetBlockHash());
d70bc52e
PW
2781 nTime3 = GetTimeMicros(); nTimeConnectTotal += nTime3 - nTime2;
2782 LogPrint("bench", " - Connect total: %.2fms [%.2fs]\n", (nTime3 - nTime2) * 0.001, nTimeConnectTotal * 0.000001);
75f51f2a 2783 assert(view.Flush());
0a61b0df 2784 }
d70bc52e
PW
2785 int64_t nTime4 = GetTimeMicros(); nTimeFlush += nTime4 - nTime3;
2786 LogPrint("bench", " - Flush: %.2fms [%.2fs]\n", (nTime4 - nTime3) * 0.001, nTimeFlush * 0.000001);
75f51f2a 2787 // Write the chain state to disk, if necessary.
a2069500 2788 if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
75f51f2a 2789 return false;
d70bc52e
PW
2790 int64_t nTime5 = GetTimeMicros(); nTimeChainState += nTime5 - nTime4;
2791 LogPrint("bench", " - Writing chainstate: %.2fms [%.2fs]\n", (nTime5 - nTime4) * 0.001, nTimeChainState * 0.000001);
75f51f2a 2792 // Remove conflicting transactions from the mempool.
93a18a36 2793 list<CTransaction> txConflicted;
b649e039 2794 mempool.removeForBlock(pblock->vtx, pindexNew->nHeight, txConflicted, !IsInitialBlockDownload());
9bb37bf0
JG
2795
2796 // Remove transactions that expire at new block height from mempool
2797 mempool.removeExpired(pindexNew->nHeight);
2798
75f51f2a
PW
2799 // Update chainActive & related variables.
2800 UpdateTip(pindexNew);
93a18a36
GA
2801 // Tell wallet about transactions that went from mempool
2802 // to conflicted:
2803 BOOST_FOREACH(const CTransaction &tx, txConflicted) {
d38da59b 2804 SyncWithWallets(tx, NULL);
93a18a36
GA
2805 }
2806 // ... and about transactions that got confirmed:
92bb6f2f
PW
2807 BOOST_FOREACH(const CTransaction &tx, pblock->vtx) {
2808 SyncWithWallets(tx, pblock);
93a18a36 2809 }
769e031c 2810 // Update cached incremental witnesses
de42390f 2811 GetMainSignals().ChainTip(pindexNew, pblock, oldTree, true);
d920f7dc 2812
5b3bc971
JG
2813 EnforceNodeDeprecation(pindexNew->nHeight);
2814
d70bc52e
PW
2815 int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1;
2816 LogPrint("bench", " - Connect postprocess: %.2fms [%.2fs]\n", (nTime6 - nTime5) * 0.001, nTimePostConnect * 0.000001);
2817 LogPrint("bench", "- Connect block: %.2fms [%.2fs]\n", (nTime6 - nTime1) * 0.001, nTimeTotal * 0.000001);
0a61b0df 2818 return true;
2819}
2820
c5b390b6
MF
2821/**
2822 * Return the tip of the chain with the most work in it, that isn't
2823 * known to be invalid (it's however far from certain to be valid).
2824 */
77339e5a 2825static CBlockIndex* FindMostWorkChain() {
75f51f2a 2826 do {
77339e5a
PW
2827 CBlockIndex *pindexNew = NULL;
2828
75f51f2a
PW
2829 // Find the best candidate header.
2830 {
e17bd583
PW
2831 std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
2832 if (it == setBlockIndexCandidates.rend())
77339e5a 2833 return NULL;
75f51f2a
PW
2834 pindexNew = *it;
2835 }
2836
2837 // Check whether all blocks on the path between the currently active chain and the candidate are valid.
2838 // Just going until the active chain is an optimization, as we know all blocks in it are valid already.
2839 CBlockIndex *pindexTest = pindexNew;
2840 bool fInvalidAncestor = false;
2841 while (pindexTest && !chainActive.Contains(pindexTest)) {
341735eb 2842 assert(pindexTest->nChainTx || pindexTest->nHeight == 0);
f9ec3f0f 2843
2844 // Pruned nodes may have entries in setBlockIndexCandidates for
2845 // which block files have been deleted. Remove those as candidates
2846 // for the most work chain if we come across them; we can't switch
2847 // to a chain unless we have all the non-active-chain parent blocks.
2848 bool fFailedChain = pindexTest->nStatus & BLOCK_FAILED_MASK;
2849 bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA);
2850 if (fFailedChain || fMissingData) {
2851 // Candidate chain is not usable (either invalid or missing data)
2852 if (fFailedChain && (pindexBestInvalid == NULL || pindexNew->nChainWork > pindexBestInvalid->nChainWork))
942b33a1
PW
2853 pindexBestInvalid = pindexNew;
2854 CBlockIndex *pindexFailed = pindexNew;
f9ec3f0f 2855 // Remove the entire chain from the set.
75f51f2a 2856 while (pindexTest != pindexFailed) {
f9ec3f0f 2857 if (fFailedChain) {
2858 pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
2859 } else if (fMissingData) {
2860 // If we're missing data, then add back to mapBlocksUnlinked,
2861 // so that if the block arrives in the future we can try adding
2862 // to setBlockIndexCandidates again.
2863 mapBlocksUnlinked.insert(std::make_pair(pindexFailed->pprev, pindexFailed));
2864 }
e17bd583 2865 setBlockIndexCandidates.erase(pindexFailed);
75f51f2a
PW
2866 pindexFailed = pindexFailed->pprev;
2867 }
e17bd583 2868 setBlockIndexCandidates.erase(pindexTest);
75f51f2a
PW
2869 fInvalidAncestor = true;
2870 break;
ef3988ca 2871 }
75f51f2a 2872 pindexTest = pindexTest->pprev;
0a61b0df 2873 }
77339e5a
PW
2874 if (!fInvalidAncestor)
2875 return pindexNew;
75f51f2a 2876 } while(true);
75f51f2a 2877}
0a61b0df 2878
c5b390b6 2879/** Delete all entries in setBlockIndexCandidates that are worse than the current tip. */
cca48f69 2880static void PruneBlockIndexCandidates() {
2881 // Note that we can't delete the current block itself, as we may need to return to it later in case a
2882 // reorganization to a better block fails.
2883 std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
34559c7c 2884 while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, chainActive.Tip())) {
cca48f69 2885 setBlockIndexCandidates.erase(it++);
2886 }
34559c7c
PW
2887 // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
2888 assert(!setBlockIndexCandidates.empty());
cca48f69 2889}
2890
c5b390b6
MF
2891/**
2892 * Try to make some progress towards making pindexMostWork the active block.
2893 * pblock is either NULL or a pointer to a CBlock corresponding to pindexMostWork.
2894 */
92bb6f2f 2895static bool ActivateBestChainStep(CValidationState &state, CBlockIndex *pindexMostWork, CBlock *pblock) {
4e0eed88 2896 AssertLockHeld(cs_main);
202e0194 2897 bool fInvalidFound = false;
b33bd7a3
DK
2898 const CBlockIndex *pindexOldTip = chainActive.Tip();
2899 const CBlockIndex *pindexFork = chainActive.FindFork(pindexMostWork);
0a61b0df 2900
57e6ecda
JG
2901 // - On ChainDB initialization, pindexOldTip will be null, so there are no removable blocks.
2902 // - If pindexMostWork is in a chain that doesn't have the same genesis block as our chain,
2903 // then pindexFork will be null, and we would need to remove the entire chain including
2904 // our genesis block. In practice this (probably) won't happen because of checks elsewhere.
2905 auto reorgLength = pindexOldTip ? pindexOldTip->nHeight - (pindexFork ? pindexFork->nHeight : -1) : 0;
2906 static_assert(MAX_REORG_LENGTH > 0, "We must be able to reorg some distance");
2907 if (reorgLength > MAX_REORG_LENGTH) {
2908 auto msg = strprintf(_(
2909 "A block chain reorganization has been detected that would roll back %d blocks! "
2910 "This is larger than the maximum of %d blocks, and so the node is shutting down for your safety."
2911 ), reorgLength, MAX_REORG_LENGTH) + "\n\n" +
2912 _("Reorganization details") + ":\n" +
2913 "- " + strprintf(_("Current tip: %s, height %d, work %s"),
2914 pindexOldTip->phashBlock->GetHex(), pindexOldTip->nHeight, pindexOldTip->nChainWork.GetHex()) + "\n" +
2915 "- " + strprintf(_("New tip: %s, height %d, work %s"),
2916 pindexMostWork->phashBlock->GetHex(), pindexMostWork->nHeight, pindexMostWork->nChainWork.GetHex()) + "\n" +
2917 "- " + strprintf(_("Fork point: %s, height %d"),
2918 pindexFork->phashBlock->GetHex(), pindexFork->nHeight) + "\n\n" +
2919 _("Please help, human!");
2920 LogPrintf("*** %s\n", msg);
2921 uiInterface.ThreadSafeMessageBox(msg, "", CClientUIInterface::MSG_ERROR);
2922 StartShutdown();
2923 return false;
2924 }
2925
4e0eed88 2926 // Disconnect active blocks which are no longer in the best chain.
fe5cef05 2927 bool fBlocksDisconnected = false;
4e0eed88
PW
2928 while (chainActive.Tip() && chainActive.Tip() != pindexFork) {
2929 if (!DisconnectTip(state))
2930 return false;
fe5cef05 2931 fBlocksDisconnected = true;
4e0eed88 2932 }
75f51f2a 2933
4e0eed88
PW
2934 // Build list of new blocks to connect.
2935 std::vector<CBlockIndex*> vpindexToConnect;
afc32c5e
PW
2936 bool fContinue = true;
2937 int nHeight = pindexFork ? pindexFork->nHeight : -1;
2938 while (fContinue && nHeight != pindexMostWork->nHeight) {
5aa165d5
MC
2939 // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
2940 // a few blocks along the way.
2941 int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
2942 vpindexToConnect.clear();
2943 vpindexToConnect.reserve(nTargetHeight - nHeight);
2944 CBlockIndex *pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
2945 while (pindexIter && pindexIter->nHeight != nHeight) {
2946 vpindexToConnect.push_back(pindexIter);
2947 pindexIter = pindexIter->pprev;
2948 }
2949 nHeight = nTargetHeight;
2950
2951 // Connect new blocks.
2952 BOOST_REVERSE_FOREACH(CBlockIndex *pindexConnect, vpindexToConnect) {
2953 if (!ConnectTip(state, pindexConnect, pindexConnect == pindexMostWork ? pblock : NULL)) {
2954 if (state.IsInvalid()) {
2955 // The block violates a consensus rule.
2956 if (!state.CorruptionPossible())
2957 InvalidChainFound(vpindexToConnect.back());
2958 state = CValidationState();
2959 fInvalidFound = true;
2960 fContinue = false;
2961 break;
2962 } else {
2963 // A system error occurred (disk space, database error, ...).
2964 return false;
2965 }
4e0eed88 2966 } else {
5aa165d5
MC
2967 PruneBlockIndexCandidates();
2968 if (!pindexOldTip || chainActive.Tip()->nChainWork > pindexOldTip->nChainWork) {
2969 // We're in a better position than we were. Return temporarily to release the lock.
2970 fContinue = false;
2971 break;
2972 }
75f51f2a
PW
2973 }
2974 }
231b3999 2975 }
0a61b0df 2976
fe5cef05 2977 if (fBlocksDisconnected) {
233c9eb6 2978 mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
afc32c5e 2979 }
34a64fe0
JG
2980 mempool.removeWithoutBranchId(
2981 CurrentEpochBranchId(chainActive.Tip()->nHeight + 1, Params().GetConsensus()));
fe5cef05 2982 mempool.check(pcoinsTip);
0a61b0df 2983
202e0194
PW
2984 // Callbacks/notifications for a new best chain.
2985 if (fInvalidFound)
2986 CheckForkWarningConditionsOnNewFork(vpindexToConnect.back());
2987 else
2988 CheckForkWarningConditions();
2989
0a61b0df 2990 return true;
2991}
0a61b0df 2992
c5b390b6
MF
2993/**
2994 * Make the best chain active, in multiple steps. The result is either failure
2995 * or an activated best chain. pblock is either NULL or a pointer to a block
2996 * that is already loaded (to avoid loading it again from disk).
2997 */
92bb6f2f 2998bool ActivateBestChain(CValidationState &state, CBlock *pblock) {
202e0194
PW
2999 CBlockIndex *pindexNewTip = NULL;
3000 CBlockIndex *pindexMostWork = NULL;
11982d36 3001 const CChainParams& chainParams = Params();
4e0eed88
PW
3002 do {
3003 boost::this_thread::interruption_point();
3004
202e0194
PW
3005 bool fInitialDownload;
3006 {
3007 LOCK(cs_main);
3008 pindexMostWork = FindMostWorkChain();
4e0eed88 3009
202e0194
PW
3010 // Whether we have anything to do at all.
3011 if (pindexMostWork == NULL || pindexMostWork == chainActive.Tip())
3012 return true;
4e0eed88 3013
92bb6f2f 3014 if (!ActivateBestChainStep(state, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : NULL))
202e0194 3015 return false;
4e0eed88 3016
202e0194
PW
3017 pindexNewTip = chainActive.Tip();
3018 fInitialDownload = IsInitialBlockDownload();
3019 }
3020 // When we reach this point, we switched to a new tip (stored in pindexNewTip).
3021
3022 // Notifications/callbacks that can run without cs_main
3023 if (!fInitialDownload) {
3024 uint256 hashNewTip = pindexNewTip->GetBlockHash();
3025 // Relay inventory, but don't relay old inventory during initial block download.
a8cdaf5c
CF
3026 int nBlockEstimate = 0;
3027 if (fCheckpointsEnabled)
3028 nBlockEstimate = Checkpoints::GetTotalBlocksEstimate(chainParams.Checkpoints());
f9ec3f0f 3029 // Don't relay blocks if pruning -- could cause a peer to try to download, resulting
3030 // in a stalled download if the block file is pruned before the request.
3031 if (nLocalServices & NODE_NETWORK) {
4dc5eb05
PK
3032 LOCK(cs_vNodes);
3033 BOOST_FOREACH(CNode* pnode, vNodes)
3034 if (chainActive.Height() > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
3035 pnode->PushInventory(CInv(MSG_BLOCK, hashNewTip));
202e0194 3036 }
51ce901a 3037 // Notify external listeners about the new tip.
6a793d9c 3038 GetMainSignals().UpdatedBlockTip(pindexNewTip);
c7b6117d 3039 uiInterface.NotifyBlockTip(hashNewTip);
202e0194 3040 }
202e0194 3041 } while(pindexMostWork != chainActive.Tip());
3fcfbc8a 3042 CheckBlockIndex();
4e0eed88 3043
51ce901a 3044 // Write changes periodically to disk, after relay.
a2069500 3045 if (!FlushStateToDisk(state, FLUSH_STATE_PERIODIC)) {
51ce901a
PW
3046 return false;
3047 }
3048
4e0eed88
PW
3049 return true;
3050}
942b33a1 3051
9b0a8d31
PW
3052bool InvalidateBlock(CValidationState& state, CBlockIndex *pindex) {
3053 AssertLockHeld(cs_main);
3054
3055 // Mark the block itself as invalid.
3056 pindex->nStatus |= BLOCK_FAILED_VALID;
0dd06b25 3057 setDirtyBlockIndex.insert(pindex);
9b0a8d31
PW
3058 setBlockIndexCandidates.erase(pindex);
3059
3060 while (chainActive.Contains(pindex)) {
3061 CBlockIndex *pindexWalk = chainActive.Tip();
3062 pindexWalk->nStatus |= BLOCK_FAILED_CHILD;
0dd06b25 3063 setDirtyBlockIndex.insert(pindexWalk);
9b0a8d31
PW
3064 setBlockIndexCandidates.erase(pindexWalk);
3065 // ActivateBestChain considers blocks already in chainActive
3066 // unconditionally valid already, so force disconnect away from it.
3067 if (!DisconnectTip(state)) {
233c9eb6 3068 mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
34a64fe0
JG
3069 mempool.removeWithoutBranchId(
3070 CurrentEpochBranchId(chainActive.Tip()->nHeight + 1, Params().GetConsensus()));
9b0a8d31
PW
3071 return false;
3072 }
3073 }
3074
3075 // The resulting new best tip may not be in setBlockIndexCandidates anymore, so
b05a89b2 3076 // add it again.
9b0a8d31
PW
3077 BlockMap::iterator it = mapBlockIndex.begin();
3078 while (it != mapBlockIndex.end()) {
cd3d67cf 3079 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && !setBlockIndexCandidates.value_comp()(it->second, chainActive.Tip())) {
a9af4158 3080 setBlockIndexCandidates.insert(it->second);
9b0a8d31
PW
3081 }
3082 it++;
3083 }
3084
3085 InvalidChainFound(pindex);
233c9eb6 3086 mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
34a64fe0
JG
3087 mempool.removeWithoutBranchId(
3088 CurrentEpochBranchId(chainActive.Tip()->nHeight + 1, Params().GetConsensus()));
9b0a8d31
PW
3089 return true;
3090}
3091
3092bool ReconsiderBlock(CValidationState& state, CBlockIndex *pindex) {
3093 AssertLockHeld(cs_main);
3094
3095 int nHeight = pindex->nHeight;
3096
3097 // Remove the invalidity flag from this block and all its descendants.
3098 BlockMap::iterator it = mapBlockIndex.begin();
3099 while (it != mapBlockIndex.end()) {
3100 if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) {
3101 it->second->nStatus &= ~BLOCK_FAILED_MASK;
0dd06b25 3102 setDirtyBlockIndex.insert(it->second);
9b0a8d31
PW
3103 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && setBlockIndexCandidates.value_comp()(chainActive.Tip(), it->second)) {
3104 setBlockIndexCandidates.insert(it->second);
3105 }
3106 if (it->second == pindexBestInvalid) {
3107 // Reset invalid block marker if it was pointing to one of those.
3108 pindexBestInvalid = NULL;
3109 }
3110 }
3111 it++;
3112 }
3113
3114 // Remove the invalidity flag from all ancestors too.
3115 while (pindex != NULL) {
0dd06b25
PW
3116 if (pindex->nStatus & BLOCK_FAILED_MASK) {
3117 pindex->nStatus &= ~BLOCK_FAILED_MASK;
3118 setDirtyBlockIndex.insert(pindex);
9b0a8d31
PW
3119 }
3120 pindex = pindex->pprev;
3121 }
3122 return true;
3123}
3124
341735eb 3125CBlockIndex* AddToBlockIndex(const CBlockHeader& block)
0a61b0df 3126{
3127 // Check for duplicate
1959997a 3128 uint256 hash = block.GetHash();
145d5be8 3129 BlockMap::iterator it = mapBlockIndex.find(hash);
942b33a1
PW
3130 if (it != mapBlockIndex.end())
3131 return it->second;
0a61b0df 3132
3133 // Construct new block index object
1959997a 3134 CBlockIndex* pindexNew = new CBlockIndex(block);
94c8bfb2 3135 assert(pindexNew);
341735eb
PW
3136 // We assign the sequence id to blocks only when the full data is available,
3137 // to avoid miners withholding blocks but broadcasting headers, to get a
3138 // competitive advantage.
3139 pindexNew->nSequenceId = 0;
145d5be8 3140 BlockMap::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
0a61b0df 3141 pindexNew->phashBlock = &((*mi).first);
145d5be8 3142 BlockMap::iterator miPrev = mapBlockIndex.find(block.hashPrevBlock);
0a61b0df 3143 if (miPrev != mapBlockIndex.end())
3144 {
3145 pindexNew->pprev = (*miPrev).second;
3146 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
c9a09183 3147 pindexNew->BuildSkip();
0a61b0df 3148 }
092b58d1 3149 pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew);
942b33a1 3150 pindexNew->RaiseValidity(BLOCK_VALID_TREE);
341735eb
PW
3151 if (pindexBestHeader == NULL || pindexBestHeader->nChainWork < pindexNew->nChainWork)
3152 pindexBestHeader = pindexNew;
3153
51ce901a 3154 setDirtyBlockIndex.insert(pindexNew);
942b33a1
PW
3155
3156 return pindexNew;
3157}
3158
c5b390b6 3159/** Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS). */
942b33a1
PW
3160bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBlockIndex *pindexNew, const CDiskBlockPos& pos)
3161{
3162 pindexNew->nTx = block.vtx.size();
341735eb 3163 pindexNew->nChainTx = 0;
ad6a36ad
JG
3164 CAmount sproutValue = 0;
3165 for (auto tx : block.vtx) {
3166 for (auto js : tx.vjoinsplit) {
3167 sproutValue += js.vpub_old;
3168 sproutValue -= js.vpub_new;
3169 }
3170 }
3171 pindexNew->nSproutValue = sproutValue;
3172 pindexNew->nChainSproutValue = boost::none;
857c61df
PW
3173 pindexNew->nFile = pos.nFile;
3174 pindexNew->nDataPos = pos.nPos;
5382bcf8 3175 pindexNew->nUndoPos = 0;
942b33a1 3176 pindexNew->nStatus |= BLOCK_HAVE_DATA;
341735eb 3177 pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS);
51ce901a 3178 setDirtyBlockIndex.insert(pindexNew);
942b33a1 3179
341735eb
PW
3180 if (pindexNew->pprev == NULL || pindexNew->pprev->nChainTx) {
3181 // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
3182 deque<CBlockIndex*> queue;
3183 queue.push_back(pindexNew);
0a61b0df 3184
341735eb
PW
3185 // Recursively process any descendant blocks that now may be eligible to be connected.
3186 while (!queue.empty()) {
3187 CBlockIndex *pindex = queue.front();
3188 queue.pop_front();
3189 pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
ad6a36ad
JG
3190 if (pindex->pprev) {
3191 if (pindex->pprev->nChainSproutValue && pindex->nSproutValue) {
3192 pindex->nChainSproutValue = *pindex->pprev->nChainSproutValue + *pindex->nSproutValue;
3193 } else {
3194 pindex->nChainSproutValue = boost::none;
3195 }
3196 } else {
3197 pindex->nChainSproutValue = pindex->nSproutValue;
3198 }
c1ecee8f
SD
3199 {
3200 LOCK(cs_nBlockSequenceId);
3201 pindex->nSequenceId = nBlockSequenceId++;
3202 }
3fcfbc8a
PW
3203 if (chainActive.Tip() == NULL || !setBlockIndexCandidates.value_comp()(pindex, chainActive.Tip())) {
3204 setBlockIndexCandidates.insert(pindex);
3205 }
341735eb
PW
3206 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex);
3207 while (range.first != range.second) {
3208 std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
3209 queue.push_back(it->second);
3210 range.first++;
3211 mapBlocksUnlinked.erase(it);
3212 }
341735eb
PW
3213 }
3214 } else {
3215 if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
3216 mapBlocksUnlinked.insert(std::make_pair(pindexNew->pprev, pindexNew));
3217 }
341735eb 3218 }
0a61b0df 3219
18e72167 3220 return true;
0a61b0df 3221}
3222
51ed9ec9 3223bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false)
5382bcf8 3224{
5382bcf8
PW
3225 LOCK(cs_LastBlockFile);
3226
ed6d1a2c
PW
3227 unsigned int nFile = fKnown ? pos.nFile : nLastBlockFile;
3228 if (vinfoBlockFile.size() <= nFile) {
3229 vinfoBlockFile.resize(nFile + 1);
3230 }
3231
3232 if (!fKnown) {
3233 while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
ed6d1a2c
PW
3234 nFile++;
3235 if (vinfoBlockFile.size() <= nFile) {
3236 vinfoBlockFile.resize(nFile + 1);
3237 }
7fea4846 3238 }
ed6d1a2c
PW
3239 pos.nFile = nFile;
3240 pos.nPos = vinfoBlockFile[nFile].nSize;
5382bcf8
PW
3241 }
3242
4e895b08
PW
3243 if (nFile != nLastBlockFile) {
3244 if (!fKnown) {
3245 LogPrintf("Leaving block file %i: %s\n", nFile, vinfoBlockFile[nFile].ToString());
3246 }
3247 FlushBlockFile(!fKnown);
3248 nLastBlockFile = nFile;
3249 }
3250
ed6d1a2c 3251 vinfoBlockFile[nFile].AddBlock(nHeight, nTime);
bb6acff0
CF
3252 if (fKnown)
3253 vinfoBlockFile[nFile].nSize = std::max(pos.nPos + nAddSize, vinfoBlockFile[nFile].nSize);
3254 else
3255 vinfoBlockFile[nFile].nSize += nAddSize;
5382bcf8 3256
7fea4846
PW
3257 if (!fKnown) {
3258 unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
ed6d1a2c 3259 unsigned int nNewChunks = (vinfoBlockFile[nFile].nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
7fea4846 3260 if (nNewChunks > nOldChunks) {
f9ec3f0f 3261 if (fPruneMode)
3262 fCheckForPruning = true;
fa45c26a
PK
3263 if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
3264 FILE *file = OpenBlockFile(pos);
3265 if (file) {
881a85a2 3266 LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
fa45c26a
PK
3267 AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
3268 fclose(file);
3269 }
7fea4846 3270 }
fa45c26a 3271 else
c117d9e9 3272 return state.Error("out of disk space");
bba89aa8 3273 }
bba89aa8
PW
3274 }
3275
51ce901a 3276 setDirtyFileInfo.insert(nFile);
5382bcf8
PW
3277 return true;
3278}
3279
ef3988ca 3280bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
5382bcf8
PW
3281{
3282 pos.nFile = nFile;
3283
3284 LOCK(cs_LastBlockFile);
3285
bba89aa8 3286 unsigned int nNewSize;
ed6d1a2c
PW
3287 pos.nPos = vinfoBlockFile[nFile].nUndoSize;
3288 nNewSize = vinfoBlockFile[nFile].nUndoSize += nAddSize;
51ce901a 3289 setDirtyFileInfo.insert(nFile);
bba89aa8
PW
3290
3291 unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
3292 unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
3293 if (nNewChunks > nOldChunks) {
f9ec3f0f 3294 if (fPruneMode)
3295 fCheckForPruning = true;
fa45c26a
PK
3296 if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
3297 FILE *file = OpenUndoFile(pos);
3298 if (file) {
881a85a2 3299 LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
fa45c26a
PK
3300 AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
3301 fclose(file);
3302 }
bba89aa8 3303 }
fa45c26a 3304 else
c117d9e9 3305 return state.Error("out of disk space");
5382bcf8
PW
3306 }
3307
5382bcf8
PW
3308 return true;
3309}
3310
f4573470 3311bool CheckBlockHeader(const CBlockHeader& block, CValidationState& state, bool fCheckPOW)
0a61b0df 3312{
80f4cdcf
JG
3313 // Check block version
3314 if (block.nVersion < MIN_BLOCK_VERSION)
3315 return state.DoS(100, error("CheckBlockHeader(): block version too low"),
3316 REJECT_INVALID, "version-too-low");
3317
fdda3c50
JG
3318 // Check Equihash solution is valid
3319 if (fCheckPOW && !CheckEquihashSolution(&block, Params()))
3320 return state.DoS(100, error("CheckBlockHeader(): Equihash solution invalid"),
3321 REJECT_INVALID, "invalid-solution");
3322
172f0060 3323 // Check proof of work matches claimed amount
d698ef69 3324 if (fCheckPOW && !CheckProofOfWork(block.GetHash(), block.nBits, Params().GetConsensus()))
5262fde0 3325 return state.DoS(50, error("CheckBlockHeader(): proof of work failed"),
14e7ffcc 3326 REJECT_INVALID, "high-hash");
172f0060 3327
0a61b0df 3328 // Check timestamp
38991ffa 3329 if (block.GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
5262fde0 3330 return state.Invalid(error("CheckBlockHeader(): block timestamp too far in the future"),
14e7ffcc 3331 REJECT_INVALID, "time-too-new");
0a61b0df 3332
f4573470
PW
3333 return true;
3334}
3335
6fb8d0c2
JG
3336bool CheckBlock(const CBlock& block, CValidationState& state,
3337 libzcash::ProofVerifier& verifier,
3338 bool fCheckPOW, bool fCheckMerkleRoot)
0a61b0df 3339{
341735eb 3340 // These are checks that are independent of context.
0a61b0df 3341
57425a24
DK
3342 // Check that the header is valid (particularly PoW). This is mostly
3343 // redundant with the call in AcceptBlockHeader.
f4573470
PW
3344 if (!CheckBlockHeader(block, state, fCheckPOW))
3345 return false;
3346
341735eb
PW
3347 // Check the merkle root.
3348 if (fCheckMerkleRoot) {
3349 bool mutated;
3350 uint256 hashMerkleRoot2 = block.BuildMerkleTree(&mutated);
3351 if (block.hashMerkleRoot != hashMerkleRoot2)
5262fde0 3352 return state.DoS(100, error("CheckBlock(): hashMerkleRoot mismatch"),
341735eb
PW
3353 REJECT_INVALID, "bad-txnmrklroot", true);
3354
3355 // Check for merkle tree malleability (CVE-2012-2459): repeating sequences
3356 // of transactions in a block without affecting the merkle root of a block,
3357 // while still invalidating it.
3358 if (mutated)
5262fde0 3359 return state.DoS(100, error("CheckBlock(): duplicate transaction"),
341735eb
PW
3360 REJECT_INVALID, "bad-txns-duplicate", true);
3361 }
3362
3363 // All potential-corruption validation must be done before we do any
3364 // transaction validation, as otherwise we may mark the header as invalid
3365 // because we receive the wrong transactions for it.
3366
0a61b0df 3367 // Size limits
38991ffa 3368 if (block.vtx.empty() || block.vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
5262fde0 3369 return state.DoS(100, error("CheckBlock(): size limits failed"),
14e7ffcc 3370 REJECT_INVALID, "bad-blk-length");
0a61b0df 3371
0a61b0df 3372 // First transaction must be coinbase, the rest must not be
38991ffa 3373 if (block.vtx.empty() || !block.vtx[0].IsCoinBase())
5262fde0 3374 return state.DoS(100, error("CheckBlock(): first tx is not coinbase"),
14e7ffcc 3375 REJECT_INVALID, "bad-cb-missing");
38991ffa
EL
3376 for (unsigned int i = 1; i < block.vtx.size(); i++)
3377 if (block.vtx[i].IsCoinBase())
5262fde0 3378 return state.DoS(100, error("CheckBlock(): more than one coinbase"),
14e7ffcc 3379 REJECT_INVALID, "bad-cb-multiple");
0a61b0df 3380
3381 // Check transactions
38991ffa 3382 BOOST_FOREACH(const CTransaction& tx, block.vtx)
6fb8d0c2 3383 if (!CheckTransaction(tx, state, verifier))
5262fde0 3384 return error("CheckBlock(): CheckTransaction failed");
0a61b0df 3385
7bd9c3a3 3386 unsigned int nSigOps = 0;
38991ffa 3387 BOOST_FOREACH(const CTransaction& tx, block.vtx)
e679ec96 3388 {
05df3fc6 3389 nSigOps += GetLegacySigOpCount(tx);
e679ec96
GA
3390 }
3391 if (nSigOps > MAX_BLOCK_SIGOPS)
5262fde0 3392 return state.DoS(100, error("CheckBlock(): out-of-bounds SigOpCount"),
14e7ffcc 3393 REJECT_INVALID, "bad-blk-sigops", true);
0a61b0df 3394
0a61b0df 3395 return true;
3396}
3397
a48f2d6d
LD
3398bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex * const pindexPrev)
3399{
11982d36
CF
3400 const CChainParams& chainParams = Params();
3401 const Consensus::Params& consensusParams = chainParams.GetConsensus();
a48f2d6d 3402 uint256 hash = block.GetHash();
4e382177 3403 if (hash == consensusParams.hashGenesisBlock)
a48f2d6d
LD
3404 return true;
3405
3406 assert(pindexPrev);
3407
3408 int nHeight = pindexPrev->nHeight+1;
3409
3410 // Check proof of work
11982d36 3411 if (block.nBits != GetNextWorkRequired(pindexPrev, &block, consensusParams))
5262fde0 3412 return state.DoS(100, error("%s: incorrect proof of work", __func__),
a48f2d6d
LD
3413 REJECT_INVALID, "bad-diffbits");
3414
3415 // Check timestamp against prev
3416 if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
5262fde0 3417 return state.Invalid(error("%s: block's timestamp is too early", __func__),
a48f2d6d
LD
3418 REJECT_INVALID, "time-too-old");
3419
bfa832c7 3420 if (fCheckpointsEnabled)
a8cdaf5c 3421 {
a8cdaf5c
CF
3422 // Don't accept any forks from the main chain prior to last checkpoint
3423 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(chainParams.Checkpoints());
3424 if (pcheckpoint && nHeight < pcheckpoint->nHeight)
3425 return state.DoS(100, error("%s: forked chain older than last checkpoint (height %d)", __func__, nHeight));
3426 }
a48f2d6d 3427
542da618
SB
3428 // Reject block.nVersion < 4 blocks
3429 if (block.nVersion < 4)
3430 return state.Invalid(error("%s : rejected nVersion<4 block", __func__),
5e82e1c8
PT
3431 REJECT_OBSOLETE, "bad-version");
3432
a48f2d6d
LD
3433 return true;
3434}
3435
3436bool ContextualCheckBlock(const CBlock& block, CValidationState& state, CBlockIndex * const pindexPrev)
3437{
3438 const int nHeight = pindexPrev == NULL ? 0 : pindexPrev->nHeight + 1;
51aa2492 3439 const Consensus::Params& consensusParams = Params().GetConsensus();
a48f2d6d
LD
3440
3441 // Check that all transactions are finalized
a1d3c6fb 3442 BOOST_FOREACH(const CTransaction& tx, block.vtx) {
072099d7
S
3443
3444 // Check transaction contextually against consensus rules at block height
3445 if (!ContextualCheckTransaction(tx, state, nHeight, 100)) {
3446 return false; // Failure reason has been set in validation state object
3447 }
3448
a1d3c6fb
MF
3449 int nLockTimeFlags = 0;
3450 int64_t nLockTimeCutoff = (nLockTimeFlags & LOCKTIME_MEDIAN_TIME_PAST)
3451 ? pindexPrev->GetMedianTimePast()
3452 : block.GetBlockTime();
3453 if (!IsFinalTx(tx, nHeight, nLockTimeCutoff)) {
5262fde0 3454 return state.DoS(10, error("%s: contains a non-final transaction", __func__), REJECT_INVALID, "bad-txns-nonfinal");
a48f2d6d 3455 }
a1d3c6fb 3456 }
a48f2d6d 3457
c2a722d3
DH
3458 // Enforce BIP 34 rule that the coinbase starts with serialized block height.
3459 // In Zcash this has been enforced since launch, except that the genesis
3460 // block didn't include the height in the coinbase (see Zcash protocol spec
3461 // section '6.8 Bitcoin Improvement Proposals').
548bbd95 3462 if (nHeight > 0)
a48f2d6d
LD
3463 {
3464 CScript expect = CScript() << nHeight;
3465 if (block.vtx[0].vin[0].scriptSig.size() < expect.size() ||
3466 !std::equal(expect.begin(), expect.end(), block.vtx[0].vin[0].scriptSig.begin())) {
5262fde0 3467 return state.DoS(100, error("%s: block height mismatch in coinbase", __func__), REJECT_INVALID, "bad-cb-height");
a48f2d6d
LD
3468 }
3469 }
3470
f3ffa3d2 3471 // Coinbase transaction must include an output sending 20% of
b7d07206
S
3472 // the block reward to a founders reward script, until the last founders
3473 // reward block is reached, with exception of the genesis block.
3474 // The last founders reward block is defined as the block just before the
3475 // first subsidy halving block, which occurs at halving_interval + slow_start_shift
db0f9315 3476 if ((nHeight > 0) && (nHeight <= consensusParams.GetLastFoundersRewardBlockHeight())) {
f3ffa3d2
SB
3477 bool found = false;
3478
3479 BOOST_FOREACH(const CTxOut& output, block.vtx[0].vout) {
3b30d836 3480 if (output.scriptPubKey == Params().GetFoundersRewardScriptAtHeight(nHeight)) {
f3ffa3d2
SB
3481 if (output.nValue == (GetBlockSubsidy(nHeight, consensusParams) / 5)) {
3482 found = true;
3483 break;
3484 }
3485 }
3486 }
3487
3488 if (!found) {
3489 return state.DoS(100, error("%s: founders reward missing", __func__), REJECT_INVALID, "cb-no-founders-reward");
3490 }
3491 }
3492
a48f2d6d
LD
3493 return true;
3494}
3495
341735eb 3496bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex** ppindex)
0a61b0df 3497{
4e382177 3498 const CChainParams& chainparams = Params();
e07c943c 3499 AssertLockHeld(cs_main);
0a61b0df 3500 // Check for duplicate
2a4d3464 3501 uint256 hash = block.GetHash();
145d5be8 3502 BlockMap::iterator miSelf = mapBlockIndex.find(hash);
942b33a1
PW
3503 CBlockIndex *pindex = NULL;
3504 if (miSelf != mapBlockIndex.end()) {
341735eb 3505 // Block header is already known.
942b33a1 3506 pindex = miSelf->second;
341735eb
PW
3507 if (ppindex)
3508 *ppindex = pindex;
942b33a1 3509 if (pindex->nStatus & BLOCK_FAILED_MASK)
5262fde0 3510 return state.Invalid(error("%s: block is marked invalid", __func__), 0, "duplicate");
341735eb 3511 return true;
942b33a1 3512 }
0a61b0df 3513
57425a24
DK
3514 if (!CheckBlockHeader(block, state))
3515 return false;
3516
0a61b0df 3517 // Get prev block index
7fea4846 3518 CBlockIndex* pindexPrev = NULL;
4e382177 3519 if (hash != chainparams.GetConsensus().hashGenesisBlock) {
145d5be8 3520 BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
b56585d0 3521 if (mi == mapBlockIndex.end())
5262fde0 3522 return state.DoS(10, error("%s: prev block not found", __func__), 0, "bad-prevblk");
b56585d0 3523 pindexPrev = (*mi).second;
34970223 3524 if (pindexPrev->nStatus & BLOCK_FAILED_MASK)
5262fde0 3525 return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk");
942b33a1
PW
3526 }
3527
a48f2d6d
LD
3528 if (!ContextualCheckBlockHeader(block, state, pindexPrev))
3529 return false;
3530
942b33a1
PW
3531 if (pindex == NULL)
3532 pindex = AddToBlockIndex(block);
3533
3534 if (ppindex)
3535 *ppindex = pindex;
3536
3537 return true;
3538}
3539
304892fc 3540bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex** ppindex, bool fRequested, CDiskBlockPos* dbp)
942b33a1 3541{
e6973430 3542 const CChainParams& chainparams = Params();
942b33a1
PW
3543 AssertLockHeld(cs_main);
3544
3545 CBlockIndex *&pindex = *ppindex;
3546
3547 if (!AcceptBlockHeader(block, state, &pindex))
3548 return false;
3549
304892fc
SD
3550 // Try to process all requested blocks that we don't have, but only
3551 // process an unrequested block if it's new and has enough work to
93b606ae 3552 // advance our tip, and isn't too many blocks ahead.
304892fc
SD
3553 bool fAlreadyHave = pindex->nStatus & BLOCK_HAVE_DATA;
3554 bool fHasMoreWork = (chainActive.Tip() ? pindex->nChainWork > chainActive.Tip()->nChainWork : true);
93b606ae
SD
3555 // Blocks that are too out-of-order needlessly limit the effectiveness of
3556 // pruning, because pruning will not delete block files that contain any
3557 // blocks which are too close in height to the tip. Apply this test
3558 // regardless of whether pruning is enabled; it should generally be safe to
3559 // not process unrequested blocks.
3560 bool fTooFarAhead = (pindex->nHeight > int(chainActive.Height() + MIN_BLOCKS_TO_KEEP));
304892fc
SD
3561
3562 // TODO: deal better with return value and error conditions for duplicate
3563 // and unrequested blocks.
3564 if (fAlreadyHave) return true;
3565 if (!fRequested) { // If we didn't ask for it:
3566 if (pindex->nTx != 0) return true; // This is a previously-processed block that was pruned
3567 if (!fHasMoreWork) return true; // Don't process less-work chains
93b606ae 3568 if (fTooFarAhead) return true; // Block height is too high
341735eb
PW
3569 }
3570
6fb8d0c2
JG
3571 // See method docstring for why this is always disabled
3572 auto verifier = libzcash::ProofVerifier::Disabled();
3573 if ((!CheckBlock(block, state, verifier)) || !ContextualCheckBlock(block, state, pindex->pprev)) {
43005cff 3574 if (state.IsInvalid() && !state.CorruptionPossible()) {
942b33a1 3575 pindex->nStatus |= BLOCK_FAILED_VALID;
51ce901a 3576 setDirtyBlockIndex.insert(pindex);
942b33a1
PW
3577 }
3578 return false;
3579 }
3580
3581 int nHeight = pindex->nHeight;
942b33a1 3582
0a61b0df 3583 // Write block to history file
421218d3 3584 try {
2a4d3464 3585 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
421218d3
PW
3586 CDiskBlockPos blockPos;
3587 if (dbp != NULL)
3588 blockPos = *dbp;
209377a7 3589 if (!FindBlockPos(state, blockPos, nBlockSize+8, nHeight, block.GetBlockTime(), dbp != NULL))
5262fde0 3590 return error("AcceptBlock(): FindBlockPos failed");
421218d3 3591 if (dbp == NULL)
e6973430 3592 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
27afcd89 3593 AbortNode(state, "Failed to write block");
942b33a1 3594 if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
5262fde0 3595 return error("AcceptBlock(): ReceivedBlockTransactions failed");
27df4123 3596 } catch (const std::runtime_error& e) {
27afcd89 3597 return AbortNode(state, std::string("System error: ") + e.what());
421218d3 3598 }
0a61b0df 3599
f9ec3f0f 3600 if (fCheckForPruning)
3601 FlushStateToDisk(state, FLUSH_STATE_NONE); // we just allocated more disk space for block files
3602
0a61b0df 3603 return true;
3604}
3605
51aa2492 3606static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned nRequired, const Consensus::Params& consensusParams)
de237cbf
GA
3607{
3608 unsigned int nFound = 0;
51aa2492 3609 for (int i = 0; i < consensusParams.nMajorityWindow && nFound < nRequired && pstart != NULL; i++)
de237cbf
GA
3610 {
3611 if (pstart->nVersion >= minVersion)
3612 ++nFound;
3613 pstart = pstart->pprev;
3614 }
3615 return (nFound >= nRequired);
3616}
3617
c9a09183 3618
304892fc 3619bool ProcessNewBlock(CValidationState &state, CNode* pfrom, CBlock* pblock, bool fForceProcessing, CDiskBlockPos *dbp)
0a61b0df 3620{
0a61b0df 3621 // Preliminary checks
6fb8d0c2
JG
3622 auto verifier = libzcash::ProofVerifier::Disabled();
3623 bool checked = CheckBlock(*pblock, state, verifier);
0a61b0df 3624
0a61b0df 3625 {
341735eb 3626 LOCK(cs_main);
304892fc
SD
3627 bool fRequested = MarkBlockAsReceived(pblock->GetHash());
3628 fRequested |= fForceProcessing;
341735eb 3629 if (!checked) {
5262fde0 3630 return error("%s: CheckBlock FAILED", __func__);
5c88e3c1 3631 }
0a61b0df 3632
341735eb
PW
3633 // Store to disk
3634 CBlockIndex *pindex = NULL;
304892fc 3635 bool ret = AcceptBlock(*pblock, state, &pindex, fRequested, dbp);
341735eb
PW
3636 if (pindex && pfrom) {
3637 mapBlockSource[pindex->GetBlockHash()] = pfrom->GetId();
0a61b0df 3638 }
3fcfbc8a 3639 CheckBlockIndex();
341735eb 3640 if (!ret)
5262fde0 3641 return error("%s: AcceptBlock FAILED", __func__);
18e72167
PW
3642 }
3643
92bb6f2f 3644 if (!ActivateBestChain(state, pblock))
5262fde0 3645 return error("%s: ActivateBestChain failed", __func__);
18e72167 3646
0a61b0df 3647 return true;
3648}
3649
df08a626
LD
3650bool TestBlockValidity(CValidationState &state, const CBlock& block, CBlockIndex * const pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
3651{
3652 AssertLockHeld(cs_main);
3653 assert(pindexPrev == chainActive.Tip());
3654
3655 CCoinsViewCache viewNew(pcoinsTip);
3656 CBlockIndex indexDummy(block);
3657 indexDummy.pprev = pindexPrev;
3658 indexDummy.nHeight = pindexPrev->nHeight + 1;
6fb8d0c2
JG
3659 // JoinSplit proofs are verified in ConnectBlock
3660 auto verifier = libzcash::ProofVerifier::Disabled();
df08a626
LD
3661
3662 // NOTE: CheckBlockHeader is called by CheckBlock
3663 if (!ContextualCheckBlockHeader(block, state, pindexPrev))
3664 return false;
6fb8d0c2 3665 if (!CheckBlock(block, state, verifier, fCheckPOW, fCheckMerkleRoot))
df08a626
LD
3666 return false;
3667 if (!ContextualCheckBlock(block, state, pindexPrev))
3668 return false;
3669 if (!ConnectBlock(block, state, &indexDummy, viewNew, true))
3670 return false;
3671 assert(state.IsValid());
3672
3673 return true;
3674}
3675
f9ec3f0f 3676/**
3677 * BLOCK PRUNING CODE
3678 */
3679
3680/* Calculate the amount of disk space the block & undo files currently use */
3681uint64_t CalculateCurrentUsage()
3682{
3683 uint64_t retval = 0;
3684 BOOST_FOREACH(const CBlockFileInfo &file, vinfoBlockFile) {
3685 retval += file.nSize + file.nUndoSize;
3686 }
3687 return retval;
3688}
3689
3690/* Prune a block file (modify associated database entries)*/
3691void PruneOneBlockFile(const int fileNumber)
3692{
3693 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); ++it) {
3694 CBlockIndex* pindex = it->second;
3695 if (pindex->nFile == fileNumber) {
3696 pindex->nStatus &= ~BLOCK_HAVE_DATA;
3697 pindex->nStatus &= ~BLOCK_HAVE_UNDO;
3698 pindex->nFile = 0;
3699 pindex->nDataPos = 0;
3700 pindex->nUndoPos = 0;
3701 setDirtyBlockIndex.insert(pindex);
3702
3703 // Prune from mapBlocksUnlinked -- any block we prune would have
3704 // to be downloaded again in order to consider its chain, at which
3705 // point it would be considered as a candidate for
3706 // mapBlocksUnlinked or setBlockIndexCandidates.
3707 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex->pprev);
3708 while (range.first != range.second) {
3709 std::multimap<CBlockIndex *, CBlockIndex *>::iterator it = range.first;
3710 range.first++;
3711 if (it->second == pindex) {
3712 mapBlocksUnlinked.erase(it);
3713 }
3714 }
3715 }
3716 }
3717
3718 vinfoBlockFile[fileNumber].SetNull();
3719 setDirtyFileInfo.insert(fileNumber);
3720}
3721
3722
3723void UnlinkPrunedFiles(std::set<int>& setFilesToPrune)
3724{
3725 for (set<int>::iterator it = setFilesToPrune.begin(); it != setFilesToPrune.end(); ++it) {
3726 CDiskBlockPos pos(*it, 0);
3727 boost::filesystem::remove(GetBlockPosFilename(pos, "blk"));
3728 boost::filesystem::remove(GetBlockPosFilename(pos, "rev"));
3729 LogPrintf("Prune: %s deleted blk/rev (%05u)\n", __func__, *it);
3730 }
3731}
3732
3733/* Calculate the block/rev files that should be deleted to remain under target*/
3734void FindFilesToPrune(std::set<int>& setFilesToPrune)
3735{
3736 LOCK2(cs_main, cs_LastBlockFile);
3737 if (chainActive.Tip() == NULL || nPruneTarget == 0) {
3738 return;
3739 }
3740 if (chainActive.Tip()->nHeight <= Params().PruneAfterHeight()) {
3741 return;
3742 }
3743
b89f3077 3744 unsigned int nLastBlockWeCanPrune = chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP;
f9ec3f0f 3745 uint64_t nCurrentUsage = CalculateCurrentUsage();
3746 // We don't check to prune until after we've allocated new space for files
3747 // So we should leave a buffer under our target to account for another allocation
3748 // before the next pruning.
3749 uint64_t nBuffer = BLOCKFILE_CHUNK_SIZE + UNDOFILE_CHUNK_SIZE;
3750 uint64_t nBytesToPrune;
3751 int count=0;
3752
3753 if (nCurrentUsage + nBuffer >= nPruneTarget) {
3754 for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
3755 nBytesToPrune = vinfoBlockFile[fileNumber].nSize + vinfoBlockFile[fileNumber].nUndoSize;
3756
3757 if (vinfoBlockFile[fileNumber].nSize == 0)
3758 continue;
3759
3760 if (nCurrentUsage + nBuffer < nPruneTarget) // are we below our target?
3761 break;
3762
6cb70ca4 3763 // don't prune files that could have a block within MIN_BLOCKS_TO_KEEP of the main chain's tip but keep scanning
b89f3077 3764 if (vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
6cb70ca4 3765 continue;
f9ec3f0f 3766
3767 PruneOneBlockFile(fileNumber);
3768 // Queue up the files for removal
3769 setFilesToPrune.insert(fileNumber);
3770 nCurrentUsage -= nBytesToPrune;
3771 count++;
3772 }
3773 }
3774
b89f3077 3775 LogPrint("prune", "Prune: target=%dMiB actual=%dMiB diff=%dMiB max_prune_height=%d removed %d blk/rev pairs\n",
f9ec3f0f 3776 nPruneTarget/1024/1024, nCurrentUsage/1024/1024,
3777 ((int64_t)nPruneTarget - (int64_t)nCurrentUsage)/1024/1024,
b89f3077 3778 nLastBlockWeCanPrune, count);
f9ec3f0f 3779}
3780
51ed9ec9 3781bool CheckDiskSpace(uint64_t nAdditionalBytes)
0a61b0df 3782{
a3241998 3783 uint64_t nFreeBytesAvailable = boost::filesystem::space(GetDataDir()).available;
0a61b0df 3784
966ae00f
PK
3785 // Check for nMinDiskSpace bytes (currently 50MB)
3786 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
b9b2e3fa 3787 return AbortNode("Disk space is low!", _("Error: Disk space is low!"));
7851033d 3788
0a61b0df 3789 return true;
3790}
3791
5382bcf8 3792FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
42613c97 3793{
450cbb09 3794 if (pos.IsNull())
0a61b0df 3795 return NULL;
ec7eb0fa 3796 boost::filesystem::path path = GetBlockPosFilename(pos, prefix);
5382bcf8
PW
3797 boost::filesystem::create_directories(path.parent_path());
3798 FILE* file = fopen(path.string().c_str(), "rb+");
3799 if (!file && !fReadOnly)
3800 file = fopen(path.string().c_str(), "wb+");
450cbb09 3801 if (!file) {
7d9d134b 3802 LogPrintf("Unable to open file %s\n", path.string());
0a61b0df 3803 return NULL;
450cbb09 3804 }
5382bcf8
PW
3805 if (pos.nPos) {
3806 if (fseek(file, pos.nPos, SEEK_SET)) {
7d9d134b 3807 LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string());
5382bcf8
PW
3808 fclose(file);
3809 return NULL;
3810 }
3811 }
0a61b0df 3812 return file;
3813}
3814
5382bcf8
PW
3815FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
3816 return OpenDiskFile(pos, "blk", fReadOnly);
3817}
3818
69e07747 3819FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
5382bcf8
PW
3820 return OpenDiskFile(pos, "rev", fReadOnly);
3821}
3822
ec7eb0fa
SD
3823boost::filesystem::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
3824{
f7e36370 3825 return GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
ec7eb0fa
SD
3826}
3827
2d8a4829
PW
3828CBlockIndex * InsertBlockIndex(uint256 hash)
3829{
4f152496 3830 if (hash.IsNull())
2d8a4829
PW
3831 return NULL;
3832
3833 // Return existing
145d5be8 3834 BlockMap::iterator mi = mapBlockIndex.find(hash);
2d8a4829
PW
3835 if (mi != mapBlockIndex.end())
3836 return (*mi).second;
3837
3838 // Create new
3839 CBlockIndex* pindexNew = new CBlockIndex();
3840 if (!pindexNew)
5262fde0 3841 throw runtime_error("LoadBlockIndex(): new CBlockIndex failed");
2d8a4829
PW
3842 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
3843 pindexNew->phashBlock = &((*mi).first);
3844
3845 return pindexNew;
3846}
3847
3848bool static LoadBlockIndexDB()
3849{
11982d36 3850 const CChainParams& chainparams = Params();
2d8a4829
PW
3851 if (!pblocktree->LoadBlockIndexGuts())
3852 return false;
3853
b31499ec 3854 boost::this_thread::interruption_point();
2d8a4829 3855
1657c4bc 3856 // Calculate nChainWork
2d8a4829
PW
3857 vector<pair<int, CBlockIndex*> > vSortedByHeight;
3858 vSortedByHeight.reserve(mapBlockIndex.size());
3859 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
3860 {
3861 CBlockIndex* pindex = item.second;
3862 vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
3863 }
3864 sort(vSortedByHeight.begin(), vSortedByHeight.end());
3865 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
3866 {
3867 CBlockIndex* pindex = item.second;
092b58d1 3868 pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex);
f9ec3f0f 3869 // We can link the chain of blocks for which we've received transactions at some point.
3870 // Pruned nodes may have deleted the block.
3871 if (pindex->nTx > 0) {
341735eb
PW
3872 if (pindex->pprev) {
3873 if (pindex->pprev->nChainTx) {
3874 pindex->nChainTx = pindex->pprev->nChainTx + pindex->nTx;
ad6a36ad
JG
3875 if (pindex->pprev->nChainSproutValue && pindex->nSproutValue) {
3876 pindex->nChainSproutValue = *pindex->pprev->nChainSproutValue + *pindex->nSproutValue;
3877 } else {
3878 pindex->nChainSproutValue = boost::none;
3879 }
341735eb
PW
3880 } else {
3881 pindex->nChainTx = 0;
ad6a36ad 3882 pindex->nChainSproutValue = boost::none;
341735eb
PW
3883 mapBlocksUnlinked.insert(std::make_pair(pindex->pprev, pindex));
3884 }
3885 } else {
3886 pindex->nChainTx = pindex->nTx;
ad6a36ad 3887 pindex->nChainSproutValue = pindex->nSproutValue;
341735eb
PW
3888 }
3889 }
9e851450
JG
3890 // Construct in-memory chain of branch IDs.
3891 // Relies on invariant: a block that does not activate a network upgrade
3892 // will always be valid under the same consensus rules as its parent.
828940b1
JG
3893 // Genesis block has a branch ID of zero by definition, but has no
3894 // validity status because it is side-loaded into a fresh chain.
3895 // Activation blocks will have branch IDs set (read from disk).
3896 if (pindex->pprev) {
3897 if (pindex->IsValid(BLOCK_VALID_CONSENSUS) && !pindex->nCachedBranchId) {
3898 pindex->nCachedBranchId = pindex->pprev->nCachedBranchId;
3899 }
3900 } else {
be126699 3901 pindex->nCachedBranchId = SPROUT_BRANCH_ID;
9e851450 3902 }
341735eb 3903 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->nChainTx || pindex->pprev == NULL))
e17bd583 3904 setBlockIndexCandidates.insert(pindex);
85eb2cef
PW
3905 if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork))
3906 pindexBestInvalid = pindex;
c9a09183
PW
3907 if (pindex->pprev)
3908 pindex->BuildSkip();
341735eb
PW
3909 if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == NULL || CBlockIndexWorkComparator()(pindexBestHeader, pindex)))
3910 pindexBestHeader = pindex;
2d8a4829
PW
3911 }
3912
3913 // Load block file info
3914 pblocktree->ReadLastBlockFile(nLastBlockFile);
ed6d1a2c 3915 vinfoBlockFile.resize(nLastBlockFile + 1);
7b2bb962 3916 LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile);
ed6d1a2c
PW
3917 for (int nFile = 0; nFile <= nLastBlockFile; nFile++) {
3918 pblocktree->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]);
3919 }
7b2bb962 3920 LogPrintf("%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString());
ed6d1a2c
PW
3921 for (int nFile = nLastBlockFile + 1; true; nFile++) {
3922 CBlockFileInfo info;
3923 if (pblocktree->ReadBlockFileInfo(nFile, info)) {
3924 vinfoBlockFile.push_back(info);
3925 } else {
3926 break;
3927 }
3928 }
729b1806 3929
8c93bf4c
AH
3930 // Check presence of blk files
3931 LogPrintf("Checking all blk files are present...\n");
3932 set<int> setBlkDataFiles;
3933 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
3934 {
3935 CBlockIndex* pindex = item.second;
3936 if (pindex->nStatus & BLOCK_HAVE_DATA) {
3937 setBlkDataFiles.insert(pindex->nFile);
3938 }
3939 }
3940 for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++)
3941 {
3942 CDiskBlockPos pos(*it, 0);
a8738238 3943 if (CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION).IsNull()) {
8c93bf4c
AH
3944 return false;
3945 }
3946 }
3947
f9ec3f0f 3948 // Check whether we have ever pruned block & undo files
3949 pblocktree->ReadFlag("prunedblockfiles", fHavePruned);
3950 if (fHavePruned)
3951 LogPrintf("LoadBlockIndexDB(): Block files have previously been pruned\n");
3952
89b7019b
PW
3953 // Check whether we need to continue reindexing
3954 bool fReindexing = false;
3955 pblocktree->ReadReindexing(fReindexing);
3956 fReindex |= fReindexing;
3957
2d1fa42e
PW
3958 // Check whether we have a transaction index
3959 pblocktree->ReadFlag("txindex", fTxIndex);
52070c87 3960 LogPrintf("%s: transaction index %s\n", __func__, fTxIndex ? "enabled" : "disabled");
2d1fa42e 3961
0bc1e2c4
JG
3962 // Fill in-memory data
3963 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
3964 {
3965 CBlockIndex* pindex = item.second;
3966 // - This relationship will always be true even if pprev has multiple
08f07288 3967 // children, because hashSproutAnchor is technically a property of pprev,
0bc1e2c4
JG
3968 // not its children.
3969 // - This will miss chain tips; we handle the best tip below, and other
3970 // tips will be handled by ConnectTip during a re-org.
3971 if (pindex->pprev) {
e814be60 3972 pindex->pprev->hashFinalSproutRoot = pindex->hashSproutAnchor;
0bc1e2c4
JG
3973 }
3974 }
3975
85eb2cef 3976 // Load pointer to end of best chain
145d5be8 3977 BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
84674082 3978 if (it == mapBlockIndex.end())
89b7019b 3979 return true;
84674082 3980 chainActive.SetTip(it->second);
e814be60
SB
3981 // Set hashFinalSproutRoot for the end of best chain
3982 it->second->hashFinalSproutRoot = pcoinsTip->GetBestAnchor(SPROUT);
cca48f69 3983
3984 PruneBlockIndexCandidates();
3985
52070c87 3986 LogPrintf("%s: hashBestChain=%s height=%d date=%s progress=%f\n", __func__,
7d9d134b 3987 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(),
c4656e0d 3988 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
11982d36 3989 Checkpoints::GuessVerificationProgress(chainparams.Checkpoints(), chainActive.Tip()));
2d8a4829 3990
5b3bc971
JG
3991 EnforceNodeDeprecation(chainActive.Height(), true);
3992
1f355b66
PW
3993 return true;
3994}
3995
06a91d96
CL
3996CVerifyDB::CVerifyDB()
3997{
3998 uiInterface.ShowProgress(_("Verifying blocks..."), 0);
3999}
4000
4001CVerifyDB::~CVerifyDB()
4002{
4003 uiInterface.ShowProgress("", 100);
4004}
4005
2e280311 4006bool CVerifyDB::VerifyDB(CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
168ba993 4007{
a475285a 4008 LOCK(cs_main);
4c6d41b8 4009 if (chainActive.Tip() == NULL || chainActive.Tip()->pprev == NULL)
1f355b66
PW
4010 return true;
4011
2d8a4829 4012 // Verify blocks in the best chain
f5906533 4013 if (nCheckDepth <= 0)
2d8a4829 4014 nCheckDepth = 1000000000; // suffices until the year 19000
4c6d41b8
PW
4015 if (nCheckDepth > chainActive.Height())
4016 nCheckDepth = chainActive.Height();
1f355b66 4017 nCheckLevel = std::max(0, std::min(4, nCheckLevel));
881a85a2 4018 LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
7c70438d 4019 CCoinsViewCache coins(coinsview);
4c6d41b8 4020 CBlockIndex* pindexState = chainActive.Tip();
1f355b66
PW
4021 CBlockIndex* pindexFailure = NULL;
4022 int nGoodTransactions = 0;
ef3988ca 4023 CValidationState state;
6fb8d0c2
JG
4024 // No need to verify JoinSplits twice
4025 auto verifier = libzcash::ProofVerifier::Disabled();
4c6d41b8 4026 for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev)
2d8a4829 4027 {
b31499ec 4028 boost::this_thread::interruption_point();
06a91d96 4029 uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100)))));
4c6d41b8 4030 if (pindex->nHeight < chainActive.Height()-nCheckDepth)
2d8a4829
PW
4031 break;
4032 CBlock block;
1f355b66 4033 // check level 0: read from disk
7db120d5 4034 if (!ReadBlockFromDisk(block, pindex))
5262fde0 4035 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
2d8a4829 4036 // check level 1: verify block validity
6fb8d0c2 4037 if (nCheckLevel >= 1 && !CheckBlock(block, state, verifier))
5262fde0 4038 return error("VerifyDB(): *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
1f355b66
PW
4039 // check level 2: verify undo validity
4040 if (nCheckLevel >= 2 && pindex) {
4041 CBlockUndo undo;
4042 CDiskBlockPos pos = pindex->GetUndoPos();
4043 if (!pos.IsNull()) {
e035c6a7 4044 if (!UndoReadFromDisk(undo, pos, pindex->pprev->GetBlockHash()))
5262fde0 4045 return error("VerifyDB(): *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
1f355b66
PW
4046 }
4047 }
4048 // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
fc684ad8 4049 if (nCheckLevel >= 3 && pindex == pindexState && (coins.DynamicMemoryUsage() + pcoinsTip->DynamicMemoryUsage()) <= nCoinCacheUsage) {
1f355b66 4050 bool fClean = true;
5c363ed6 4051 if (!DisconnectBlock(block, state, pindex, coins, &fClean))
5262fde0 4052 return error("VerifyDB(): *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
1f355b66
PW
4053 pindexState = pindex->pprev;
4054 if (!fClean) {
4055 nGoodTransactions = 0;
4056 pindexFailure = pindex;
4057 } else
4058 nGoodTransactions += block.vtx.size();
2d8a4829 4059 }
70477a0b
TZ
4060 if (ShutdownRequested())
4061 return true;
2d8a4829 4062 }
1f355b66 4063 if (pindexFailure)
5262fde0 4064 return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
1f355b66
PW
4065
4066 // check level 4: try reconnecting blocks
4067 if (nCheckLevel >= 4) {
4068 CBlockIndex *pindex = pindexState;
4c6d41b8 4069 while (pindex != chainActive.Tip()) {
b31499ec 4070 boost::this_thread::interruption_point();
06a91d96 4071 uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, 100 - (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * 50))));
4c6d41b8 4072 pindex = chainActive.Next(pindex);
b001c871 4073 CBlock block;
7db120d5 4074 if (!ReadBlockFromDisk(block, pindex))
5262fde0 4075 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
f3ae51dc 4076 if (!ConnectBlock(block, state, pindex, coins))
5262fde0 4077 return error("VerifyDB(): *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
1f355b66 4078 }
2d8a4829
PW
4079 }
4080
4c6d41b8 4081 LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive.Height() - pindexState->nHeight, nGoodTransactions);
1f355b66 4082
2d8a4829
PW
4083 return true;
4084}
4085
89f20450
PW
4086bool RewindBlockIndex(const CChainParams& params)
4087{
4088 LOCK(cs_main);
4089
9e851450 4090 // RewindBlockIndex is called after LoadBlockIndex, so at this point every block
828940b1
JG
4091 // index will have nCachedBranchId set based on the values previously persisted
4092 // to disk. By definition, a set nCachedBranchId means that the block was
9e851450
JG
4093 // fully-validated under the corresponding consensus rules. Thus we can quickly
4094 // identify whether the current active chain matches our expected sequence of
4095 // consensus rule changes, with two checks:
4096 //
4097 // - BLOCK_ACTIVATES_UPGRADE is set only on blocks that activate upgrades.
828940b1 4098 // - nCachedBranchId for each block matches what we expect.
9e851450
JG
4099 auto sufficientlyValidated = [&params](const CBlockIndex* pindex) {
4100 auto consensus = params.GetConsensus();
4101 bool fFlagSet = pindex->nStatus & BLOCK_ACTIVATES_UPGRADE;
4102 bool fFlagExpected = IsActivationHeightForAnyUpgrade(pindex->nHeight, consensus);
828940b1
JG
4103 return fFlagSet == fFlagExpected &&
4104 pindex->nCachedBranchId &&
4105 *pindex->nCachedBranchId == CurrentEpochBranchId(pindex->nHeight, consensus);
9e851450
JG
4106 };
4107
89f20450
PW
4108 int nHeight = 1;
4109 while (nHeight <= chainActive.Height()) {
9e851450 4110 if (!sufficientlyValidated(chainActive[nHeight])) {
89f20450
PW
4111 break;
4112 }
4113 nHeight++;
4114 }
4115
4116 // nHeight is now the height of the first insufficiently-validated block, or tipheight + 1
cb580c72
JG
4117 auto rewindLength = chainActive.Height() - nHeight;
4118 if (rewindLength > 0 && rewindLength > MAX_REORG_LENGTH) {
4119 auto pindexOldTip = chainActive.Tip();
4120 auto pindexRewind = chainActive[nHeight - 1];
4121 auto msg = strprintf(_(
4122 "A block chain rewind has been detected that would roll back %d blocks! "
4123 "This is larger than the maximum of %d blocks, and so the node is shutting down for your safety."
4124 ), rewindLength, MAX_REORG_LENGTH) + "\n\n" +
4125 _("Rewind details") + ":\n" +
4126 "- " + strprintf(_("Current tip: %s, height %d"),
4127 pindexOldTip->phashBlock->GetHex(), pindexOldTip->nHeight) + "\n" +
4128 "- " + strprintf(_("Rewinding to: %s, height %d"),
4129 pindexRewind->phashBlock->GetHex(), pindexRewind->nHeight) + "\n\n" +
4130 _("Please help, human!");
4131 LogPrintf("*** %s\n", msg);
4132 uiInterface.ThreadSafeMessageBox(msg, "", CClientUIInterface::MSG_ERROR);
4133 StartShutdown();
4134 return false;
4135 }
4136
89f20450
PW
4137 CValidationState state;
4138 CBlockIndex* pindex = chainActive.Tip();
4139 while (chainActive.Height() >= nHeight) {
4140 if (fPruneMode && !(chainActive.Tip()->nStatus & BLOCK_HAVE_DATA)) {
4141 // If pruning, don't try rewinding past the HAVE_DATA point;
4142 // since older blocks can't be served anyway, there's
4143 // no need to walk further, and trying to DisconnectTip()
4144 // will fail (and require a needless reindex/redownload
4145 // of the blockchain).
4146 break;
4147 }
4148 if (!DisconnectTip(state, true)) {
4149 return error("RewindBlockIndex: unable to disconnect block at height %i", pindex->nHeight);
4150 }
4151 // Occasionally flush state to disk.
4152 if (!FlushStateToDisk(state, FLUSH_STATE_PERIODIC))
4153 return false;
4154 }
4155
f5007d89 4156 // Collect blocks to be removed (blocks in mapBlockIndex must be at least BLOCK_VALID_TREE).
89f20450
PW
4157 // We do this after actual disconnecting, otherwise we'll end up writing the lack of data
4158 // to disk before writing the chainstate, resulting in a failure to continue if interrupted.
f5007d89 4159 std::vector<const CBlockIndex*> vBlocks;
89f20450
PW
4160 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
4161 CBlockIndex* pindexIter = it->second;
4162
4163 // Note: If we encounter an insufficiently validated block that
4164 // is on chainActive, it must be because we are a pruning node, and
4165 // this block or some successor doesn't HAVE_DATA, so we were unable to
4166 // rewind all the way. Blocks remaining on chainActive at this point
4167 // must not have their validity reduced.
9e851450 4168 if (!sufficientlyValidated(pindexIter) && !chainActive.Contains(pindexIter)) {
f5007d89
JG
4169 // Add to the list of blocks to remove
4170 vBlocks.push_back(pindexIter);
39ee63c8
JG
4171 if (pindexIter == pindexBestInvalid) {
4172 // Reset invalid block marker if it was pointing to this block
4173 pindexBestInvalid = NULL;
4174 }
9e851450 4175 // Update indices
89f20450 4176 setBlockIndexCandidates.erase(pindexIter);
9e851450 4177 auto ret = mapBlocksUnlinked.equal_range(pindexIter->pprev);
89f20450
PW
4178 while (ret.first != ret.second) {
4179 if (ret.first->second == pindexIter) {
4180 mapBlocksUnlinked.erase(ret.first++);
4181 } else {
4182 ++ret.first;
4183 }
4184 }
4185 } else if (pindexIter->IsValid(BLOCK_VALID_TRANSACTIONS) && pindexIter->nChainTx) {
4186 setBlockIndexCandidates.insert(pindexIter);
4187 }
4188 }
4189
f5007d89
JG
4190 // Set pindexBestHeader to the current chain tip
4191 // (since we are about to delete the block it is pointing to)
4192 pindexBestHeader = chainActive.Tip();
4193
4194 // Erase block indices on-disk
4195 if (!pblocktree->EraseBatchSync(vBlocks)) {
4196 return AbortNode(state, "Failed to erase from block index database");
4197 }
4198
4199 // Erase block indices in-memory
4200 for (auto pindex : vBlocks) {
4201 auto ret = mapBlockIndex.find(*pindex->phashBlock);
4202 if (ret != mapBlockIndex.end()) {
4203 mapBlockIndex.erase(ret);
4204 delete pindex;
4205 }
4206 }
4207
89f20450
PW
4208 PruneBlockIndexCandidates();
4209
4210 CheckBlockIndex();
4211
4212 if (!FlushStateToDisk(state, FLUSH_STATE_ALWAYS)) {
4213 return false;
4214 }
4215
4216 return true;
4217}
4218
f7f3a96b
PW
4219void UnloadBlockIndex()
4220{
51598b26 4221 LOCK(cs_main);
e17bd583 4222 setBlockIndexCandidates.clear();
4c6d41b8 4223 chainActive.SetTip(NULL);
85eb2cef 4224 pindexBestInvalid = NULL;
51598b26
PW
4225 pindexBestHeader = NULL;
4226 mempool.clear();
4227 mapOrphanTransactions.clear();
4228 mapOrphanTransactionsByPrev.clear();
4229 nSyncStarted = 0;
4230 mapBlocksUnlinked.clear();
4231 vinfoBlockFile.clear();
4232 nLastBlockFile = 0;
4233 nBlockSequenceId = 1;
4234 mapBlockSource.clear();
4235 mapBlocksInFlight.clear();
4236 nQueuedValidatedHeaders = 0;
4237 nPreferredDownload = 0;
4238 setDirtyBlockIndex.clear();
4239 setDirtyFileInfo.clear();
4240 mapNodeState.clear();
ec9b6c33 4241 recentRejects.reset(NULL);
51598b26
PW
4242
4243 BOOST_FOREACH(BlockMap::value_type& entry, mapBlockIndex) {
4244 delete entry.second;
4245 }
4246 mapBlockIndex.clear();
f9ec3f0f 4247 fHavePruned = false;
f7f3a96b
PW
4248}
4249
7fea4846 4250bool LoadBlockIndex()
0a61b0df 4251{
d979e6e3 4252 // Load block index from databases
2d1fa42e 4253 if (!fReindex && !LoadBlockIndexDB())
0a61b0df 4254 return false;
38603761
PW
4255 return true;
4256}
2d1fa42e 4257
2d1fa42e 4258
38603761 4259bool InitBlockIndex() {
e6973430 4260 const CChainParams& chainparams = Params();
55a1db4f 4261 LOCK(cs_main);
5094a81d
WL
4262
4263 // Initialize global variables that cannot be constructed at startup.
4264 recentRejects.reset(new CRollingBloomFilter(120000, 0.000001));
4265
38603761 4266 // Check whether we're already initialized
4c6d41b8 4267 if (chainActive.Genesis() != NULL)
38603761
PW
4268 return true;
4269
4270 // Use the provided setting for -txindex in the new database
4271 fTxIndex = GetBoolArg("-txindex", false);
4272 pblocktree->WriteFlag("txindex", fTxIndex);
881a85a2 4273 LogPrintf("Initializing databases...\n");
38603761
PW
4274
4275 // Only add the genesis block if not reindexing (in which case we reuse the one already on disk)
4276 if (!fReindex) {
38603761 4277 try {
0e4b3175
MH
4278 CBlock &block = const_cast<CBlock&>(Params().GenesisBlock());
4279 // Start new block file
38603761
PW
4280 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
4281 CDiskBlockPos blockPos;
4282 CValidationState state;
209377a7 4283 if (!FindBlockPos(state, blockPos, nBlockSize+8, 0, block.GetBlockTime()))
5262fde0 4284 return error("LoadBlockIndex(): FindBlockPos failed");
e6973430 4285 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
5262fde0 4286 return error("LoadBlockIndex(): writing genesis block to disk failed");
942b33a1
PW
4287 CBlockIndex *pindex = AddToBlockIndex(block);
4288 if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
5262fde0 4289 return error("LoadBlockIndex(): genesis block not accepted");
92bb6f2f 4290 if (!ActivateBestChain(state, &block))
5262fde0 4291 return error("LoadBlockIndex(): genesis block cannot be activated");
bf7835c2 4292 // Force a chainstate write so that when we VerifyDB in a moment, it doesn't check stale data
a2069500 4293 return FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
27df4123 4294 } catch (const std::runtime_error& e) {
5262fde0 4295 return error("LoadBlockIndex(): failed to initialize block database: %s", e.what());
38603761 4296 }
0a61b0df 4297 }
4298
4299 return true;
4300}
4301
4302
4303
7fea4846 4304bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp)
1d740055 4305{
4e382177 4306 const CChainParams& chainparams = Params();
ad96e7cc
WL
4307 // Map of disk positions for blocks with unknown parent (only used for reindex)
4308 static std::multimap<uint256, CDiskBlockPos> mapBlocksUnknownParent;
51ed9ec9 4309 int64_t nStart = GetTimeMillis();
746f502a 4310
1d740055 4311 int nLoaded = 0;
421218d3 4312 try {
c9fb27da 4313 // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor
05d97268 4314 CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SIZE, MAX_BLOCK_SIZE+8, SER_DISK, CLIENT_VERSION);
51ed9ec9 4315 uint64_t nRewind = blkdat.GetPos();
eb0b56b1 4316 while (!blkdat.eof()) {
21eb5ada
GA
4317 boost::this_thread::interruption_point();
4318
05d97268
PW
4319 blkdat.SetPos(nRewind);
4320 nRewind++; // start one byte further next time, in case of failure
4321 blkdat.SetLimit(); // remove former limit
7fea4846 4322 unsigned int nSize = 0;
05d97268
PW
4323 try {
4324 // locate a header
0caf2b18 4325 unsigned char buf[MESSAGE_START_SIZE];
0e4b3175 4326 blkdat.FindByte(Params().MessageStart()[0]);
05d97268
PW
4327 nRewind = blkdat.GetPos()+1;
4328 blkdat >> FLATDATA(buf);
0caf2b18 4329 if (memcmp(buf, Params().MessageStart(), MESSAGE_START_SIZE))
05d97268
PW
4330 continue;
4331 // read size
1d740055 4332 blkdat >> nSize;
05d97268
PW
4333 if (nSize < 80 || nSize > MAX_BLOCK_SIZE)
4334 continue;
27df4123 4335 } catch (const std::exception&) {
7fea4846
PW
4336 // no valid block header found; don't complain
4337 break;
4338 }
4339 try {
05d97268 4340 // read block
51ed9ec9 4341 uint64_t nBlockPos = blkdat.GetPos();
ad96e7cc
WL
4342 if (dbp)
4343 dbp->nPos = nBlockPos;
7fea4846 4344 blkdat.SetLimit(nBlockPos + nSize);
16d51941
PW
4345 blkdat.SetPos(nBlockPos);
4346 CBlock block;
4347 blkdat >> block;
ad96e7cc
WL
4348 nRewind = blkdat.GetPos();
4349
16d51941
PW
4350 // detect out of order blocks, and store them for later
4351 uint256 hash = block.GetHash();
4e382177 4352 if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex.find(block.hashPrevBlock) == mapBlockIndex.end()) {
ad96e7cc 4353 LogPrint("reindex", "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(),
16d51941 4354 block.hashPrevBlock.ToString());
ad96e7cc 4355 if (dbp)
16d51941 4356 mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp));
ad96e7cc
WL
4357 continue;
4358 }
4359
16d51941 4360 // process in case the block isn't known yet
8375e221 4361 if (mapBlockIndex.count(hash) == 0 || (mapBlockIndex[hash]->nStatus & BLOCK_HAVE_DATA) == 0) {
16d51941 4362 CValidationState state;
304892fc 4363 if (ProcessNewBlock(state, NULL, &block, true, dbp))
16d51941
PW
4364 nLoaded++;
4365 if (state.IsError())
4366 break;
4e382177 4367 } else if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex[hash]->nHeight % 1000 == 0) {
50b43fda 4368 LogPrintf("Block Import: already had block %s at height %d\n", hash.ToString(), mapBlockIndex[hash]->nHeight);
16d51941 4369 }
ad96e7cc
WL
4370
4371 // Recursively process earlier encountered successors of this block
4372 deque<uint256> queue;
4373 queue.push_back(hash);
4374 while (!queue.empty()) {
4375 uint256 head = queue.front();
4376 queue.pop_front();
4377 std::pair<std::multimap<uint256, CDiskBlockPos>::iterator, std::multimap<uint256, CDiskBlockPos>::iterator> range = mapBlocksUnknownParent.equal_range(head);
4378 while (range.first != range.second) {
4379 std::multimap<uint256, CDiskBlockPos>::iterator it = range.first;
4380 if (ReadBlockFromDisk(block, it->second))
4381 {
4382 LogPrintf("%s: Processing out of order child %s of %s\n", __func__, block.GetHash().ToString(),
4383 head.ToString());
4384 CValidationState dummy;
304892fc 4385 if (ProcessNewBlock(dummy, NULL, &block, true, &it->second))
ad96e7cc
WL
4386 {
4387 nLoaded++;
4388 queue.push_back(block.GetHash());
4389 }
4390 }
4391 range.first++;
4392 mapBlocksUnknownParent.erase(it);
4393 }
1d740055 4394 }
27df4123 4395 } catch (const std::exception& e) {
7ff9d122 4396 LogPrintf("%s: Deserialize or I/O error - %s\n", __func__, e.what());
1d740055
PW
4397 }
4398 }
27df4123 4399 } catch (const std::runtime_error& e) {
b9b2e3fa 4400 AbortNode(std::string("System error: ") + e.what());
1d740055 4401 }
7fea4846 4402 if (nLoaded > 0)
f48742c2 4403 LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart);
1d740055
PW
4404 return nLoaded > 0;
4405}
0a61b0df 4406
3fcfbc8a
PW
4407void static CheckBlockIndex()
4408{
4e382177 4409 const Consensus::Params& consensusParams = Params().GetConsensus();
3fcfbc8a
PW
4410 if (!fCheckBlockIndex) {
4411 return;
4412 }
4413
4414 LOCK(cs_main);
4415
0421c18f 4416 // During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain,
4417 // so we have the genesis block in mapBlockIndex but no active chain. (A few of the tests when
4418 // iterating the block tree require that chainActive has been initialized.)
4419 if (chainActive.Height() < 0) {
4420 assert(mapBlockIndex.size() <= 1);
4421 return;
4422 }
4423
3fcfbc8a
PW
4424 // Build forward-pointing map of the entire block tree.
4425 std::multimap<CBlockIndex*,CBlockIndex*> forward;
4426 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
4427 forward.insert(std::make_pair(it->second->pprev, it->second));
4428 }
4429
4430 assert(forward.size() == mapBlockIndex.size());
4431
4432 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeGenesis = forward.equal_range(NULL);
4433 CBlockIndex *pindex = rangeGenesis.first->second;
4434 rangeGenesis.first++;
4435 assert(rangeGenesis.first == rangeGenesis.second); // There is only one index entry with parent NULL.
4436
4437 // Iterate over the entire block tree, using depth-first search.
4438 // Along the way, remember whether there are blocks on the path from genesis
4439 // block being explored which are the first to have certain properties.
4440 size_t nNodes = 0;
4441 int nHeight = 0;
4442 CBlockIndex* pindexFirstInvalid = NULL; // Oldest ancestor of pindex which is invalid.
4443 CBlockIndex* pindexFirstMissing = NULL; // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA.
f9ec3f0f 4444 CBlockIndex* pindexFirstNeverProcessed = NULL; // Oldest ancestor of pindex for which nTx == 0.
3fcfbc8a 4445 CBlockIndex* pindexFirstNotTreeValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not).
ede379f7 4446 CBlockIndex* pindexFirstNotTransactionsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TRANSACTIONS (regardless of being valid or not).
3fcfbc8a
PW
4447 CBlockIndex* pindexFirstNotChainValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not).
4448 CBlockIndex* pindexFirstNotScriptsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not).
4449 while (pindex != NULL) {
4450 nNodes++;
4451 if (pindexFirstInvalid == NULL && pindex->nStatus & BLOCK_FAILED_VALID) pindexFirstInvalid = pindex;
4452 if (pindexFirstMissing == NULL && !(pindex->nStatus & BLOCK_HAVE_DATA)) pindexFirstMissing = pindex;
f9ec3f0f 4453 if (pindexFirstNeverProcessed == NULL && pindex->nTx == 0) pindexFirstNeverProcessed = pindex;
3fcfbc8a 4454 if (pindex->pprev != NULL && pindexFirstNotTreeValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TREE) pindexFirstNotTreeValid = pindex;
ede379f7 4455 if (pindex->pprev != NULL && pindexFirstNotTransactionsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TRANSACTIONS) pindexFirstNotTransactionsValid = pindex;
3fcfbc8a
PW
4456 if (pindex->pprev != NULL && pindexFirstNotChainValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CHAIN) pindexFirstNotChainValid = pindex;
4457 if (pindex->pprev != NULL && pindexFirstNotScriptsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) pindexFirstNotScriptsValid = pindex;
4458
4459 // Begin: actual consistency checks.
4460 if (pindex->pprev == NULL) {
4461 // Genesis block checks.
4e382177 4462 assert(pindex->GetBlockHash() == consensusParams.hashGenesisBlock); // Genesis block's hash must match.
3fcfbc8a
PW
4463 assert(pindex == chainActive.Genesis()); // The current active chain's genesis block must be this block.
4464 }
c1ecee8f 4465 if (pindex->nChainTx == 0) assert(pindex->nSequenceId == 0); // nSequenceId can't be set for blocks that aren't linked
f9ec3f0f 4466 // VALID_TRANSACTIONS is equivalent to nTx > 0 for all nodes (whether or not pruning has occurred).
4467 // HAVE_DATA is only equivalent to nTx > 0 (or VALID_TRANSACTIONS) if no pruning has occurred.
4468 if (!fHavePruned) {
4469 // If we've never pruned, then HAVE_DATA should be equivalent to nTx > 0
4470 assert(!(pindex->nStatus & BLOCK_HAVE_DATA) == (pindex->nTx == 0));
4471 assert(pindexFirstMissing == pindexFirstNeverProcessed);
4472 } else {
4473 // If we have pruned, then we can only say that HAVE_DATA implies nTx > 0
4474 if (pindex->nStatus & BLOCK_HAVE_DATA) assert(pindex->nTx > 0);
4475 }
4476 if (pindex->nStatus & BLOCK_HAVE_UNDO) assert(pindex->nStatus & BLOCK_HAVE_DATA);
4477 assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS) == (pindex->nTx > 0)); // This is pruning-independent.
4478 // All parents having had data (at some point) is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to nChainTx being set.
4479 assert((pindexFirstNeverProcessed != NULL) == (pindex->nChainTx == 0)); // nChainTx != 0 is used to signal that all parent blocks have been processed (but may have been pruned).
ede379f7 4480 assert((pindexFirstNotTransactionsValid != NULL) == (pindex->nChainTx == 0));
3fcfbc8a
PW
4481 assert(pindex->nHeight == nHeight); // nHeight must be consistent.
4482 assert(pindex->pprev == NULL || pindex->nChainWork >= pindex->pprev->nChainWork); // For every block except the genesis block, the chainwork must be larger than the parent's.
4483 assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->nHeight < nHeight))); // The pskip pointer must point back for all but the first 2 blocks.
4484 assert(pindexFirstNotTreeValid == NULL); // All mapBlockIndex entries must at least be TREE valid
4485 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE) assert(pindexFirstNotTreeValid == NULL); // TREE valid implies all parents are TREE valid
4486 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CHAIN) assert(pindexFirstNotChainValid == NULL); // CHAIN valid implies all parents are CHAIN valid
4487 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_SCRIPTS) assert(pindexFirstNotScriptsValid == NULL); // SCRIPTS valid implies all parents are SCRIPTS valid
4488 if (pindexFirstInvalid == NULL) {
4489 // Checks for not-invalid blocks.
4490 assert((pindex->nStatus & BLOCK_FAILED_MASK) == 0); // The failed mask cannot be set for blocks without invalid parents.
4491 }
f9ec3f0f 4492 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && pindexFirstNeverProcessed == NULL) {
4493 if (pindexFirstInvalid == NULL) {
4494 // If this block sorts at least as good as the current tip and
4495 // is valid and we have all data for its parents, it must be in
4496 // setBlockIndexCandidates. chainActive.Tip() must also be there
4497 // even if some data has been pruned.
4498 if (pindexFirstMissing == NULL || pindex == chainActive.Tip()) {
4499 assert(setBlockIndexCandidates.count(pindex));
4500 }
4501 // If some parent is missing, then it could be that this block was in
4502 // setBlockIndexCandidates but had to be removed because of the missing data.
4503 // In this case it must be in mapBlocksUnlinked -- see test below.
3fcfbc8a 4504 }
f9ec3f0f 4505 } else { // If this block sorts worse than the current tip or some ancestor's block has never been seen, it cannot be in setBlockIndexCandidates.
3fcfbc8a
PW
4506 assert(setBlockIndexCandidates.count(pindex) == 0);
4507 }
4508 // Check whether this block is in mapBlocksUnlinked.
4509 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeUnlinked = mapBlocksUnlinked.equal_range(pindex->pprev);
4510 bool foundInUnlinked = false;
4511 while (rangeUnlinked.first != rangeUnlinked.second) {
4512 assert(rangeUnlinked.first->first == pindex->pprev);
4513 if (rangeUnlinked.first->second == pindex) {
4514 foundInUnlinked = true;
4515 break;
4516 }
4517 rangeUnlinked.first++;
4518 }
f9ec3f0f 4519 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed != NULL && pindexFirstInvalid == NULL) {
4520 // If this block has block data available, some parent was never received, and has no invalid parents, it must be in mapBlocksUnlinked.
4521 assert(foundInUnlinked);
4522 }
4523 if (!(pindex->nStatus & BLOCK_HAVE_DATA)) assert(!foundInUnlinked); // Can't be in mapBlocksUnlinked if we don't HAVE_DATA
4524 if (pindexFirstMissing == NULL) assert(!foundInUnlinked); // We aren't missing data for any parent -- cannot be in mapBlocksUnlinked.
4525 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed == NULL && pindexFirstMissing != NULL) {
4526 // We HAVE_DATA for this block, have received data for all parents at some point, but we're currently missing data for some parent.
4527 assert(fHavePruned); // We must have pruned.
4528 // This block may have entered mapBlocksUnlinked if:
4529 // - it has a descendant that at some point had more work than the
4530 // tip, and
4531 // - we tried switching to that descendant but were missing
4532 // data for some intermediate block between chainActive and the
4533 // tip.
4534 // So if this block is itself better than chainActive.Tip() and it wasn't in
4535 // setBlockIndexCandidates, then it must be in mapBlocksUnlinked.
4536 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && setBlockIndexCandidates.count(pindex) == 0) {
4537 if (pindexFirstInvalid == NULL) {
4538 assert(foundInUnlinked);
4539 }
3fcfbc8a 4540 }
3fcfbc8a
PW
4541 }
4542 // assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow
4543 // End: actual consistency checks.
4544
4545 // Try descending into the first subnode.
4546 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> range = forward.equal_range(pindex);
4547 if (range.first != range.second) {
4548 // A subnode was found.
4549 pindex = range.first->second;
4550 nHeight++;
4551 continue;
4552 }
4553 // This is a leaf node.
4554 // Move upwards until we reach a node of which we have not yet visited the last child.
4555 while (pindex) {
4556 // We are going to either move to a parent or a sibling of pindex.
4557 // If pindex was the first with a certain property, unset the corresponding variable.
4558 if (pindex == pindexFirstInvalid) pindexFirstInvalid = NULL;
4559 if (pindex == pindexFirstMissing) pindexFirstMissing = NULL;
f9ec3f0f 4560 if (pindex == pindexFirstNeverProcessed) pindexFirstNeverProcessed = NULL;
3fcfbc8a 4561 if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = NULL;
ede379f7 4562 if (pindex == pindexFirstNotTransactionsValid) pindexFirstNotTransactionsValid = NULL;
3fcfbc8a
PW
4563 if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = NULL;
4564 if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = NULL;
4565 // Find our parent.
4566 CBlockIndex* pindexPar = pindex->pprev;
4567 // Find which child we just visited.
4568 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangePar = forward.equal_range(pindexPar);
4569 while (rangePar.first->second != pindex) {
4570 assert(rangePar.first != rangePar.second); // Our parent must have at least the node we're coming from as child.
4571 rangePar.first++;
4572 }
4573 // Proceed to the next one.
4574 rangePar.first++;
4575 if (rangePar.first != rangePar.second) {
4576 // Move to the sibling.
4577 pindex = rangePar.first->second;
4578 break;
4579 } else {
4580 // Move up further.
4581 pindex = pindexPar;
4582 nHeight--;
4583 continue;
4584 }
4585 }
4586 }
4587
4588 // Check that we actually traversed the entire map.
4589 assert(nNodes == forward.size());
4590}
4591
0a61b0df 4592//////////////////////////////////////////////////////////////////////////////
4593//
4594// CAlert
4595//
4596
db954a65 4597std::string GetWarnings(const std::string& strFor)
0a61b0df 4598{
4599 int nPriority = 0;
4600 string strStatusBar;
4601 string strRPC;
62e21fb5 4602
62e21fb5
WL
4603 if (!CLIENT_VERSION_IS_RELEASE)
4604 strStatusBar = _("This is a pre-release test build - use at your own risk - do not use for mining or merchant applications");
4605
73578933 4606 if (GetBoolArg("-testsafemode", false))
4607 strStatusBar = strRPC = "testsafemode enabled";
4608
0a61b0df 4609 // Misc warnings like out of disk space and clock is wrong
4610 if (strMiscWarning != "")
4611 {
4612 nPriority = 1000;
4613 strStatusBar = strMiscWarning;
4614 }
4615
b8585384 4616 if (fLargeWorkForkFound)
0a61b0df 4617 {
4618 nPriority = 2000;
f65e7092
MC
4619 strStatusBar = strRPC = _("Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.");
4620 }
4621 else if (fLargeWorkInvalidChainFound)
0a61b0df 4622 {
4623 nPriority = 2000;
f65e7092 4624 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.");
0a61b0df 4625 }
4626
4627 // Alerts
0a61b0df 4628 {
f8dcd5ca 4629 LOCK(cs_mapAlerts);
223b6f1b 4630 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
0a61b0df 4631 {
4632 const CAlert& alert = item.second;
4633 if (alert.AppliesToMe() && alert.nPriority > nPriority)
4634 {
4635 nPriority = alert.nPriority;
4636 strStatusBar = alert.strStatusBar;
a40034f7
JG
4637 if (alert.nPriority >= ALERT_PRIORITY_SAFE_MODE) {
4638 strRPC = alert.strRPCError;
4639 }
0a61b0df 4640 }
4641 }
4642 }
4643
4644 if (strFor == "statusbar")
4645 return strStatusBar;
4646 else if (strFor == "rpc")
4647 return strRPC;
5262fde0 4648 assert(!"GetWarnings(): invalid parameter");
0a61b0df 4649 return "error";
4650}
4651
0a61b0df 4652
4653
4654
4655
4656
4657
4658
4659//////////////////////////////////////////////////////////////////////////////
4660//
4661// Messages
4662//
4663
4664
72b25b0f 4665bool static AlreadyHave(const CInv& inv) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
0a61b0df 4666{
4667 switch (inv.type)
4668 {
8deb9822
JG
4669 case MSG_TX:
4670 {
5094a81d 4671 assert(recentRejects);
ec9b6c33
PT
4672 if (chainActive.Tip()->GetBlockHash() != hashRecentRejectsChainTip)
4673 {
4674 // If the chain tip has changed previously rejected transactions
4675 // might be now valid, e.g. due to a nLockTime'd tx becoming valid,
4676 // or a double-spend. Reset the rejects filter and give those
4677 // txs a second chance.
4678 hashRecentRejectsChainTip = chainActive.Tip()->GetBlockHash();
4679 recentRejects->reset();
4680 }
4681
4682 return recentRejects->contains(inv.hash) ||
4683 mempool.exists(inv.hash) ||
4684 mapOrphanTransactions.count(inv.hash) ||
4685 pcoinsTip->HaveCoins(inv.hash);
8deb9822 4686 }
8deb9822 4687 case MSG_BLOCK:
341735eb 4688 return mapBlockIndex.count(inv.hash);
0a61b0df 4689 }
4690 // Don't know what it is, just say we already got one
4691 return true;
4692}
4693
c7f039b6
PW
4694void static ProcessGetData(CNode* pfrom)
4695{
4696 std::deque<CInv>::iterator it = pfrom->vRecvGetData.begin();
4697
4698 vector<CInv> vNotFound;
4699
7d38af3c
PW
4700 LOCK(cs_main);
4701
c7f039b6
PW
4702 while (it != pfrom->vRecvGetData.end()) {
4703 // Don't bother if send buffer is too full to respond anyway
4704 if (pfrom->nSendSize >= SendBufferSize())
4705 break;
4706
4707 const CInv &inv = *it;
4708 {
b31499ec 4709 boost::this_thread::interruption_point();
c7f039b6
PW
4710 it++;
4711
4712 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
4713 {
d8b4b496 4714 bool send = false;
145d5be8 4715 BlockMap::iterator mi = mapBlockIndex.find(inv.hash);
c7f039b6
PW
4716 if (mi != mapBlockIndex.end())
4717 {
85da07a5 4718 if (chainActive.Contains(mi->second)) {
2b45345a 4719 send = true;
85da07a5 4720 } else {
f7303f97 4721 static const int nOneMonth = 30 * 24 * 60 * 60;
85da07a5 4722 // To prevent fingerprinting attacks, only send blocks outside of the active
f7303f97
PW
4723 // chain if they are valid, and no more than a month older (both in time, and in
4724 // best equivalent proof of work) than the best header chain we know about.
85da07a5 4725 send = mi->second->IsValid(BLOCK_VALID_SCRIPTS) && (pindexBestHeader != NULL) &&
f7303f97
PW
4726 (pindexBestHeader->GetBlockTime() - mi->second->GetBlockTime() < nOneMonth) &&
4727 (GetBlockProofEquivalentTime(*pindexBestHeader, *mi->second, *pindexBestHeader, Params().GetConsensus()) < nOneMonth);
85da07a5 4728 if (!send) {
30c1db1c 4729 LogPrintf("%s: ignoring request from peer=%i for old block that isn't in the main chain\n", __func__, pfrom->GetId());
85da07a5 4730 }
d8b4b496
AH
4731 }
4732 }
f9ec3f0f 4733 // Pruned nodes may have deleted the block, so check whether
4734 // it's available before trying to send.
4735 if (send && (mi->second->nStatus & BLOCK_HAVE_DATA))
d8b4b496
AH
4736 {
4737 // Send block from disk
c7f039b6 4738 CBlock block;
4a48a067
WL
4739 if (!ReadBlockFromDisk(block, (*mi).second))
4740 assert(!"cannot load block from disk");
c7f039b6
PW
4741 if (inv.type == MSG_BLOCK)
4742 pfrom->PushMessage("block", block);
4743 else // MSG_FILTERED_BLOCK)
4744 {
4745 LOCK(pfrom->cs_filter);
4746 if (pfrom->pfilter)
4747 {
4748 CMerkleBlock merkleBlock(block, *pfrom->pfilter);
4749 pfrom->PushMessage("merkleblock", merkleBlock);
4750 // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
4751 // This avoids hurting performance by pointlessly requiring a round-trip
7e6d23b1 4752 // Note that there is currently no way for a node to request any single transactions we didn't send here -
c7f039b6
PW
4753 // they must either disconnect and retry or request the full block.
4754 // Thus, the protocol spec specified allows for us to provide duplicate txn here,
4755 // however we MUST always provide at least what the remote peer needs
4756 typedef std::pair<unsigned int, uint256> PairType;
4757 BOOST_FOREACH(PairType& pair, merkleBlock.vMatchedTxn)
4758 if (!pfrom->setInventoryKnown.count(CInv(MSG_TX, pair.second)))
4759 pfrom->PushMessage("tx", block.vtx[pair.first]);
4760 }
4761 // else
4762 // no response
4763 }
4764
b05a89b2 4765 // Trigger the peer node to send a getblocks request for the next batch of inventory
c7f039b6
PW
4766 if (inv.hash == pfrom->hashContinue)
4767 {
4768 // Bypass PushInventory, this must send even if redundant,
4769 // and we want it right after the last block so they don't
4770 // wait for other stuff first.
4771 vector<CInv> vInv;
4c6d41b8 4772 vInv.push_back(CInv(MSG_BLOCK, chainActive.Tip()->GetBlockHash()));
c7f039b6 4773 pfrom->PushMessage("inv", vInv);
4f152496 4774 pfrom->hashContinue.SetNull();
c7f039b6
PW
4775 }
4776 }
4777 }
4778 else if (inv.IsKnownType())
4779 {
4780 // Send stream from relay memory
4781 bool pushed = false;
4782 {
4783 LOCK(cs_mapRelay);
4784 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
4785 if (mi != mapRelay.end()) {
4786 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
4787 pushed = true;
4788 }
4789 }
4790 if (!pushed && inv.type == MSG_TX) {
319b1160
GA
4791 CTransaction tx;
4792 if (mempool.lookup(inv.hash, tx)) {
c7f039b6
PW
4793 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
4794 ss.reserve(1000);
4795 ss << tx;
4796 pfrom->PushMessage("tx", ss);
4797 pushed = true;
4798 }
4799 }
4800 if (!pushed) {
4801 vNotFound.push_back(inv);
4802 }
4803 }
4804
4805 // Track requests for our stuff.
26c16d9d 4806 GetMainSignals().Inventory(inv.hash);
cd696e64 4807
75ef87dd
PS
4808 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
4809 break;
c7f039b6
PW
4810 }
4811 }
4812
4813 pfrom->vRecvGetData.erase(pfrom->vRecvGetData.begin(), it);
4814
4815 if (!vNotFound.empty()) {
4816 // Let the peer know that we didn't find what it asked for, so it doesn't
4817 // have to wait around forever. Currently only SPV clients actually care
4818 // about this message: it's needed when they are recursively walking the
4819 // dependencies of relevant unconfirmed transactions. SPV clients want to
4820 // do that because they want to know about (and store and rebroadcast and
4821 // risk analyze) the dependencies of transactions relevant to them, without
4822 // having to download the entire memory pool.
4823 pfrom->PushMessage("notfound", vNotFound);
4824 }
4825}
4826
9f4da19b 4827bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, int64_t nTimeReceived)
0a61b0df 4828{
e8e8904d 4829 const CChainParams& chainparams = Params();
28d4cff0 4830 LogPrint("net", "received: %s (%u bytes) peer=%d\n", SanitizeString(strCommand), vRecv.size(), pfrom->id);
0a61b0df 4831 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
4832 {
881a85a2 4833 LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n");
0a61b0df 4834 return true;
4835 }
4836
0a61b0df 4837
0a61b0df 4838 if (strCommand == "version")
4839 {
4840 // Each connection can only send one version message
4841 if (pfrom->nVersion != 0)
806704c2 4842 {
358ce266 4843 pfrom->PushMessage("reject", strCommand, REJECT_DUPLICATE, string("Duplicate version message"));
b2864d2f 4844 Misbehaving(pfrom->GetId(), 1);
0a61b0df 4845 return false;
806704c2 4846 }
0a61b0df 4847
51ed9ec9 4848 int64_t nTime;
0a61b0df 4849 CAddress addrMe;
4850 CAddress addrFrom;
51ed9ec9 4851 uint64_t nNonce = 1;
0a61b0df 4852 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
1ce41892 4853 if (pfrom->nVersion < MIN_PEER_PROTO_VERSION)
18c0fa97 4854 {
1ce41892 4855 // disconnect from peers older than this proto version
2e36866f 4856 LogPrintf("peer=%d using obsolete version %i; disconnecting\n", pfrom->id, pfrom->nVersion);
358ce266
GA
4857 pfrom->PushMessage("reject", strCommand, REJECT_OBSOLETE,
4858 strprintf("Version must be %d or greater", MIN_PEER_PROTO_VERSION));
18c0fa97
PW
4859 pfrom->fDisconnect = true;
4860 return false;
4861 }
4862
72b21929
S
4863 // When Overwinter is active, reject incoming connections from non-Overwinter nodes
4864 const Consensus::Params& params = Params().GetConsensus();
4865 if (NetworkUpgradeActive(GetHeight(), params, Consensus::UPGRADE_OVERWINTER)
4866 && pfrom->nVersion < params.vUpgrades[Consensus::UPGRADE_OVERWINTER].nProtocolVersion)
4867 {
4868 LogPrintf("peer=%d using obsolete version %i; disconnecting\n", pfrom->id, pfrom->nVersion);
4869 pfrom->PushMessage("reject", strCommand, REJECT_OBSOLETE,
4870 strprintf("Version must be %d or greater",
4871 params.vUpgrades[Consensus::UPGRADE_OVERWINTER].nProtocolVersion));
4872 pfrom->fDisconnect = true;
4873 return false;
4874 }
4875
9ad9a25e
SB
4876 if (pfrom->nVersion == 10300)
4877 pfrom->nVersion = 300;
18c0fa97 4878 if (!vRecv.empty())
0a61b0df 4879 vRecv >> addrFrom >> nNonce;
a946aa8d 4880 if (!vRecv.empty()) {
2bc62dc4 4881 vRecv >> LIMITED_STRING(pfrom->strSubVer, MAX_SUBVERSION_LENGTH);
a946aa8d
MH
4882 pfrom->cleanSubVer = SanitizeString(pfrom->strSubVer);
4883 }
18c0fa97 4884 if (!vRecv.empty())
0a61b0df 4885 vRecv >> pfrom->nStartingHeight;
4c8fc1a5
MC
4886 if (!vRecv.empty())
4887 vRecv >> pfrom->fRelayTxes; // set to true after we get the first filter* message
4888 else
4889 pfrom->fRelayTxes = true;
0a61b0df 4890
0a61b0df 4891 // Disconnect if we connected to ourself
4892 if (nNonce == nLocalHostNonce && nNonce > 1)
4893 {
7d9d134b 4894 LogPrintf("connected to self at %s, disconnecting\n", pfrom->addr.ToString());
0a61b0df 4895 pfrom->fDisconnect = true;
4896 return true;
4897 }
4898
845c86d1
GM
4899 pfrom->addrLocal = addrMe;
4900 if (pfrom->fInbound && addrMe.IsRoutable())
4901 {
4902 SeenLocal(addrMe);
4903 }
4904
cbc920d4
GA
4905 // Be shy and don't send version until we hear
4906 if (pfrom->fInbound)
4907 pfrom->PushVersion();
4908
0a61b0df 4909 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
0a61b0df 4910
b4ee0bdd
PW
4911 // Potentially mark this peer as a preferred download peer.
4912 UpdatePreferredDownload(pfrom, State(pfrom->GetId()));
0a61b0df 4913
4914 // Change version
18c0fa97 4915 pfrom->PushMessage("verack");
41b052ad 4916 pfrom->ssSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
0a61b0df 4917
c891967b 4918 if (!pfrom->fInbound)
4919 {
4920 // Advertise our address
53a08815 4921 if (fListen && !IsInitialBlockDownload())
c891967b 4922 {
39857190
PW
4923 CAddress addr = GetLocalAddress(&pfrom->addr);
4924 if (addr.IsRoutable())
845c86d1 4925 {
eb5f63fe 4926 LogPrintf("ProcessMessages: advertizing address %s\n", addr.ToString());
845c86d1
GM
4927 pfrom->PushAddress(addr);
4928 } else if (IsPeerAddrLocalGood(pfrom)) {
4929 addr.SetIP(pfrom->addrLocal);
eb5f63fe 4930 LogPrintf("ProcessMessages: advertizing address %s\n", addr.ToString());
39857190 4931 pfrom->PushAddress(addr);
845c86d1 4932 }
c891967b 4933 }
4934
4935 // Get recent addresses
15a99376
SB
4936 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
4937 {
4938 pfrom->PushMessage("getaddr");
4939 pfrom->fGetAddr = true;
4940 }
5fee401f
PW
4941 addrman.Good(pfrom->addr);
4942 } else {
4943 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
4944 {
4945 addrman.Add(addrFrom, addrFrom);
4946 addrman.Good(addrFrom);
4947 }
c891967b 4948 }
4949
0a61b0df 4950 // Relay alerts
f8dcd5ca
PW
4951 {
4952 LOCK(cs_mapAlerts);
223b6f1b 4953 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
0a61b0df 4954 item.second.RelayTo(pfrom);
f8dcd5ca 4955 }
0a61b0df 4956
4957 pfrom->fSuccessfullyConnected = true;
4958
70b9d36a
JG
4959 string remoteAddr;
4960 if (fLogIPs)
4961 remoteAddr = ", peeraddr=" + pfrom->addr.ToString();
4962
4963 LogPrintf("receive version message: %s: version %d, blocks=%d, us=%s, peer=%d%s\n",
4964 pfrom->cleanSubVer, pfrom->nVersion,
4965 pfrom->nStartingHeight, addrMe.ToString(), pfrom->id,
4966 remoteAddr);
a8b95ce6 4967
26a6bae7
PJ
4968 int64_t nTimeOffset = nTime - GetTime();
4969 pfrom->nTimeOffset = nTimeOffset;
4970 AddTimeData(pfrom->addr, nTimeOffset);
0a61b0df 4971 }
4972
4973
4974 else if (pfrom->nVersion == 0)
4975 {
4976 // Must have a version message before anything else
b2864d2f 4977 Misbehaving(pfrom->GetId(), 1);
0a61b0df 4978 return false;
4979 }
4980
4981
4982 else if (strCommand == "verack")
4983 {
607dbfde 4984 pfrom->SetRecvVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
9c273790
PW
4985
4986 // Mark this node as currently connected, so we update its timestamp later.
4987 if (pfrom->fNetworkNode) {
4988 LOCK(cs_main);
4989 State(pfrom->GetId())->fCurrentlyConnected = true;
4990 }
0a61b0df 4991 }
4992
4993
72b21929
S
4994 // Disconnect existing peer connection when:
4995 // 1. The version message has been received
4996 // 2. Overwinter is active
4997 // 3. Peer version is pre-Overwinter
4998 else if (NetworkUpgradeActive(GetHeight(), chainparams.GetConsensus(), Consensus::UPGRADE_OVERWINTER)
4999 && (pfrom->nVersion < chainparams.GetConsensus().vUpgrades[Consensus::UPGRADE_OVERWINTER].nProtocolVersion))
5000 {
5001 LogPrintf("peer=%d using obsolete version %i; disconnecting\n", pfrom->id, pfrom->nVersion);
5002 pfrom->PushMessage("reject", strCommand, REJECT_OBSOLETE,
5003 strprintf("Version must be %d or greater",
5004 chainparams.GetConsensus().vUpgrades[Consensus::UPGRADE_OVERWINTER].nProtocolVersion));
5005 pfrom->fDisconnect = true;
5006 return false;
5007 }
5008
5009
0a61b0df 5010 else if (strCommand == "addr")
5011 {
5012 vector<CAddress> vAddr;
5013 vRecv >> vAddr;
c891967b 5014
15a99376
SB
5015 // Don't want addr from older versions unless seeding
5016 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
5017 return true;
0a61b0df 5018 if (vAddr.size() > 1000)
806704c2 5019 {
b2864d2f 5020 Misbehaving(pfrom->GetId(), 20);
783b182c 5021 return error("message addr size() = %u", vAddr.size());
806704c2 5022 }
0a61b0df 5023
5024 // Store the new addresses
090e5b40 5025 vector<CAddress> vAddrOk;
51ed9ec9
BD
5026 int64_t nNow = GetAdjustedTime();
5027 int64_t nSince = nNow - 10 * 60;
223b6f1b 5028 BOOST_FOREACH(CAddress& addr, vAddr)
0a61b0df 5029 {
b31499ec
GA
5030 boost::this_thread::interruption_point();
5031
c891967b 5032 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
5033 addr.nTime = nNow - 5 * 24 * 60 * 60;
0a61b0df 5034 pfrom->AddAddressKnown(addr);
090e5b40 5035 bool fReachable = IsReachable(addr);
c891967b 5036 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
0a61b0df 5037 {
5038 // Relay to a limited number of other nodes
0a61b0df 5039 {
f8dcd5ca 5040 LOCK(cs_vNodes);
5cbf7532 5041 // Use deterministic randomness to send to the same nodes for 24 hours
d81cff32 5042 // at a time so the addrKnowns of the chosen nodes prevent repeats
0a61b0df 5043 static uint256 hashSalt;
4f152496 5044 if (hashSalt.IsNull())
f718aedd 5045 hashSalt = GetRandHash();
51ed9ec9 5046 uint64_t hashAddr = addr.GetHash();
734f85c4 5047 uint256 hashRand = ArithToUint256(UintToArith256(hashSalt) ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60)));
5cbf7532 5048 hashRand = Hash(BEGIN(hashRand), END(hashRand));
0a61b0df 5049 multimap<uint256, CNode*> mapMix;
223b6f1b 5050 BOOST_FOREACH(CNode* pnode, vNodes)
5cbf7532 5051 {
15a99376
SB
5052 if (pnode->nVersion < CADDR_TIME_VERSION)
5053 continue;
5cbf7532 5054 unsigned int nPointer;
5055 memcpy(&nPointer, &pnode, sizeof(nPointer));
734f85c4 5056 uint256 hashKey = ArithToUint256(UintToArith256(hashRand) ^ nPointer);
5cbf7532 5057 hashKey = Hash(BEGIN(hashKey), END(hashKey));
5058 mapMix.insert(make_pair(hashKey, pnode));
5059 }
090e5b40 5060 int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
0a61b0df 5061 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
5062 ((*mi).second)->PushAddress(addr);
5063 }
5064 }
090e5b40
PW
5065 // Do not store addresses outside our network
5066 if (fReachable)
5067 vAddrOk.push_back(addr);
0a61b0df 5068 }
090e5b40 5069 addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
0a61b0df 5070 if (vAddr.size() < 1000)
5071 pfrom->fGetAddr = false;
478b01d9
PW
5072 if (pfrom->fOneShot)
5073 pfrom->fDisconnect = true;
0a61b0df 5074 }
5075
5076
5077 else if (strCommand == "inv")
5078 {
5079 vector<CInv> vInv;
5080 vRecv >> vInv;
05a85b2b 5081 if (vInv.size() > MAX_INV_SZ)
806704c2 5082 {
b2864d2f 5083 Misbehaving(pfrom->GetId(), 20);
783b182c 5084 return error("message inv size() = %u", vInv.size());
806704c2 5085 }
0a61b0df 5086
7d38af3c
PW
5087 LOCK(cs_main);
5088
341735eb
PW
5089 std::vector<CInv> vToFetch;
5090
c376ac35 5091 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
0a61b0df 5092 {
0aa89c08
PW
5093 const CInv &inv = vInv[nInv];
5094
b31499ec 5095 boost::this_thread::interruption_point();
0a61b0df 5096 pfrom->AddInventoryKnown(inv);
5097
ae8bfd12 5098 bool fAlreadyHave = AlreadyHave(inv);
2e36866f 5099 LogPrint("net", "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom->id);
0a61b0df 5100
341735eb
PW
5101 if (!fAlreadyHave && !fImporting && !fReindex && inv.type != MSG_BLOCK)
5102 pfrom->AskFor(inv);
0a61b0df 5103
341735eb 5104 if (inv.type == MSG_BLOCK) {
aa815647 5105 UpdateBlockAvailability(pfrom->GetId(), inv.hash);
341735eb 5106 if (!fAlreadyHave && !fImporting && !fReindex && !mapBlocksInFlight.count(inv.hash)) {
7e6d23b1 5107 // First request the headers preceding the announced block. In the normal fully-synced
341735eb
PW
5108 // case where a new block is announced that succeeds the current tip (no reorganization),
5109 // there are no such headers.
5110 // Secondly, and only when we are close to being synced, we request the announced block directly,
5111 // to avoid an extra round-trip. Note that we must *first* ask for the headers, so by the
5112 // time the block arrives, the header chain leading up to it is already validated. Not
5113 // doing this will result in the received block being rejected as an orphan in case it is
5114 // not a direct successor.
5115 pfrom->PushMessage("getheaders", chainActive.GetLocator(pindexBestHeader), inv.hash);
c9077043 5116 CNodeState *nodestate = State(pfrom->GetId());
e8e8904d 5117 if (chainActive.Tip()->GetBlockTime() > GetAdjustedTime() - chainparams.GetConsensus().nPowTargetSpacing * 20 &&
c9077043 5118 nodestate->nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
341735eb
PW
5119 vToFetch.push_back(inv);
5120 // Mark block as in flight already, even though the actual "getdata" message only goes out
5121 // later (within the same cs_main lock, though).
82737933 5122 MarkBlockAsInFlight(pfrom->GetId(), inv.hash, chainparams.GetConsensus());
341735eb 5123 }
4c933229 5124 LogPrint("net", "getheaders (%d) %s to peer=%d\n", pindexBestHeader->nHeight, inv.hash.ToString(), pfrom->id);
341735eb
PW
5125 }
5126 }
aa815647 5127
0a61b0df 5128 // Track requests for our stuff
26c16d9d 5129 GetMainSignals().Inventory(inv.hash);
540ac451
JG
5130
5131 if (pfrom->nSendSize > (SendBufferSize() * 2)) {
5132 Misbehaving(pfrom->GetId(), 50);
5133 return error("send buffer size() = %u", pfrom->nSendSize);
5134 }
0a61b0df 5135 }
341735eb
PW
5136
5137 if (!vToFetch.empty())
5138 pfrom->PushMessage("getdata", vToFetch);
0a61b0df 5139 }
5140
5141
5142 else if (strCommand == "getdata")
5143 {
5144 vector<CInv> vInv;
5145 vRecv >> vInv;
05a85b2b 5146 if (vInv.size() > MAX_INV_SZ)
806704c2 5147 {
b2864d2f 5148 Misbehaving(pfrom->GetId(), 20);
783b182c 5149 return error("message getdata size() = %u", vInv.size());
806704c2 5150 }
0a61b0df 5151
3b570559 5152 if (fDebug || (vInv.size() != 1))
2e36866f 5153 LogPrint("net", "received getdata (%u invsz) peer=%d\n", vInv.size(), pfrom->id);
983e4bde 5154
3b570559 5155 if ((fDebug && vInv.size() > 0) || (vInv.size() == 1))
2e36866f 5156 LogPrint("net", "received getdata for: %s peer=%d\n", vInv[0].ToString(), pfrom->id);
0a61b0df 5157
c7f039b6
PW
5158 pfrom->vRecvGetData.insert(pfrom->vRecvGetData.end(), vInv.begin(), vInv.end());
5159 ProcessGetData(pfrom);
0a61b0df 5160 }
5161
5162
5163 else if (strCommand == "getblocks")
5164 {
5165 CBlockLocator locator;
5166 uint256 hashStop;
5167 vRecv >> locator >> hashStop;
5168
7d38af3c
PW
5169 LOCK(cs_main);
5170
f03304a9 5171 // Find the last block the caller has in the main chain
6db83db3 5172 CBlockIndex* pindex = FindForkInGlobalIndex(chainActive, locator);
0a61b0df 5173
5174 // Send the rest of the chain
5175 if (pindex)
4c6d41b8 5176 pindex = chainActive.Next(pindex);
9d6cd04b 5177 int nLimit = 500;
4f152496 5178 LogPrint("net", "getblocks %d to %s limit %d from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), nLimit, pfrom->id);
4c6d41b8 5179 for (; pindex; pindex = chainActive.Next(pindex))
0a61b0df 5180 {
5181 if (pindex->GetBlockHash() == hashStop)
5182 {
7d9d134b 5183 LogPrint("net", " getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
0a61b0df 5184 break;
5185 }
5186 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
9d6cd04b 5187 if (--nLimit <= 0)
0a61b0df 5188 {
b05a89b2
LD
5189 // When this block is requested, we'll send an inv that'll
5190 // trigger the peer to getblocks the next batch of inventory.
7d9d134b 5191 LogPrint("net", " getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
0a61b0df 5192 pfrom->hashContinue = pindex->GetBlockHash();
5193 break;
5194 }
5195 }
5196 }
5197
5198
f03304a9 5199 else if (strCommand == "getheaders")
5200 {
5201 CBlockLocator locator;
5202 uint256 hashStop;
5203 vRecv >> locator >> hashStop;
5204
7d38af3c
PW
5205 LOCK(cs_main);
5206
b4bbad18
SD
5207 if (IsInitialBlockDownload())
5208 return true;
5209
f03304a9 5210 CBlockIndex* pindex = NULL;
5211 if (locator.IsNull())
5212 {
5213 // If locator is null, return the hashStop block
145d5be8 5214 BlockMap::iterator mi = mapBlockIndex.find(hashStop);
f03304a9 5215 if (mi == mapBlockIndex.end())
5216 return true;
5217 pindex = (*mi).second;
5218 }
5219 else
5220 {
5221 // Find the last block the caller has in the main chain
6db83db3 5222 pindex = FindForkInGlobalIndex(chainActive, locator);
f03304a9 5223 if (pindex)
4c6d41b8 5224 pindex = chainActive.Next(pindex);
f03304a9 5225 }
5226
e754cf41 5227 // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
f03304a9 5228 vector<CBlock> vHeaders;
341735eb 5229 int nLimit = MAX_HEADERS_RESULTS;
4c933229 5230 LogPrint("net", "getheaders %d to %s from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString(), pfrom->id);
4c6d41b8 5231 for (; pindex; pindex = chainActive.Next(pindex))
f03304a9 5232 {
5233 vHeaders.push_back(pindex->GetBlockHeader());
5234 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
5235 break;
5236 }
5237 pfrom->PushMessage("headers", vHeaders);
5238 }
5239
5240
0a61b0df 5241 else if (strCommand == "tx")
5242 {
5243 vector<uint256> vWorkQueue;
7a15109c 5244 vector<uint256> vEraseQueue;
0a61b0df 5245 CTransaction tx;
5246 vRecv >> tx;
5247
805344dc 5248 CInv inv(MSG_TX, tx.GetHash());
0a61b0df 5249 pfrom->AddInventoryKnown(inv);
5250
7d38af3c
PW
5251 LOCK(cs_main);
5252
0a61b0df 5253 bool fMissingInputs = false;
ef3988ca 5254 CValidationState state;
604ee2aa 5255
e2190f80 5256 pfrom->setAskFor.erase(inv.hash);
604ee2aa
B
5257 mapAlreadyAskedFor.erase(inv);
5258
60aed954 5259 if (!AlreadyHave(inv) && AcceptToMemoryPool(mempool, state, tx, true, &fMissingInputs))
0a61b0df 5260 {
a0fa20a1 5261 mempool.check(pcoinsTip);
d38da59b 5262 RelayTransaction(tx);
0a61b0df 5263 vWorkQueue.push_back(inv.hash);
5264
5262fde0 5265 LogPrint("mempool", "AcceptToMemoryPool: peer=%d %s: accepted %s (poolsz %u)\n",
2e36866f 5266 pfrom->id, pfrom->cleanSubVer,
805344dc 5267 tx.GetHash().ToString(),
ba6a4ea3
MH
5268 mempool.mapTx.size());
5269
0a61b0df 5270 // Recursively process any orphan transactions that depended on this one
c74332c6 5271 set<NodeId> setMisbehaving;
c376ac35 5272 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
0a61b0df 5273 {
89d91f6a
WL
5274 map<uint256, set<uint256> >::iterator itByPrev = mapOrphanTransactionsByPrev.find(vWorkQueue[i]);
5275 if (itByPrev == mapOrphanTransactionsByPrev.end())
5276 continue;
5277 for (set<uint256>::iterator mi = itByPrev->second.begin();
5278 mi != itByPrev->second.end();
0a61b0df 5279 ++mi)
5280 {
159bc481 5281 const uint256& orphanHash = *mi;
c74332c6
GA
5282 const CTransaction& orphanTx = mapOrphanTransactions[orphanHash].tx;
5283 NodeId fromPeer = mapOrphanTransactions[orphanHash].fromPeer;
7a15109c 5284 bool fMissingInputs2 = false;
159bc481
GA
5285 // Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan
5286 // resolution (that is, feeding people an invalid transaction based on LegitTxX in order to get
5287 // anyone relaying LegitTxX banned)
8c4e4313 5288 CValidationState stateDummy;
0a61b0df 5289
c74332c6
GA
5290
5291 if (setMisbehaving.count(fromPeer))
5292 continue;
319b1160 5293 if (AcceptToMemoryPool(mempool, stateDummy, orphanTx, true, &fMissingInputs2))
0a61b0df 5294 {
7d9d134b 5295 LogPrint("mempool", " accepted orphan tx %s\n", orphanHash.ToString());
d38da59b 5296 RelayTransaction(orphanTx);
159bc481 5297 vWorkQueue.push_back(orphanHash);
37b4e425 5298 vEraseQueue.push_back(orphanHash);
7a15109c
GA
5299 }
5300 else if (!fMissingInputs2)
5301 {
c74332c6
GA
5302 int nDos = 0;
5303 if (stateDummy.IsInvalid(nDos) && nDos > 0)
5304 {
5305 // Punish peer that gave us an invalid orphan tx
5306 Misbehaving(fromPeer, nDos);
5307 setMisbehaving.insert(fromPeer);
5308 LogPrint("mempool", " invalid orphan tx %s\n", orphanHash.ToString());
5309 }
37b4e425
AM
5310 // Has inputs but not accepted to mempool
5311 // Probably non-standard or insufficient fee/priority
7d9d134b 5312 LogPrint("mempool", " removed orphan tx %s\n", orphanHash.ToString());
37b4e425 5313 vEraseQueue.push_back(orphanHash);
5094a81d 5314 assert(recentRejects);
ec9b6c33 5315 recentRejects->insert(orphanHash);
0a61b0df 5316 }
a0fa20a1 5317 mempool.check(pcoinsTip);
0a61b0df 5318 }
5319 }
5320
7a15109c 5321 BOOST_FOREACH(uint256 hash, vEraseQueue)
0a61b0df 5322 EraseOrphanTx(hash);
5323 }
b7e4abd6 5324 // TODO: currently, prohibit joinsplits from entering mapOrphans
8675d94b 5325 else if (fMissingInputs && tx.vjoinsplit.size() == 0)
0a61b0df 5326 {
c74332c6 5327 AddOrphanTx(tx, pfrom->GetId());
142e6041
GA
5328
5329 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
aa3c697e
GA
5330 unsigned int nMaxOrphanTx = (unsigned int)std::max((int64_t)0, GetArg("-maxorphantx", DEFAULT_MAX_ORPHAN_TRANSACTIONS));
5331 unsigned int nEvicted = LimitOrphanTxSize(nMaxOrphanTx);
142e6041 5332 if (nEvicted > 0)
881a85a2 5333 LogPrint("mempool", "mapOrphan overflow, removed %u tx\n", nEvicted);
ec9b6c33 5334 } else {
36f14bf2 5335 assert(recentRejects);
805344dc 5336 recentRejects->insert(tx.GetHash());
36f14bf2 5337
ec9b6c33
PT
5338 if (pfrom->fWhitelisted) {
5339 // Always relay transactions received from whitelisted peers, even
60aed954
PW
5340 // if they were already in the mempool or rejected from it due
5341 // to policy, allowing the node to function as a gateway for
5342 // nodes hidden behind it.
ec9b6c33 5343 //
60aed954
PW
5344 // Never relay transactions that we would assign a non-zero DoS
5345 // score for, as we expect peers to do the same with us in that
5346 // case.
5347 int nDoS = 0;
5348 if (!state.IsInvalid(nDoS) || nDoS == 0) {
5349 LogPrintf("Force relaying tx %s from whitelisted peer=%d\n", tx.GetHash().ToString(), pfrom->id);
5350 RelayTransaction(tx);
5351 } else {
e63d14fd 5352 LogPrintf("Not relaying invalid transaction %s from whitelisted peer=%d (%s (code %d))\n",
de3dd8a0 5353 tx.GetHash().ToString(), pfrom->id, state.GetRejectReason(), state.GetRejectCode());
60aed954 5354 }
ec9b6c33 5355 }
0a61b0df 5356 }
fbed9c9d 5357 int nDoS = 0;
5ea66c54 5358 if (state.IsInvalid(nDoS))
2b45345a 5359 {
805344dc 5360 LogPrint("mempool", "%s from peer=%d %s was not accepted into the memory pool: %s\n", tx.GetHash().ToString(),
2e36866f 5361 pfrom->id, pfrom->cleanSubVer,
7d9d134b 5362 state.GetRejectReason());
358ce266 5363 pfrom->PushMessage("reject", strCommand, state.GetRejectCode(),
307f7d48 5364 state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash);
5ea66c54 5365 if (nDoS > 0)
b2864d2f 5366 Misbehaving(pfrom->GetId(), nDoS);
358ce266 5367 }
0a61b0df 5368 }
5369
5370
341735eb
PW
5371 else if (strCommand == "headers" && !fImporting && !fReindex) // Ignore headers received while importing
5372 {
5373 std::vector<CBlockHeader> headers;
5374
5375 // Bypass the normal CBlock deserialization, as we don't want to risk deserializing 2000 full blocks.
5376 unsigned int nCount = ReadCompactSize(vRecv);
5377 if (nCount > MAX_HEADERS_RESULTS) {
5378 Misbehaving(pfrom->GetId(), 20);
5379 return error("headers message size = %u", nCount);
5380 }
5381 headers.resize(nCount);
5382 for (unsigned int n = 0; n < nCount; n++) {
5383 vRecv >> headers[n];
5384 ReadCompactSize(vRecv); // ignore tx count; assume it is 0.
5385 }
5386
5387 LOCK(cs_main);
5388
5389 if (nCount == 0) {
5390 // Nothing interesting. Stop asking this peers for more headers.
5391 return true;
5392 }
5393
5394 CBlockIndex *pindexLast = NULL;
5395 BOOST_FOREACH(const CBlockHeader& header, headers) {
5396 CValidationState state;
5397 if (pindexLast != NULL && header.hashPrevBlock != pindexLast->GetBlockHash()) {
5398 Misbehaving(pfrom->GetId(), 20);
5399 return error("non-continuous headers sequence");
5400 }
5401 if (!AcceptBlockHeader(header, state, &pindexLast)) {
5402 int nDoS;
5403 if (state.IsInvalid(nDoS)) {
5404 if (nDoS > 0)
5405 Misbehaving(pfrom->GetId(), nDoS);
5406 return error("invalid header received");
5407 }
5408 }
5409 }
5410
5411 if (pindexLast)
5412 UpdateBlockAvailability(pfrom->GetId(), pindexLast->GetBlockHash());
5413
5414 if (nCount == MAX_HEADERS_RESULTS && pindexLast) {
5415 // Headers message had its maximum size; the peer may have more headers.
5416 // TODO: optimize: if pindexLast is an ancestor of chainActive.Tip or pindexBestHeader, continue
5417 // from there instead.
4c933229 5418 LogPrint("net", "more getheaders (%d) to end to peer=%d (startheight:%d)\n", pindexLast->nHeight, pfrom->id, pfrom->nStartingHeight);
4f152496 5419 pfrom->PushMessage("getheaders", chainActive.GetLocator(pindexLast), uint256());
341735eb 5420 }
3fcfbc8a
PW
5421
5422 CheckBlockIndex();
341735eb
PW
5423 }
5424
7fea4846 5425 else if (strCommand == "block" && !fImporting && !fReindex) // Ignore blocks received while importing
0a61b0df 5426 {
f03304a9 5427 CBlock block;
5428 vRecv >> block;
0a61b0df 5429
f03304a9 5430 CInv inv(MSG_BLOCK, block.GetHash());
341735eb 5431 LogPrint("net", "received block %s peer=%d\n", inv.hash.ToString(), pfrom->id);
0a61b0df 5432
341735eb 5433 pfrom->AddInventoryKnown(inv);
7d38af3c 5434
ef3988ca 5435 CValidationState state;
93b606ae
SD
5436 // Process all blocks from whitelisted peers, even if not requested,
5437 // unless we're still syncing with the network.
5438 // Such an unrequested block may still be processed, subject to the
5439 // conditions in AcceptBlock().
5440 bool forceProcessing = pfrom->fWhitelisted && !IsInitialBlockDownload();
5441 ProcessNewBlock(state, pfrom, &block, forceProcessing, NULL);
40f5cb87
PW
5442 int nDoS;
5443 if (state.IsInvalid(nDoS)) {
5444 pfrom->PushMessage("reject", strCommand, state.GetRejectCode(),
307f7d48 5445 state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash);
40f5cb87
PW
5446 if (nDoS > 0) {
5447 LOCK(cs_main);
5448 Misbehaving(pfrom->GetId(), nDoS);
5449 }
5450 }
5451
0a61b0df 5452 }
5453
5454
dca799e1
IP
5455 // This asymmetric behavior for inbound and outbound connections was introduced
5456 // to prevent a fingerprinting attack: an attacker can send specific fake addresses
b05a89b2
LD
5457 // to users' AddrMan and later request them by sending getaddr messages.
5458 // Making nodes which are behind NAT and can only make outgoing connections ignore
5459 // the getaddr message mitigates the attack.
dca799e1 5460 else if ((strCommand == "getaddr") && (pfrom->fInbound))
0a61b0df 5461 {
a514cb29
GM
5462 // Only send one GetAddr response per connection to reduce resource waste
5463 // and discourage addr stamping of INV announcements.
5464 if (pfrom->fSentAddr) {
5465 LogPrint("net", "Ignoring repeated \"getaddr\". peer=%d\n", pfrom->id);
5466 return true;
5467 }
5468 pfrom->fSentAddr = true;
5469
0a61b0df 5470 pfrom->vAddrToSend.clear();
5fee401f
PW
5471 vector<CAddress> vAddr = addrman.GetAddr();
5472 BOOST_FOREACH(const CAddress &addr, vAddr)
5473 pfrom->PushAddress(addr);
0a61b0df 5474 }
5475
5476
05a85b2b
JG
5477 else if (strCommand == "mempool")
5478 {
319b1160 5479 LOCK2(cs_main, pfrom->cs_filter);
7d38af3c 5480
05a85b2b
JG
5481 std::vector<uint256> vtxid;
5482 mempool.queryHashes(vtxid);
5483 vector<CInv> vInv;
c51694eb
MC
5484 BOOST_FOREACH(uint256& hash, vtxid) {
5485 CInv inv(MSG_TX, hash);
1c82adeb
MC
5486 if (pfrom->pfilter) {
5487 CTransaction tx;
5488 bool fInMemPool = mempool.lookup(hash, tx);
5489 if (!fInMemPool) continue; // another thread removed since queryHashes, maybe...
5490 if (!pfrom->pfilter->IsRelevantAndUpdate(tx)) continue;
5491 }
5492 vInv.push_back(inv);
1f3d3647
GA
5493 if (vInv.size() == MAX_INV_SZ) {
5494 pfrom->PushMessage("inv", vInv);
5495 vInv.clear();
5496 }
05a85b2b
JG
5497 }
5498 if (vInv.size() > 0)
5499 pfrom->PushMessage("inv", vInv);
5500 }
5501
5502
0a61b0df 5503 else if (strCommand == "ping")
5504 {
15a99376
SB
5505 if (pfrom->nVersion > BIP0031_VERSION)
5506 {
5507 uint64_t nonce = 0;
5508 vRecv >> nonce;
5509 // Echo the message back with the nonce. This allows for two useful features:
5510 //
5511 // 1) A remote node can quickly check if the connection is operational
5512 // 2) Remote nodes can measure the latency of the network thread. If this node
5513 // is overloaded it won't respond to pings quickly and the remote node can
5514 // avoid sending us more work, like chain download requests.
5515 //
5516 // The nonce stops the remote getting confused between different pings: without
5517 // it, if the remote node sends a ping once per second and this node takes 5
5518 // seconds to respond to each, the 5th ping the remote sends would appear to
5519 // return very quickly.
5520 pfrom->PushMessage("pong", nonce);
5521 }
0a61b0df 5522 }
5523
5524
971bb3e9
JL
5525 else if (strCommand == "pong")
5526 {
9f4da19b 5527 int64_t pingUsecEnd = nTimeReceived;
51ed9ec9 5528 uint64_t nonce = 0;
971bb3e9
JL
5529 size_t nAvail = vRecv.in_avail();
5530 bool bPingFinished = false;
5531 std::string sProblem;
cd696e64 5532
971bb3e9
JL
5533 if (nAvail >= sizeof(nonce)) {
5534 vRecv >> nonce;
cd696e64 5535
971bb3e9
JL
5536 // Only process pong message if there is an outstanding ping (old ping without nonce should never pong)
5537 if (pfrom->nPingNonceSent != 0) {
5538 if (nonce == pfrom->nPingNonceSent) {
5539 // Matching pong received, this ping is no longer outstanding
5540 bPingFinished = true;
51ed9ec9 5541 int64_t pingUsecTime = pingUsecEnd - pfrom->nPingUsecStart;
971bb3e9
JL
5542 if (pingUsecTime > 0) {
5543 // Successful ping time measurement, replace previous
5544 pfrom->nPingUsecTime = pingUsecTime;
e279e5f9 5545 pfrom->nMinPingUsecTime = std::min(pfrom->nMinPingUsecTime, pingUsecTime);
971bb3e9
JL
5546 } else {
5547 // This should never happen
5548 sProblem = "Timing mishap";
5549 }
5550 } else {
5551 // Nonce mismatches are normal when pings are overlapping
5552 sProblem = "Nonce mismatch";
5553 if (nonce == 0) {
7e6d23b1 5554 // This is most likely a bug in another implementation somewhere; cancel this ping
971bb3e9
JL
5555 bPingFinished = true;
5556 sProblem = "Nonce zero";
5557 }
5558 }
5559 } else {
5560 sProblem = "Unsolicited pong without ping";
5561 }
5562 } else {
7e6d23b1 5563 // This is most likely a bug in another implementation somewhere; cancel this ping
971bb3e9
JL
5564 bPingFinished = true;
5565 sProblem = "Short payload";
5566 }
cd696e64 5567
971bb3e9 5568 if (!(sProblem.empty())) {
2e36866f
B
5569 LogPrint("net", "pong peer=%d %s: %s, %x expected, %x received, %u bytes\n",
5570 pfrom->id,
7d9d134b
WL
5571 pfrom->cleanSubVer,
5572 sProblem,
7dea6345
PK
5573 pfrom->nPingNonceSent,
5574 nonce,
5575 nAvail);
971bb3e9
JL
5576 }
5577 if (bPingFinished) {
5578 pfrom->nPingNonceSent = 0;
5579 }
5580 }
cd696e64
PK
5581
5582
4d9c7fe6 5583 else if (fAlerts && strCommand == "alert")
0a61b0df 5584 {
5585 CAlert alert;
5586 vRecv >> alert;
5587
d5a52d9b
GA
5588 uint256 alertHash = alert.GetHash();
5589 if (pfrom->setKnown.count(alertHash) == 0)
0a61b0df 5590 {
f14e687f 5591 if (alert.ProcessAlert(Params().AlertKey()))
f8dcd5ca 5592 {
d5a52d9b
GA
5593 // Relay
5594 pfrom->setKnown.insert(alertHash);
5595 {
5596 LOCK(cs_vNodes);
5597 BOOST_FOREACH(CNode* pnode, vNodes)
5598 alert.RelayTo(pnode);
5599 }
5600 }
5601 else {
5602 // Small DoS penalty so peers that send us lots of
5603 // duplicate/expired/invalid-signature/whatever alerts
5604 // eventually get banned.
5605 // This isn't a Misbehaving(100) (immediate ban) because the
5606 // peer might be an older or different implementation with
5607 // a different signature key, etc.
b2864d2f 5608 Misbehaving(pfrom->GetId(), 10);
f8dcd5ca 5609 }
0a61b0df 5610 }
5611 }
5612
5613
2b7fcab8
JG
5614 else if (!(nLocalServices & NODE_BLOOM) &&
5615 (strCommand == "filterload" ||
4f31d823 5616 strCommand == "filteradd"))
2b7fcab8
JG
5617 {
5618 if (pfrom->nVersion >= NO_BLOOM_VERSION) {
5619 Misbehaving(pfrom->GetId(), 100);
5620 return false;
5621 } else if (GetBoolArg("-enforcenodebloom", false)) {
5622 pfrom->fDisconnect = true;
5623 return false;
5624 }
5625 }
5626
5627
422d1225
MC
5628 else if (strCommand == "filterload")
5629 {
5630 CBloomFilter filter;
5631 vRecv >> filter;
5632
5633 if (!filter.IsWithinSizeConstraints())
5634 // There is no excuse for sending a too-large filter
b2864d2f 5635 Misbehaving(pfrom->GetId(), 100);
422d1225
MC
5636 else
5637 {
5638 LOCK(pfrom->cs_filter);
5639 delete pfrom->pfilter;
5640 pfrom->pfilter = new CBloomFilter(filter);
a7f533a9 5641 pfrom->pfilter->UpdateEmptyFull();
422d1225 5642 }
4c8fc1a5 5643 pfrom->fRelayTxes = true;
422d1225
MC
5644 }
5645
5646
5647 else if (strCommand == "filteradd")
5648 {
5649 vector<unsigned char> vData;
5650 vRecv >> vData;
5651
5652 // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
5653 // and thus, the maximum size any matched object can have) in a filteradd message
192cc910 5654 if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE)
422d1225 5655 {
b2864d2f 5656 Misbehaving(pfrom->GetId(), 100);
422d1225
MC
5657 } else {
5658 LOCK(pfrom->cs_filter);
5659 if (pfrom->pfilter)
5660 pfrom->pfilter->insert(vData);
5661 else
b2864d2f 5662 Misbehaving(pfrom->GetId(), 100);
422d1225
MC
5663 }
5664 }
5665
5666
5667 else if (strCommand == "filterclear")
5668 {
5669 LOCK(pfrom->cs_filter);
4f31d823
B
5670 if (nLocalServices & NODE_BLOOM) {
5671 delete pfrom->pfilter;
5672 pfrom->pfilter = new CBloomFilter();
5673 }
4c8fc1a5 5674 pfrom->fRelayTxes = true;
422d1225
MC
5675 }
5676
5677
358ce266
GA
5678 else if (strCommand == "reject")
5679 {
efad808a
PW
5680 if (fDebug) {
5681 try {
5682 string strMsg; unsigned char ccode; string strReason;
307f7d48 5683 vRecv >> LIMITED_STRING(strMsg, CMessageHeader::COMMAND_SIZE) >> ccode >> LIMITED_STRING(strReason, MAX_REJECT_MESSAGE_LENGTH);
358ce266 5684
efad808a
PW
5685 ostringstream ss;
5686 ss << strMsg << " code " << itostr(ccode) << ": " << strReason;
358ce266 5687
efad808a
PW
5688 if (strMsg == "block" || strMsg == "tx")
5689 {
5690 uint256 hash;
5691 vRecv >> hash;
5692 ss << ": hash " << hash.ToString();
5693 }
5694 LogPrint("net", "Reject %s\n", SanitizeString(ss.str()));
27df4123 5695 } catch (const std::ios_base::failure&) {
efad808a
PW
5696 // Avoid feedback loops by preventing reject messages from triggering a new reject message.
5697 LogPrint("net", "Unparseable reject message received\n");
358ce266 5698 }
358ce266
GA
5699 }
5700 }
5701
432bc22a 5702 else if (strCommand == "notfound") {
e496b2e3
WL
5703 // We do not care about the NOTFOUND message, but logging an Unknown Command
5704 // message would be undesirable as we transmit it ourselves.
5705 }
5706
5707 else {
0a61b0df 5708 // Ignore unknown commands for extensibility
6ecf3edf 5709 LogPrint("net", "Unknown command \"%s\" from peer=%d\n", SanitizeString(strCommand), pfrom->id);
0a61b0df 5710 }
5711
5712
0a61b0df 5713
5714 return true;
5715}
5716
607dbfde 5717// requires LOCK(cs_vRecvMsg)
e89b9f6a
PW
5718bool ProcessMessages(CNode* pfrom)
5719{
e89b9f6a 5720 //if (fDebug)
30c1db1c 5721 // LogPrintf("%s(%u messages)\n", __func__, pfrom->vRecvMsg.size());
0a61b0df 5722
e89b9f6a
PW
5723 //
5724 // Message format
5725 // (4) message start
5726 // (12) command
5727 // (4) size
5728 // (4) checksum
5729 // (x) data
5730 //
967f2459 5731 bool fOk = true;
0a61b0df 5732
c7f039b6
PW
5733 if (!pfrom->vRecvGetData.empty())
5734 ProcessGetData(pfrom);
cd696e64 5735
75ef87dd
PS
5736 // this maintains the order of responses
5737 if (!pfrom->vRecvGetData.empty()) return fOk;
cd696e64 5738
967f2459 5739 std::deque<CNetMessage>::iterator it = pfrom->vRecvMsg.begin();
41b052ad 5740 while (!pfrom->fDisconnect && it != pfrom->vRecvMsg.end()) {
9d6cd04b 5741 // Don't bother if send buffer is too full to respond anyway
41b052ad 5742 if (pfrom->nSendSize >= SendBufferSize())
9d6cd04b
MC
5743 break;
5744
967f2459
PW
5745 // get next message
5746 CNetMessage& msg = *it;
607dbfde
JG
5747
5748 //if (fDebug)
30c1db1c 5749 // LogPrintf("%s(message %u msgsz, %u bytes, complete:%s)\n", __func__,
607dbfde
JG
5750 // msg.hdr.nMessageSize, msg.vRecv.size(),
5751 // msg.complete() ? "Y" : "N");
5752
967f2459 5753 // end, if an incomplete message is found
607dbfde 5754 if (!msg.complete())
e89b9f6a 5755 break;
607dbfde 5756
967f2459
PW
5757 // at this point, any failure means we can delete the current message
5758 it++;
5759
607dbfde 5760 // Scan for message start
0e4b3175 5761 if (memcmp(msg.hdr.pchMessageStart, Params().MessageStart(), MESSAGE_START_SIZE) != 0) {
28d4cff0 5762 LogPrintf("PROCESSMESSAGE: INVALID MESSAGESTART %s peer=%d\n", SanitizeString(msg.hdr.GetCommand()), pfrom->id);
967f2459
PW
5763 fOk = false;
5764 break;
e89b9f6a 5765 }
0a61b0df 5766
e89b9f6a 5767 // Read header
607dbfde 5768 CMessageHeader& hdr = msg.hdr;
eec37136 5769 if (!hdr.IsValid(Params().MessageStart()))
e89b9f6a 5770 {
28d4cff0 5771 LogPrintf("PROCESSMESSAGE: ERRORS IN HEADER %s peer=%d\n", SanitizeString(hdr.GetCommand()), pfrom->id);
e89b9f6a
PW
5772 continue;
5773 }
5774 string strCommand = hdr.GetCommand();
5775
5776 // Message size
5777 unsigned int nMessageSize = hdr.nMessageSize;
e89b9f6a
PW
5778
5779 // Checksum
607dbfde 5780 CDataStream& vRecv = msg.vRecv;
18c0fa97 5781 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
556814ec 5782 unsigned int nChecksum = ReadLE32((unsigned char*)&hash);
18c0fa97 5783 if (nChecksum != hdr.nChecksum)
e89b9f6a 5784 {
30c1db1c 5785 LogPrintf("%s(%s, %u bytes): CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n", __func__,
28d4cff0 5786 SanitizeString(strCommand), nMessageSize, nChecksum, hdr.nChecksum);
18c0fa97 5787 continue;
e89b9f6a
PW
5788 }
5789
e89b9f6a
PW
5790 // Process message
5791 bool fRet = false;
5792 try
5793 {
9f4da19b 5794 fRet = ProcessMessage(pfrom, strCommand, vRecv, msg.nTime);
b31499ec 5795 boost::this_thread::interruption_point();
e89b9f6a 5796 }
27df4123 5797 catch (const std::ios_base::failure& e)
e89b9f6a 5798 {
358ce266 5799 pfrom->PushMessage("reject", strCommand, REJECT_MALFORMED, string("error parsing message"));
e89b9f6a
PW
5800 if (strstr(e.what(), "end of data"))
5801 {
814efd6f 5802 // Allow exceptions from under-length message on vRecv
30c1db1c 5803 LogPrintf("%s(%s, %u bytes): Exception '%s' caught, normally caused by a message being shorter than its stated length\n", __func__, SanitizeString(strCommand), nMessageSize, e.what());
e89b9f6a
PW
5804 }
5805 else if (strstr(e.what(), "size too large"))
5806 {
814efd6f 5807 // Allow exceptions from over-long size
30c1db1c 5808 LogPrintf("%s(%s, %u bytes): Exception '%s' caught\n", __func__, SanitizeString(strCommand), nMessageSize, e.what());
e89b9f6a
PW
5809 }
5810 else
5811 {
ea591ead 5812 PrintExceptionContinue(&e, "ProcessMessages()");
e89b9f6a
PW
5813 }
5814 }
27df4123 5815 catch (const boost::thread_interrupted&) {
b31499ec
GA
5816 throw;
5817 }
27df4123 5818 catch (const std::exception& e) {
ea591ead 5819 PrintExceptionContinue(&e, "ProcessMessages()");
e89b9f6a 5820 } catch (...) {
ea591ead 5821 PrintExceptionContinue(NULL, "ProcessMessages()");
e89b9f6a
PW
5822 }
5823
5824 if (!fRet)
30c1db1c 5825 LogPrintf("%s(%s, %u bytes) FAILED peer=%d\n", __func__, SanitizeString(strCommand), nMessageSize, pfrom->id);
cd696e64 5826
75ef87dd 5827 break;
e89b9f6a
PW
5828 }
5829
41b052ad
PW
5830 // In case the connection got shut down, its receive buffer was wiped
5831 if (!pfrom->fDisconnect)
5832 pfrom->vRecvMsg.erase(pfrom->vRecvMsg.begin(), it);
5833
967f2459 5834 return fOk;
e89b9f6a 5835}
0a61b0df 5836
5837
0a61b0df 5838bool SendMessages(CNode* pto, bool fSendTrickle)
5839{
e8e8904d 5840 const Consensus::Params& consensusParams = Params().GetConsensus();
6055b910 5841 {
b05a89b2 5842 // Don't send anything until we get its version message
0a61b0df 5843 if (pto->nVersion == 0)
5844 return true;
5845
971bb3e9
JL
5846 //
5847 // Message: ping
5848 //
5849 bool pingSend = false;
5850 if (pto->fPingQueued) {
5851 // RPC ping request by user
5852 pingSend = true;
5853 }
f1920e86
PW
5854 if (pto->nPingNonceSent == 0 && pto->nPingUsecStart + PING_INTERVAL * 1000000 < GetTimeMicros()) {
5855 // Ping automatically sent as a latency probe & keepalive.
971bb3e9
JL
5856 pingSend = true;
5857 }
5858 if (pingSend) {
51ed9ec9 5859 uint64_t nonce = 0;
971bb3e9 5860 while (nonce == 0) {
001a53d7 5861 GetRandBytes((unsigned char*)&nonce, sizeof(nonce));
971bb3e9 5862 }
971bb3e9 5863 pto->fPingQueued = false;
f1920e86 5864 pto->nPingUsecStart = GetTimeMicros();
15a99376
SB
5865 if (pto->nVersion > BIP0031_VERSION) {
5866 pto->nPingNonceSent = nonce;
5867 pto->PushMessage("ping", nonce);
5868 } else {
5869 // Peer is too old to support ping command with nonce, pong will never arrive.
5870 pto->nPingNonceSent = 0;
5871 pto->PushMessage("ping");
5872 }
93e447b6 5873 }
0a61b0df 5874
55a1db4f
WL
5875 TRY_LOCK(cs_main, lockMain); // Acquire cs_main for IsInitialBlockDownload() and CNodeState()
5876 if (!lockMain)
5877 return true;
5878
0a61b0df 5879 // Address refresh broadcast
51ed9ec9 5880 static int64_t nLastRebroadcast;
5d1b8f17 5881 if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
0a61b0df 5882 {
845c86d1
GM
5883 LOCK(cs_vNodes);
5884 BOOST_FOREACH(CNode* pnode, vNodes)
0a61b0df 5885 {
d81cff32 5886 // Periodically clear addrKnown to allow refresh broadcasts
845c86d1 5887 if (nLastRebroadcast)
83671efe 5888 pnode->addrKnown.reset();
0a61b0df 5889
845c86d1
GM
5890 // Rebroadcast our address
5891 AdvertizeLocal(pnode);
0a61b0df 5892 }
845c86d1
GM
5893 if (!vNodes.empty())
5894 nLastRebroadcast = GetTime();
0a61b0df 5895 }
5896
0a61b0df 5897 //
5898 // Message: addr
5899 //
5900 if (fSendTrickle)
5901 {
5902 vector<CAddress> vAddr;
5903 vAddr.reserve(pto->vAddrToSend.size());
223b6f1b 5904 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
0a61b0df 5905 {
d81cff32 5906 if (!pto->addrKnown.contains(addr.GetKey()))
0a61b0df 5907 {
d81cff32 5908 pto->addrKnown.insert(addr.GetKey());
0a61b0df 5909 vAddr.push_back(addr);
5910 // receiver rejects addr messages larger than 1000
5911 if (vAddr.size() >= 1000)
5912 {
5913 pto->PushMessage("addr", vAddr);
5914 vAddr.clear();
5915 }
5916 }
5917 }
5918 pto->vAddrToSend.clear();
5919 if (!vAddr.empty())
5920 pto->PushMessage("addr", vAddr);
5921 }
5922
75f51f2a
PW
5923 CNodeState &state = *State(pto->GetId());
5924 if (state.fShouldBan) {
dc942e6f
PW
5925 if (pto->fWhitelisted)
5926 LogPrintf("Warning: not punishing whitelisted peer %s!\n", pto->addr.ToString());
b2864d2f
PW
5927 else {
5928 pto->fDisconnect = true;
dc942e6f
PW
5929 if (pto->addr.IsLocal())
5930 LogPrintf("Warning: not banning local peer %s!\n", pto->addr.ToString());
5931 else
c74332c6 5932 {
dc942e6f 5933 CNode::Ban(pto->addr);
c74332c6 5934 }
b2864d2f 5935 }
75f51f2a 5936 state.fShouldBan = false;
b2864d2f
PW
5937 }
5938
75f51f2a
PW
5939 BOOST_FOREACH(const CBlockReject& reject, state.rejects)
5940 pto->PushMessage("reject", (string)"block", reject.chRejectCode, reject.strRejectReason, reject.hashBlock);
5941 state.rejects.clear();
5942
6055b910 5943 // Start block sync
341735eb
PW
5944 if (pindexBestHeader == NULL)
5945 pindexBestHeader = chainActive.Tip();
b4ee0bdd 5946 bool fFetch = state.fPreferredDownload || (nPreferredDownload == 0 && !pto->fClient && !pto->fOneShot); // Download if this is a nice peer, or we have no nice peers and this one might do.
00dcaf4b 5947 if (!state.fSyncStarted && !pto->fClient && !fImporting && !fReindex) {
341735eb 5948 // Only actively request headers from a single peer, unless we're close to today.
00dcaf4b 5949 if ((nSyncStarted == 0 && fFetch) || pindexBestHeader->GetBlockTime() > GetAdjustedTime() - 24 * 60 * 60) {
341735eb
PW
5950 state.fSyncStarted = true;
5951 nSyncStarted++;
5952 CBlockIndex *pindexStart = pindexBestHeader->pprev ? pindexBestHeader->pprev : pindexBestHeader;
4c933229 5953 LogPrint("net", "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart->nHeight, pto->id, pto->nStartingHeight);
4f152496 5954 pto->PushMessage("getheaders", chainActive.GetLocator(pindexStart), uint256());
341735eb 5955 }
6055b910
PW
5956 }
5957
5958 // Resend wallet transactions that haven't gotten in a block yet
5959 // Except during reindex, importing and IBD, when old wallet
5960 // transactions become unconfirmed and spams other nodes.
5961 if (!fReindex && !fImporting && !IsInitialBlockDownload())
5962 {
0f5954c4 5963 GetMainSignals().Broadcast(nTimeBestReceived);
6055b910 5964 }
0a61b0df 5965
5966 //
5967 // Message: inventory
5968 //
5969 vector<CInv> vInv;
5970 vector<CInv> vInvWait;
0a61b0df 5971 {
f8dcd5ca 5972 LOCK(pto->cs_inventory);
0a61b0df 5973 vInv.reserve(pto->vInventoryToSend.size());
5974 vInvWait.reserve(pto->vInventoryToSend.size());
223b6f1b 5975 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
0a61b0df 5976 {
5977 if (pto->setInventoryKnown.count(inv))
5978 continue;
5979
5980 // trickle out tx inv to protect privacy
5981 if (inv.type == MSG_TX && !fSendTrickle)
5982 {
5983 // 1/4 of tx invs blast to all immediately
5984 static uint256 hashSalt;
4f152496 5985 if (hashSalt.IsNull())
f718aedd 5986 hashSalt = GetRandHash();
734f85c4 5987 uint256 hashRand = ArithToUint256(UintToArith256(inv.hash) ^ UintToArith256(hashSalt));
0a61b0df 5988 hashRand = Hash(BEGIN(hashRand), END(hashRand));
734f85c4 5989 bool fTrickleWait = ((UintToArith256(hashRand) & 3) != 0);
0a61b0df 5990
0a61b0df 5991 if (fTrickleWait)
5992 {
5993 vInvWait.push_back(inv);
5994 continue;
5995 }
5996 }
5997
5998 // returns true if wasn't already contained in the set
5999 if (pto->setInventoryKnown.insert(inv).second)
6000 {
6001 vInv.push_back(inv);
6002 if (vInv.size() >= 1000)
6003 {
6004 pto->PushMessage("inv", vInv);
6005 vInv.clear();
6006 }
6007 }
6008 }
6009 pto->vInventoryToSend = vInvWait;
6010 }
6011 if (!vInv.empty())
6012 pto->PushMessage("inv", vInv);
6013
341735eb 6014 // Detect whether we're stalling
f59d8f0b 6015 int64_t nNow = GetTimeMicros();
341735eb
PW
6016 if (!pto->fDisconnect && state.nStallingSince && state.nStallingSince < nNow - 1000000 * BLOCK_STALLING_TIMEOUT) {
6017 // Stalling only triggers when the block download window cannot move. During normal steady state,
6018 // the download window should be much larger than the to-be-downloaded set of blocks, so disconnection
6019 // should only happen during initial block download.
6020 LogPrintf("Peer=%d is stalling block download, disconnecting\n", pto->id);
f59d8f0b
PW
6021 pto->fDisconnect = true;
6022 }
3ff735c9 6023 // In case there is a block that has been in flight from this peer for (2 + 0.5 * N) times the block interval
91613034
PW
6024 // (with N the number of validated blocks that were in flight at the time it was requested), disconnect due to
6025 // timeout. We compensate for in-flight blocks to prevent killing off peers due to our own downstream link
7e6d23b1 6026 // being saturated. We only count validated in-flight blocks so peers can't advertise non-existing block hashes
91613034 6027 // to unreasonably increase our timeout.
8ba7f842
SD
6028 // We also compare the block download timeout originally calculated against the time at which we'd disconnect
6029 // if we assumed the block were being requested now (ignoring blocks we've requested from this peer, since we're
6030 // only looking at this peer's oldest request). This way a large queue in the past doesn't result in a
6031 // permanently large window for this block to be delivered (ie if the number of blocks in flight is decreasing
6032 // more quickly than once every 5 minutes, then we'll shorten the download window for this block).
6033 if (!pto->fDisconnect && state.vBlocksInFlight.size() > 0) {
6034 QueuedBlock &queuedBlock = state.vBlocksInFlight.front();
82737933 6035 int64_t nTimeoutIfRequestedNow = GetBlockTimeout(nNow, nQueuedValidatedHeaders - state.nBlocksInFlightValidHeaders, consensusParams);
8ba7f842
SD
6036 if (queuedBlock.nTimeDisconnect > nTimeoutIfRequestedNow) {
6037 LogPrint("net", "Reducing block download timeout for peer=%d block=%s, orig=%d new=%d\n", pto->id, queuedBlock.hash.ToString(), queuedBlock.nTimeDisconnect, nTimeoutIfRequestedNow);
6038 queuedBlock.nTimeDisconnect = nTimeoutIfRequestedNow;
6039 }
6040 if (queuedBlock.nTimeDisconnect < nNow) {
6041 LogPrintf("Timeout downloading block %s from peer=%d, disconnecting\n", queuedBlock.hash.ToString(), pto->id);
6042 pto->fDisconnect = true;
6043 }
91613034 6044 }
f59d8f0b 6045
0a61b0df 6046 //
f59d8f0b 6047 // Message: getdata (blocks)
0a61b0df 6048 //
6049 vector<CInv> vGetData;
00dcaf4b 6050 if (!pto->fDisconnect && !pto->fClient && (fFetch || !IsInitialBlockDownload()) && state.nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
341735eb
PW
6051 vector<CBlockIndex*> vToDownload;
6052 NodeId staller = -1;
6053 FindNextBlocksToDownload(pto->GetId(), MAX_BLOCKS_IN_TRANSIT_PER_PEER - state.nBlocksInFlight, vToDownload, staller);
6054 BOOST_FOREACH(CBlockIndex *pindex, vToDownload) {
6055 vGetData.push_back(CInv(MSG_BLOCK, pindex->GetBlockHash()));
82737933 6056 MarkBlockAsInFlight(pto->GetId(), pindex->GetBlockHash(), consensusParams, pindex);
1af838b3
B
6057 LogPrint("net", "Requesting block %s (%d) peer=%d\n", pindex->GetBlockHash().ToString(),
6058 pindex->nHeight, pto->id);
341735eb
PW
6059 }
6060 if (state.nBlocksInFlight == 0 && staller != -1) {
1bcee67e 6061 if (State(staller)->nStallingSince == 0) {
341735eb 6062 State(staller)->nStallingSince = nNow;
1bcee67e
B
6063 LogPrint("net", "Stall started peer=%d\n", staller);
6064 }
f59d8f0b
PW
6065 }
6066 }
6067
6068 //
6069 // Message: getdata (non-blocks)
6070 //
6071 while (!pto->fDisconnect && !pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
0a61b0df 6072 {
6073 const CInv& inv = (*pto->mapAskFor.begin()).second;
ae8bfd12 6074 if (!AlreadyHave(inv))
0a61b0df 6075 {
3b570559 6076 if (fDebug)
2e36866f 6077 LogPrint("net", "Requesting %s peer=%d\n", inv.ToString(), pto->id);
0a61b0df 6078 vGetData.push_back(inv);
6079 if (vGetData.size() >= 1000)
6080 {
6081 pto->PushMessage("getdata", vGetData);
6082 vGetData.clear();
6083 }
e2190f80
GM
6084 } else {
6085 //If we're not going to ask, don't expect a response.
6086 pto->setAskFor.erase(inv.hash);
0a61b0df 6087 }
6088 pto->mapAskFor.erase(pto->mapAskFor.begin());
6089 }
6090 if (!vGetData.empty())
6091 pto->PushMessage("getdata", vGetData);
6092
6093 }
6094 return true;
6095}
6096
651480c8 6097 std::string CBlockFileInfo::ToString() const {
2c2cc5da 6098 return strprintf("CBlockFileInfo(blocks=%u, size=%u, heights=%u...%u, time=%s...%s)", nBlocks, nSize, nHeightFirst, nHeightLast, DateTimeStrFormat("%Y-%m-%d", nTimeFirst), DateTimeStrFormat("%Y-%m-%d", nTimeLast));
651480c8 6099 }
0a61b0df 6100
6101
6102
39d2e9e0 6103static class CMainCleanup
3427517d
PW
6104{
6105public:
6106 CMainCleanup() {}
6107 ~CMainCleanup() {
6108 // block headers
145d5be8 6109 BlockMap::iterator it1 = mapBlockIndex.begin();
3427517d
PW
6110 for (; it1 != mapBlockIndex.end(); it1++)
6111 delete (*it1).second;
6112 mapBlockIndex.clear();
6113
3427517d 6114 // orphan transactions
3427517d 6115 mapOrphanTransactions.clear();
c74332c6 6116 mapOrphanTransactionsByPrev.clear();
3427517d
PW
6117 }
6118} instance_of_cmaincleanup;
072099d7
S
6119
6120
6121// Set default values of new CMutableTransaction based on consensus rules at given height.
6122CMutableTransaction CreateNewContextualCMutableTransaction(const Consensus::Params& consensusParams, int nHeight)
6123{
6124 CMutableTransaction mtx;
6125
6126 bool isOverwintered = NetworkUpgradeActive(nHeight, consensusParams, Consensus::UPGRADE_OVERWINTER);
6127 if (isOverwintered) {
6128 mtx.fOverwintered = true;
fa70084c 6129 mtx.nExpiryHeight = nHeight + expiryDelta;
072099d7 6130
dc889d7f
JG
6131 if (NetworkUpgradeActive(nHeight, consensusParams, Consensus::UPGRADE_SAPLING)) {
6132 mtx.nVersionGroupId = SAPLING_VERSION_GROUP_ID;
6133 mtx.nVersion = SAPLING_TX_VERSION;
6134 } else {
6135 mtx.nVersionGroupId = OVERWINTER_VERSION_GROUP_ID;
6136 mtx.nVersion = OVERWINTER_TX_VERSION;
fa70084c
JG
6137 mtx.nExpiryHeight = std::min(
6138 mtx.nExpiryHeight,
6139 static_cast<uint32_t>(consensusParams.vUpgrades[Consensus::UPGRADE_SAPLING].nActivationHeight - 1));
dc889d7f 6140 }
072099d7
S
6141 }
6142 return mtx;
6143}
This page took 1.984866 seconds and 4 git commands to generate.