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