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