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