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