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