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