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