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