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