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