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