]>
Commit | Line | Data |
---|---|---|
0a61b0df | 1 | // Copyright (c) 2009-2010 Satoshi Nakamoto |
88216419 | 2 | // Copyright (c) 2009-2012 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 | ||
f35c6c4f | 6 | #include "alert.h" |
eb5fff9e | 7 | #include "checkpoints.h" |
1512d5ce | 8 | #include "db.h" |
2d8a4829 | 9 | #include "txdb.h" |
40c2614e | 10 | #include "net.h" |
edd309e5 | 11 | #include "init.h" |
ed6d0b5f | 12 | #include "ui_interface.h" |
d237f62c | 13 | #include <boost/algorithm/string/replace.hpp> |
926e14b3 | 14 | #include <boost/filesystem.hpp> |
31f29312 | 15 | #include <boost/filesystem/fstream.hpp> |
0a61b0df | 16 | |
223b6f1b WL |
17 | using namespace std; |
18 | using namespace boost; | |
0a61b0df | 19 | |
20 | // | |
21 | // Global state | |
22 | // | |
23 | ||
64c7ee7e PW |
24 | CCriticalSection cs_setpwalletRegistered; |
25 | set<CWallet*> setpwalletRegistered; | |
26 | ||
0a61b0df | 27 | CCriticalSection cs_main; |
28 | ||
8e45ed66 | 29 | CTxMemPool mempool; |
0a61b0df | 30 | unsigned int nTransactionsUpdated = 0; |
0a61b0df | 31 | |
32 | map<uint256, CBlockIndex*> mapBlockIndex; | |
5cbf7532 | 33 | uint256 hashGenesisBlock("0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f"); |
99860de3 | 34 | static CBigNum bnProofOfWorkLimit(~uint256(0) >> 32); |
0a61b0df | 35 | CBlockIndex* pindexGenesisBlock = NULL; |
36 | int nBestHeight = -1; | |
37 | CBigNum bnBestChainWork = 0; | |
38 | CBigNum bnBestInvalidWork = 0; | |
39 | uint256 hashBestChain = 0; | |
40 | CBlockIndex* pindexBest = NULL; | |
857c61df | 41 | set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexValid; // may contain all CBlockIndex*'s that have validness >=BLOCK_VALID_TRANSACTIONS, and must contain those who aren't failed |
bde280b9 | 42 | int64 nTimeBestReceived = 0; |
66b02c93 | 43 | bool fImporting = false; |
7fea4846 | 44 | bool fReindex = false; |
1c83b0a3 | 45 | unsigned int nCoinCacheSize = 5000; |
0a61b0df | 46 | |
a8b95ce6 WL |
47 | CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have |
48 | ||
0a61b0df | 49 | map<uint256, CBlock*> mapOrphanBlocks; |
50 | multimap<uint256, CBlock*> mapOrphanBlocksByPrev; | |
51 | ||
52 | map<uint256, CDataStream*> mapOrphanTransactions; | |
77b99cf7 | 53 | map<uint256, map<uint256, CDataStream*> > mapOrphanTransactionsByPrev; |
0a61b0df | 54 | |
7bf8b7c2 GA |
55 | // Constant stuff for coinbase transactions we create: |
56 | CScript COINBASE_FLAGS; | |
0a61b0df | 57 | |
2bc4fd60 LD |
58 | const string strMessageMagic = "Bitcoin Signed Message:\n"; |
59 | ||
0a61b0df | 60 | double dHashesPerSec; |
bde280b9 | 61 | int64 nHPSTimerStart; |
0a61b0df | 62 | |
63 | // Settings | |
bde280b9 | 64 | int64 nTransactionFee = 0; |
972060ce | 65 | |
8bb5edc1 | 66 | |
0a61b0df | 67 | |
64c7ee7e PW |
68 | ////////////////////////////////////////////////////////////////////////////// |
69 | // | |
70 | // dispatching functions | |
71 | // | |
72 | ||
d825e6a3 PW |
73 | // These functions dispatch to one or all registered wallets |
74 | ||
75 | ||
64c7ee7e PW |
76 | void RegisterWallet(CWallet* pwalletIn) |
77 | { | |
64c7ee7e | 78 | { |
f8dcd5ca | 79 | LOCK(cs_setpwalletRegistered); |
64c7ee7e PW |
80 | setpwalletRegistered.insert(pwalletIn); |
81 | } | |
82 | } | |
83 | ||
84 | void UnregisterWallet(CWallet* pwalletIn) | |
85 | { | |
64c7ee7e | 86 | { |
f8dcd5ca | 87 | LOCK(cs_setpwalletRegistered); |
64c7ee7e PW |
88 | setpwalletRegistered.erase(pwalletIn); |
89 | } | |
90 | } | |
91 | ||
d825e6a3 | 92 | // check whether the passed transaction is from us |
64c7ee7e PW |
93 | bool static IsFromMe(CTransaction& tx) |
94 | { | |
95 | BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) | |
96 | if (pwallet->IsFromMe(tx)) | |
97 | return true; | |
98 | return false; | |
99 | } | |
100 | ||
d825e6a3 | 101 | // get the wallet transaction with the given hash (if it exists) |
64c7ee7e PW |
102 | bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx) |
103 | { | |
104 | BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) | |
105 | if (pwallet->GetTransaction(hashTx,wtx)) | |
106 | return true; | |
107 | return false; | |
108 | } | |
109 | ||
d825e6a3 | 110 | // erases transaction with the given hash from all wallets |
64c7ee7e PW |
111 | void static EraseFromWallets(uint256 hash) |
112 | { | |
113 | BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) | |
114 | pwallet->EraseFromWallet(hash); | |
115 | } | |
116 | ||
d825e6a3 | 117 | // make sure all wallets know about the given transaction, in the given block |
64dd46fd | 118 | void SyncWithWallets(const uint256 &hash, const CTransaction& tx, const CBlock* pblock, bool fUpdate) |
64c7ee7e PW |
119 | { |
120 | BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) | |
64dd46fd | 121 | pwallet->AddToWalletIfInvolvingMe(hash, tx, pblock, fUpdate); |
64c7ee7e PW |
122 | } |
123 | ||
d825e6a3 | 124 | // notify wallets about a new best chain |
64c7ee7e PW |
125 | void static SetBestChain(const CBlockLocator& loc) |
126 | { | |
127 | BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) | |
128 | pwallet->SetBestChain(loc); | |
129 | } | |
130 | ||
d825e6a3 | 131 | // notify wallets about an updated transaction |
64c7ee7e PW |
132 | void static UpdatedTransaction(const uint256& hashTx) |
133 | { | |
134 | BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) | |
135 | pwallet->UpdatedTransaction(hashTx); | |
136 | } | |
137 | ||
d825e6a3 | 138 | // dump all wallets |
64c7ee7e PW |
139 | void static PrintWallets(const CBlock& block) |
140 | { | |
141 | BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) | |
142 | pwallet->PrintWallet(block); | |
143 | } | |
144 | ||
d825e6a3 | 145 | // notify wallets about an incoming inventory (for request counts) |
64c7ee7e PW |
146 | void static Inventory(const uint256& hash) |
147 | { | |
148 | BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) | |
149 | pwallet->Inventory(hash); | |
150 | } | |
151 | ||
d825e6a3 | 152 | // ask wallets to resend their transactions |
64c7ee7e PW |
153 | void static ResendWalletTransactions() |
154 | { | |
155 | BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) | |
156 | pwallet->ResendWalletTransactions(); | |
157 | } | |
158 | ||
159 | ||
160 | ||
161 | ||
162 | ||
163 | ||
164 | ||
450cbb09 PW |
165 | ////////////////////////////////////////////////////////////////////////////// |
166 | // | |
167 | // CCoinsView implementations | |
168 | // | |
169 | ||
170 | bool CCoinsView::GetCoins(uint256 txid, CCoins &coins) { return false; } | |
171 | bool CCoinsView::SetCoins(uint256 txid, const CCoins &coins) { return false; } | |
172 | bool CCoinsView::HaveCoins(uint256 txid) { return false; } | |
173 | CBlockIndex *CCoinsView::GetBestBlock() { return NULL; } | |
174 | bool CCoinsView::SetBestBlock(CBlockIndex *pindex) { return false; } | |
ae8bfd12 | 175 | bool CCoinsView::BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex) { return false; } |
beeb5761 | 176 | bool CCoinsView::GetStats(CCoinsStats &stats) { return false; } |
450cbb09 | 177 | |
13c51f20 | 178 | |
450cbb09 PW |
179 | CCoinsViewBacked::CCoinsViewBacked(CCoinsView &viewIn) : base(&viewIn) { } |
180 | bool CCoinsViewBacked::GetCoins(uint256 txid, CCoins &coins) { return base->GetCoins(txid, coins); } | |
181 | bool CCoinsViewBacked::SetCoins(uint256 txid, const CCoins &coins) { return base->SetCoins(txid, coins); } | |
182 | bool CCoinsViewBacked::HaveCoins(uint256 txid) { return base->HaveCoins(txid); } | |
183 | CBlockIndex *CCoinsViewBacked::GetBestBlock() { return base->GetBestBlock(); } | |
184 | bool CCoinsViewBacked::SetBestBlock(CBlockIndex *pindex) { return base->SetBestBlock(pindex); } | |
185 | void CCoinsViewBacked::SetBackend(CCoinsView &viewIn) { base = &viewIn; } | |
ae8bfd12 | 186 | bool CCoinsViewBacked::BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex) { return base->BatchWrite(mapCoins, pindex); } |
beeb5761 | 187 | bool CCoinsViewBacked::GetStats(CCoinsStats &stats) { return base->GetStats(stats); } |
450cbb09 PW |
188 | |
189 | CCoinsViewCache::CCoinsViewCache(CCoinsView &baseIn, bool fDummy) : CCoinsViewBacked(baseIn), pindexTip(NULL) { } | |
190 | ||
191 | bool CCoinsViewCache::GetCoins(uint256 txid, CCoins &coins) { | |
192 | if (cacheCoins.count(txid)) { | |
193 | coins = cacheCoins[txid]; | |
194 | return true; | |
195 | } | |
196 | if (base->GetCoins(txid, coins)) { | |
197 | cacheCoins[txid] = coins; | |
198 | return true; | |
199 | } | |
200 | return false; | |
201 | } | |
202 | ||
13c51f20 PW |
203 | std::map<uint256,CCoins>::iterator CCoinsViewCache::FetchCoins(uint256 txid) { |
204 | std::map<uint256,CCoins>::iterator it = cacheCoins.find(txid); | |
205 | if (it != cacheCoins.end()) | |
206 | return it; | |
207 | CCoins tmp; | |
208 | if (!base->GetCoins(txid,tmp)) | |
209 | return it; | |
210 | std::pair<std::map<uint256,CCoins>::iterator,bool> ret = cacheCoins.insert(std::make_pair(txid, tmp)); | |
211 | return ret.first; | |
212 | } | |
213 | ||
214 | CCoins &CCoinsViewCache::GetCoins(uint256 txid) { | |
215 | std::map<uint256,CCoins>::iterator it = FetchCoins(txid); | |
216 | assert(it != cacheCoins.end()); | |
217 | return it->second; | |
218 | } | |
219 | ||
450cbb09 PW |
220 | bool CCoinsViewCache::SetCoins(uint256 txid, const CCoins &coins) { |
221 | cacheCoins[txid] = coins; | |
222 | return true; | |
223 | } | |
224 | ||
225 | bool CCoinsViewCache::HaveCoins(uint256 txid) { | |
13c51f20 | 226 | return FetchCoins(txid) != cacheCoins.end(); |
450cbb09 PW |
227 | } |
228 | ||
229 | CBlockIndex *CCoinsViewCache::GetBestBlock() { | |
230 | if (pindexTip == NULL) | |
231 | pindexTip = base->GetBestBlock(); | |
232 | return pindexTip; | |
233 | } | |
234 | ||
235 | bool CCoinsViewCache::SetBestBlock(CBlockIndex *pindex) { | |
236 | pindexTip = pindex; | |
237 | return true; | |
238 | } | |
239 | ||
ae8bfd12 PW |
240 | bool CCoinsViewCache::BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex) { |
241 | for (std::map<uint256, CCoins>::const_iterator it = mapCoins.begin(); it != mapCoins.end(); it++) | |
242 | cacheCoins[it->first] = it->second; | |
243 | pindexTip = pindex; | |
450cbb09 PW |
244 | return true; |
245 | } | |
246 | ||
ae8bfd12 PW |
247 | bool CCoinsViewCache::Flush() { |
248 | bool fOk = base->BatchWrite(cacheCoins, pindexTip); | |
249 | if (fOk) | |
250 | cacheCoins.clear(); | |
251 | return fOk; | |
252 | } | |
253 | ||
254 | unsigned int CCoinsViewCache::GetCacheSize() { | |
255 | return cacheCoins.size(); | |
256 | } | |
257 | ||
450cbb09 PW |
258 | /** CCoinsView that brings transactions from a memorypool into view. |
259 | It does not check for spendings by memory pool transactions. */ | |
260 | CCoinsViewMemPool::CCoinsViewMemPool(CCoinsView &baseIn, CTxMemPool &mempoolIn) : CCoinsViewBacked(baseIn), mempool(mempoolIn) { } | |
261 | ||
262 | bool CCoinsViewMemPool::GetCoins(uint256 txid, CCoins &coins) { | |
263 | if (base->GetCoins(txid, coins)) | |
264 | return true; | |
265 | if (mempool.exists(txid)) { | |
266 | const CTransaction &tx = mempool.lookup(txid); | |
267 | coins = CCoins(tx, MEMPOOL_HEIGHT); | |
268 | return true; | |
269 | } | |
270 | return false; | |
271 | } | |
272 | ||
273 | bool CCoinsViewMemPool::HaveCoins(uint256 txid) { | |
274 | return mempool.exists(txid) || base->HaveCoins(txid); | |
275 | } | |
276 | ||
ae8bfd12 | 277 | CCoinsViewCache *pcoinsTip = NULL; |
d979e6e3 | 278 | CBlockTreeDB *pblocktree = NULL; |
450cbb09 | 279 | |
0a61b0df | 280 | ////////////////////////////////////////////////////////////////////////////// |
281 | // | |
282 | // mapOrphanTransactions | |
283 | // | |
284 | ||
77b99cf7 | 285 | bool AddOrphanTx(const CDataStream& vMsg) |
0a61b0df | 286 | { |
287 | CTransaction tx; | |
288 | CDataStream(vMsg) >> tx; | |
289 | uint256 hash = tx.GetHash(); | |
290 | if (mapOrphanTransactions.count(hash)) | |
77b99cf7 GA |
291 | return false; |
292 | ||
293 | CDataStream* pvMsg = new CDataStream(vMsg); | |
142e6041 | 294 | |
77b99cf7 GA |
295 | // Ignore big transactions, to avoid a |
296 | // send-big-orphans memory exhaustion attack. If a peer has a legitimate | |
297 | // large transaction with a missing parent then we assume | |
298 | // it will rebroadcast it later, after the parent transaction(s) | |
299 | // have been mined or received. | |
300 | // 10,000 orphans, each of which is at most 5,000 bytes big is | |
301 | // at most 500 megabytes of orphans: | |
302 | if (pvMsg->size() > 5000) | |
303 | { | |
d210f4f5 | 304 | printf("ignoring large orphan tx (size: %"PRIszu", hash: %s)\n", pvMsg->size(), hash.ToString().substr(0,10).c_str()); |
c283b3c5 | 305 | delete pvMsg; |
77b99cf7 GA |
306 | return false; |
307 | } | |
142e6041 | 308 | |
77b99cf7 | 309 | mapOrphanTransactions[hash] = pvMsg; |
223b6f1b | 310 | BOOST_FOREACH(const CTxIn& txin, tx.vin) |
77b99cf7 GA |
311 | mapOrphanTransactionsByPrev[txin.prevout.hash].insert(make_pair(hash, pvMsg)); |
312 | ||
d210f4f5 | 313 | printf("stored orphan tx %s (mapsz %"PRIszu")\n", hash.ToString().substr(0,10).c_str(), |
77b99cf7 GA |
314 | mapOrphanTransactions.size()); |
315 | return true; | |
0a61b0df | 316 | } |
317 | ||
64c7ee7e | 318 | void static EraseOrphanTx(uint256 hash) |
0a61b0df | 319 | { |
320 | if (!mapOrphanTransactions.count(hash)) | |
321 | return; | |
322 | const CDataStream* pvMsg = mapOrphanTransactions[hash]; | |
323 | CTransaction tx; | |
324 | CDataStream(*pvMsg) >> tx; | |
223b6f1b | 325 | BOOST_FOREACH(const CTxIn& txin, tx.vin) |
0a61b0df | 326 | { |
77b99cf7 GA |
327 | mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash); |
328 | if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty()) | |
329 | mapOrphanTransactionsByPrev.erase(txin.prevout.hash); | |
0a61b0df | 330 | } |
331 | delete pvMsg; | |
332 | mapOrphanTransactions.erase(hash); | |
333 | } | |
334 | ||
7bd9c3a3 | 335 | unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans) |
142e6041 | 336 | { |
7bd9c3a3 | 337 | unsigned int nEvicted = 0; |
142e6041 GA |
338 | while (mapOrphanTransactions.size() > nMaxOrphans) |
339 | { | |
340 | // Evict a random orphan: | |
f718aedd | 341 | uint256 randomhash = GetRandHash(); |
142e6041 GA |
342 | map<uint256, CDataStream*>::iterator it = mapOrphanTransactions.lower_bound(randomhash); |
343 | if (it == mapOrphanTransactions.end()) | |
344 | it = mapOrphanTransactions.begin(); | |
345 | EraseOrphanTx(it->first); | |
346 | ++nEvicted; | |
347 | } | |
348 | return nEvicted; | |
349 | } | |
0a61b0df | 350 | |
351 | ||
352 | ||
353 | ||
354 | ||
355 | ||
356 | ||
357 | ////////////////////////////////////////////////////////////////////////////// | |
358 | // | |
450cbb09 | 359 | // CTransaction |
0a61b0df | 360 | // |
361 | ||
e679ec96 GA |
362 | bool CTransaction::IsStandard() const |
363 | { | |
dae3e10a GA |
364 | if (nVersion > CTransaction::CURRENT_VERSION) |
365 | return false; | |
366 | ||
e679ec96 GA |
367 | BOOST_FOREACH(const CTxIn& txin, vin) |
368 | { | |
2a45a494 | 369 | // Biggest 'standard' txin is a 3-signature 3-of-3 CHECKMULTISIG |
922e8e29 | 370 | // pay-to-script-hash, which is 3 ~80-byte signatures, 3 |
e679ec96 | 371 | // ~65-byte public keys, plus a few script ops. |
2a45a494 | 372 | if (txin.scriptSig.size() > 500) |
922e8e29 | 373 | return false; |
e679ec96 | 374 | if (!txin.scriptSig.IsPushOnly()) |
922e8e29 | 375 | return false; |
e679ec96 | 376 | } |
65ce2156 | 377 | BOOST_FOREACH(const CTxOut& txout, vout) { |
e679ec96 | 378 | if (!::IsStandard(txout.scriptPubKey)) |
922e8e29 | 379 | return false; |
65ce2156 PW |
380 | if (txout.nValue == 0) |
381 | return false; | |
382 | } | |
e679ec96 GA |
383 | return true; |
384 | } | |
385 | ||
386 | // | |
387 | // Check transaction inputs, and make sure any | |
922e8e29 | 388 | // pay-to-script-hash transactions are evaluating IsStandard scripts |
e679ec96 GA |
389 | // |
390 | // Why bother? To avoid denial-of-service attacks; an attacker | |
922e8e29 GA |
391 | // can submit a standard HASH... OP_EQUAL transaction, |
392 | // which will get accepted into blocks. The redemption | |
393 | // script can be anything; an attacker could use a very | |
e679ec96 GA |
394 | // expensive-to-check-upon-redemption script like: |
395 | // DUP CHECKSIG DROP ... repeated 100 times... OP_1 | |
396 | // | |
13c51f20 | 397 | bool CTransaction::AreInputsStandard(CCoinsViewCache& mapInputs) const |
e679ec96 | 398 | { |
8d7849b6 | 399 | if (IsCoinBase()) |
575bdcde | 400 | return true; // Coinbases don't use vin normally |
8d7849b6 | 401 | |
c376ac35 | 402 | for (unsigned int i = 0; i < vin.size(); i++) |
e679ec96 | 403 | { |
8d7849b6 | 404 | const CTxOut& prev = GetOutputFor(vin[i], mapInputs); |
e679ec96 GA |
405 | |
406 | vector<vector<unsigned char> > vSolutions; | |
2a45a494 GA |
407 | txnouttype whichType; |
408 | // get the scriptPubKey corresponding to this input: | |
8d7849b6 | 409 | const CScript& prevScript = prev.scriptPubKey; |
2a45a494 | 410 | if (!Solver(prevScript, whichType, vSolutions)) |
922e8e29 | 411 | return false; |
39f0d968 | 412 | int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions); |
c0a0a93d JG |
413 | if (nArgsExpected < 0) |
414 | return false; | |
39f0d968 GA |
415 | |
416 | // Transactions with extra stuff in their scriptSigs are | |
417 | // non-standard. Note that this EvalScript() call will | |
418 | // be quick, because if there are any operations | |
419 | // beside "push data" in the scriptSig the | |
420 | // IsStandard() call returns false | |
421 | vector<vector<unsigned char> > stack; | |
58bc86e3 | 422 | if (!EvalScript(stack, vin[i].scriptSig, *this, i, false, 0)) |
39f0d968 GA |
423 | return false; |
424 | ||
e679ec96 GA |
425 | if (whichType == TX_SCRIPTHASH) |
426 | { | |
922e8e29 | 427 | if (stack.empty()) |
e679ec96 | 428 | return false; |
2a45a494 | 429 | CScript subscript(stack.back().begin(), stack.back().end()); |
39f0d968 GA |
430 | vector<vector<unsigned char> > vSolutions2; |
431 | txnouttype whichType2; | |
432 | if (!Solver(subscript, whichType2, vSolutions2)) | |
922e8e29 | 433 | return false; |
39f0d968 GA |
434 | if (whichType2 == TX_SCRIPTHASH) |
435 | return false; | |
c0a0a93d JG |
436 | |
437 | int tmpExpected; | |
438 | tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2); | |
439 | if (tmpExpected < 0) | |
440 | return false; | |
441 | nArgsExpected += tmpExpected; | |
e679ec96 | 442 | } |
39f0d968 | 443 | |
c0a0a93d | 444 | if (stack.size() != (unsigned int)nArgsExpected) |
39f0d968 | 445 | return false; |
e679ec96 GA |
446 | } |
447 | ||
448 | return true; | |
449 | } | |
450 | ||
7bd9c3a3 | 451 | unsigned int |
922e8e29 GA |
452 | CTransaction::GetLegacySigOpCount() const |
453 | { | |
7bd9c3a3 | 454 | unsigned int nSigOps = 0; |
922e8e29 GA |
455 | BOOST_FOREACH(const CTxIn& txin, vin) |
456 | { | |
457 | nSigOps += txin.scriptSig.GetSigOpCount(false); | |
458 | } | |
459 | BOOST_FOREACH(const CTxOut& txout, vout) | |
460 | { | |
461 | nSigOps += txout.scriptPubKey.GetSigOpCount(false); | |
462 | } | |
463 | return nSigOps; | |
464 | } | |
0a61b0df | 465 | |
466 | ||
467 | int CMerkleTx::SetMerkleBranch(const CBlock* pblock) | |
468 | { | |
469 | if (fClient) | |
470 | { | |
471 | if (hashBlock == 0) | |
472 | return 0; | |
473 | } | |
474 | else | |
475 | { | |
476 | CBlock blockTmp; | |
450cbb09 PW |
477 | |
478 | if (pblock == NULL) { | |
450cbb09 | 479 | CCoins coins; |
ae8bfd12 | 480 | if (pcoinsTip->GetCoins(GetHash(), coins)) { |
450cbb09 PW |
481 | CBlockIndex *pindex = FindBlockByHeight(coins.nHeight); |
482 | if (pindex) { | |
483 | if (!blockTmp.ReadFromDisk(pindex)) | |
484 | return 0; | |
485 | pblock = &blockTmp; | |
486 | } | |
487 | } | |
0a61b0df | 488 | } |
489 | ||
450cbb09 | 490 | if (pblock) { |
0a61b0df | 491 | // Update the tx's hashBlock |
492 | hashBlock = pblock->GetHash(); | |
493 | ||
494 | // Locate the transaction | |
1d8c7a95 | 495 | for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++) |
0a61b0df | 496 | if (pblock->vtx[nIndex] == *(CTransaction*)this) |
497 | break; | |
1d8c7a95 | 498 | if (nIndex == (int)pblock->vtx.size()) |
0a61b0df | 499 | { |
500 | vMerkleBranch.clear(); | |
501 | nIndex = -1; | |
502 | printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n"); | |
503 | return 0; | |
504 | } | |
505 | ||
506 | // Fill in merkle branch | |
507 | vMerkleBranch = pblock->GetMerkleBranch(nIndex); | |
450cbb09 | 508 | } |
0a61b0df | 509 | } |
510 | ||
511 | // Is the tx in a block that's in the main chain | |
512 | map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock); | |
513 | if (mi == mapBlockIndex.end()) | |
514 | return 0; | |
515 | CBlockIndex* pindex = (*mi).second; | |
516 | if (!pindex || !pindex->IsInMainChain()) | |
517 | return 0; | |
518 | ||
519 | return pindexBest->nHeight - pindex->nHeight + 1; | |
520 | } | |
521 | ||
522 | ||
523 | ||
0a61b0df | 524 | |
525 | ||
526 | ||
527 | ||
a790fa46 | 528 | bool CTransaction::CheckTransaction() const |
529 | { | |
530 | // Basic checks that don't depend on any context | |
d0d9486f | 531 | if (vin.empty()) |
3e52aaf2 | 532 | return DoS(10, error("CTransaction::CheckTransaction() : vin empty")); |
d0d9486f | 533 | if (vout.empty()) |
3e52aaf2 | 534 | return DoS(10, error("CTransaction::CheckTransaction() : vout empty")); |
a790fa46 | 535 | // Size limits |
6b6aaa16 | 536 | if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE) |
3e52aaf2 | 537 | return DoS(100, error("CTransaction::CheckTransaction() : size limits failed")); |
a790fa46 | 538 | |
539 | // Check for negative or overflow output values | |
bde280b9 | 540 | int64 nValueOut = 0; |
223b6f1b | 541 | BOOST_FOREACH(const CTxOut& txout, vout) |
a790fa46 | 542 | { |
543 | if (txout.nValue < 0) | |
3e52aaf2 | 544 | return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue negative")); |
a790fa46 | 545 | if (txout.nValue > MAX_MONEY) |
3e52aaf2 | 546 | return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high")); |
a790fa46 | 547 | nValueOut += txout.nValue; |
548 | if (!MoneyRange(nValueOut)) | |
3e52aaf2 | 549 | return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range")); |
a790fa46 | 550 | } |
551 | ||
33208fb5 MC |
552 | // Check for duplicate inputs |
553 | set<COutPoint> vInOutPoints; | |
554 | BOOST_FOREACH(const CTxIn& txin, vin) | |
555 | { | |
556 | if (vInOutPoints.count(txin.prevout)) | |
557 | return false; | |
558 | vInOutPoints.insert(txin.prevout); | |
559 | } | |
560 | ||
a790fa46 | 561 | if (IsCoinBase()) |
562 | { | |
563 | if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100) | |
3e52aaf2 | 564 | return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size")); |
a790fa46 | 565 | } |
566 | else | |
567 | { | |
223b6f1b | 568 | BOOST_FOREACH(const CTxIn& txin, vin) |
a790fa46 | 569 | if (txin.prevout.IsNull()) |
3e52aaf2 | 570 | return DoS(10, error("CTransaction::CheckTransaction() : prevout is null")); |
a790fa46 | 571 | } |
572 | ||
573 | return true; | |
574 | } | |
575 | ||
76970091 JG |
576 | int64 CTransaction::GetMinFee(unsigned int nBlockSize, bool fAllowFree, |
577 | enum GetMinFee_mode mode) const | |
578 | { | |
579 | // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE | |
580 | int64 nBaseFee = (mode == GMF_RELAY) ? MIN_RELAY_TX_FEE : MIN_TX_FEE; | |
581 | ||
582 | unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION); | |
583 | unsigned int nNewBlockSize = nBlockSize + nBytes; | |
584 | int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee; | |
585 | ||
586 | if (fAllowFree) | |
587 | { | |
588 | if (nBlockSize == 1) | |
589 | { | |
590 | // Transactions under 10K are free | |
591 | // (about 4500 BTC if made of 50 BTC inputs) | |
592 | if (nBytes < 10000) | |
593 | nMinFee = 0; | |
594 | } | |
595 | else | |
596 | { | |
597 | // Free transaction area | |
598 | if (nNewBlockSize < 27000) | |
599 | nMinFee = 0; | |
600 | } | |
601 | } | |
602 | ||
603 | // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01 | |
604 | if (nMinFee < nBaseFee) | |
605 | { | |
606 | BOOST_FOREACH(const CTxOut& txout, vout) | |
607 | if (txout.nValue < CENT) | |
608 | nMinFee = nBaseFee; | |
609 | } | |
610 | ||
611 | // Raise the price as the block approaches full | |
612 | if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2) | |
613 | { | |
614 | if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN) | |
615 | return MAX_MONEY; | |
616 | nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize); | |
617 | } | |
618 | ||
619 | if (!MoneyRange(nMinFee)) | |
620 | nMinFee = MAX_MONEY; | |
621 | return nMinFee; | |
622 | } | |
623 | ||
450cbb09 PW |
624 | void CTxMemPool::pruneSpent(const uint256 &hashTx, CCoins &coins) |
625 | { | |
626 | LOCK(cs); | |
627 | ||
628 | std::map<COutPoint, CInPoint>::iterator it = mapNextTx.lower_bound(COutPoint(hashTx, 0)); | |
629 | ||
630 | // iterate over all COutPoints in mapNextTx whose hash equals the provided hashTx | |
631 | while (it != mapNextTx.end() && it->first.hash == hashTx) { | |
632 | coins.Spend(it->first.n); // and remove those outputs from coins | |
633 | it++; | |
634 | } | |
635 | } | |
76970091 | 636 | |
ae8bfd12 | 637 | bool CTxMemPool::accept(CTransaction &tx, bool fCheckInputs, |
d01903e7 | 638 | bool* pfMissingInputs) |
0a61b0df | 639 | { |
640 | if (pfMissingInputs) | |
641 | *pfMissingInputs = false; | |
642 | ||
d01903e7 JG |
643 | if (!tx.CheckTransaction()) |
644 | return error("CTxMemPool::accept() : CheckTransaction failed"); | |
a790fa46 | 645 | |
0a61b0df | 646 | // Coinbase is only valid in a block, not as a loose transaction |
d01903e7 JG |
647 | if (tx.IsCoinBase()) |
648 | return tx.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx")); | |
0a61b0df | 649 | |
0a61b0df | 650 | // To help v0.1.5 clients who would see it as a negative number |
d01903e7 JG |
651 | if ((int64)tx.nLockTime > std::numeric_limits<int>::max()) |
652 | return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet"); | |
f1e1fb4b | 653 | |
5ec05f0a | 654 | // Rather not work on nonstandard transactions (unless -testnet) |
d01903e7 JG |
655 | if (!fTestNet && !tx.IsStandard()) |
656 | return error("CTxMemPool::accept() : nonstandard transaction type"); | |
97ee01ad | 657 | |
450cbb09 | 658 | // is it already in the memory pool? |
d01903e7 | 659 | uint256 hash = tx.GetHash(); |
f8dcd5ca | 660 | { |
d01903e7 JG |
661 | LOCK(cs); |
662 | if (mapTx.count(hash)) | |
0a61b0df | 663 | return false; |
f8dcd5ca | 664 | } |
0a61b0df | 665 | |
666 | // Check for conflicts with in-memory transactions | |
667 | CTransaction* ptxOld = NULL; | |
c23617fe | 668 | for (unsigned int i = 0; i < tx.vin.size(); i++) |
0a61b0df | 669 | { |
d01903e7 | 670 | COutPoint outpoint = tx.vin[i].prevout; |
0a61b0df | 671 | if (mapNextTx.count(outpoint)) |
672 | { | |
673 | // Disable replacement feature for now | |
674 | return false; | |
675 | ||
676 | // Allow replacing with a newer version of the same transaction | |
677 | if (i != 0) | |
678 | return false; | |
679 | ptxOld = mapNextTx[outpoint].ptx; | |
683bcb91 | 680 | if (ptxOld->IsFinal()) |
681 | return false; | |
d01903e7 | 682 | if (!tx.IsNewerThan(*ptxOld)) |
0a61b0df | 683 | return false; |
c23617fe | 684 | for (unsigned int i = 0; i < tx.vin.size(); i++) |
0a61b0df | 685 | { |
d01903e7 | 686 | COutPoint outpoint = tx.vin[i].prevout; |
0a61b0df | 687 | if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld) |
688 | return false; | |
689 | } | |
690 | break; | |
691 | } | |
692 | } | |
693 | ||
97ee01ad | 694 | if (fCheckInputs) |
0a61b0df | 695 | { |
4afc0b54 PW |
696 | CCoinsView dummy; |
697 | CCoinsViewCache view(dummy); | |
698 | ||
699 | { | |
700 | LOCK(cs); | |
701 | CCoinsViewMemPool viewMemPool(*pcoinsTip, *this); | |
702 | view.SetBackend(viewMemPool); | |
450cbb09 PW |
703 | |
704 | // do we already have it? | |
705 | if (view.HaveCoins(hash)) | |
33a53bc1 | 706 | return false; |
450cbb09 PW |
707 | |
708 | // do all inputs exist? | |
c2ed184f PW |
709 | // Note that this does not check for the presence of actual outputs (see the next check for that), |
710 | // only helps filling in pfMissingInputs (to determine missing vs spent). | |
450cbb09 PW |
711 | BOOST_FOREACH(const CTxIn txin, tx.vin) { |
712 | if (!view.HaveCoins(txin.prevout.hash)) { | |
713 | if (pfMissingInputs) | |
714 | *pfMissingInputs = true; | |
715 | return false; | |
716 | } | |
e679ec96 GA |
717 | } |
718 | ||
c2ed184f | 719 | // are the actual inputs available? |
13c51f20 PW |
720 | if (!tx.HaveInputs(view)) |
721 | return error("CTxMemPool::accept() : inputs already spent"); | |
13e5cce4 | 722 | |
4afc0b54 PW |
723 | // Bring the best block into scope |
724 | view.GetBestBlock(); | |
725 | ||
726 | // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool | |
727 | view.SetBackend(dummy); | |
728 | } | |
13c51f20 | 729 | |
922e8e29 | 730 | // Check for non-standard pay-to-script-hash in inputs |
450cbb09 | 731 | if (!tx.AreInputsStandard(view) && !fTestNet) |
d01903e7 | 732 | return error("CTxMemPool::accept() : nonstandard transaction input"); |
e679ec96 | 733 | |
137d0685 GA |
734 | // Note: if you modify this code to accept non-standard transactions, then |
735 | // you should add code here to check that the transaction does a | |
736 | // reasonable number of ECDSA signature verifications. | |
737 | ||
450cbb09 | 738 | int64 nFees = tx.GetValueIn(view)-tx.GetValueOut(); |
c23617fe | 739 | unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION); |
8d7849b6 GA |
740 | |
741 | // Don't accept it if it can't get into a block | |
17f8d6e4 JG |
742 | int64 txMinFee = tx.GetMinFee(1000, true, GMF_RELAY); |
743 | if (nFees < txMinFee) | |
744 | return error("CTxMemPool::accept() : not enough fees %s, %"PRI64d" < %"PRI64d, | |
b1d3e95a | 745 | hash.ToString().c_str(), |
17f8d6e4 | 746 | nFees, txMinFee); |
922e8e29 | 747 | |
5de8b54c | 748 | // Continuously rate-limit free transactions |
88abf703 | 749 | // This mitigates 'penny-flooding' -- sending thousands of free transactions just to |
b49f1398 | 750 | // be annoying or make others' transactions take longer to confirm. |
2bfda1be | 751 | if (nFees < MIN_RELAY_TX_FEE) |
97ee01ad | 752 | { |
88abf703 | 753 | static CCriticalSection cs; |
5de8b54c | 754 | static double dFreeCount; |
bde280b9 WL |
755 | static int64 nLastTime; |
756 | int64 nNow = GetTime(); | |
88abf703 | 757 | |
97ee01ad | 758 | { |
88abf703 GA |
759 | // Use an exponentially decaying ~10-minute window: |
760 | dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime)); | |
761 | nLastTime = nNow; | |
762 | // -limitfreerelay unit is thousand-bytes-per-minute | |
763 | // At default rate it would take over a month to fill 1GB | |
d01903e7 JG |
764 | if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(tx)) |
765 | return error("CTxMemPool::accept() : free transaction rejected by rate limiter"); | |
88abf703 GA |
766 | if (fDebug) |
767 | printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize); | |
768 | dFreeCount += nSize; | |
97ee01ad | 769 | } |
97ee01ad | 770 | } |
8d7849b6 GA |
771 | |
772 | // Check against previous transactions | |
773 | // This is done last to help prevent CPU exhaustion denial-of-service attacks. | |
99d0d0f3 | 774 | if (!tx.CheckInputs(view, CS_ALWAYS, SCRIPT_VERIFY_P2SH)) |
8d7849b6 | 775 | { |
d01903e7 | 776 | return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str()); |
8d7849b6 | 777 | } |
0a61b0df | 778 | } |
779 | ||
780 | // Store transaction in memory | |
0a61b0df | 781 | { |
d01903e7 | 782 | LOCK(cs); |
0a61b0df | 783 | if (ptxOld) |
784 | { | |
d01903e7 JG |
785 | printf("CTxMemPool::accept() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str()); |
786 | remove(*ptxOld); | |
0a61b0df | 787 | } |
f77654a0 | 788 | addUnchecked(hash, tx); |
0a61b0df | 789 | } |
790 | ||
791 | ///// are we sure this is ok when loading transactions or restoring block txes | |
792 | // If updated, erase old tx from wallet | |
793 | if (ptxOld) | |
64c7ee7e | 794 | EraseFromWallets(ptxOld->GetHash()); |
0a61b0df | 795 | |
d210f4f5 | 796 | printf("CTxMemPool::accept() : accepted %s (poolsz %"PRIszu")\n", |
133dce6a JG |
797 | hash.ToString().substr(0,10).c_str(), |
798 | mapTx.size()); | |
0a61b0df | 799 | return true; |
800 | } | |
801 | ||
ae8bfd12 | 802 | bool CTransaction::AcceptToMemoryPool(bool fCheckInputs, bool* pfMissingInputs) |
d01903e7 | 803 | { |
ae8bfd12 | 804 | return mempool.accept(*this, fCheckInputs, pfMissingInputs); |
d01903e7 | 805 | } |
340f0876 | 806 | |
f77654a0 | 807 | bool CTxMemPool::addUnchecked(const uint256& hash, CTransaction &tx) |
0a61b0df | 808 | { |
809 | // Add to memory pool without checking anything. Don't call this directly, | |
d01903e7 | 810 | // call CTxMemPool::accept to properly check the transaction first. |
0a61b0df | 811 | { |
8e45ed66 | 812 | mapTx[hash] = tx; |
c23617fe | 813 | for (unsigned int i = 0; i < tx.vin.size(); i++) |
8e45ed66 | 814 | mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i); |
0a61b0df | 815 | nTransactionsUpdated++; |
816 | } | |
817 | return true; | |
818 | } | |
819 | ||
820 | ||
8e45ed66 | 821 | bool CTxMemPool::remove(CTransaction &tx) |
0a61b0df | 822 | { |
823 | // Remove transaction from memory pool | |
0a61b0df | 824 | { |
8e45ed66 JG |
825 | LOCK(cs); |
826 | uint256 hash = tx.GetHash(); | |
827 | if (mapTx.count(hash)) | |
74f28bf1 | 828 | { |
8e45ed66 | 829 | BOOST_FOREACH(const CTxIn& txin, tx.vin) |
74f28bf1 | 830 | mapNextTx.erase(txin.prevout); |
8e45ed66 | 831 | mapTx.erase(hash); |
74f28bf1 | 832 | nTransactionsUpdated++; |
74f28bf1 | 833 | } |
0a61b0df | 834 | } |
835 | return true; | |
836 | } | |
837 | ||
bdab0cf5 | 838 | void CTxMemPool::clear() |
639b61d7 LD |
839 | { |
840 | LOCK(cs); | |
841 | mapTx.clear(); | |
842 | mapNextTx.clear(); | |
843 | ++nTransactionsUpdated; | |
844 | } | |
845 | ||
25d5c195 JG |
846 | void CTxMemPool::queryHashes(std::vector<uint256>& vtxid) |
847 | { | |
848 | vtxid.clear(); | |
0a61b0df | 849 | |
25d5c195 JG |
850 | LOCK(cs); |
851 | vtxid.reserve(mapTx.size()); | |
852 | for (map<uint256, CTransaction>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi) | |
853 | vtxid.push_back((*mi).first); | |
854 | } | |
0a61b0df | 855 | |
856 | ||
857 | ||
858 | ||
30ab2c9c | 859 | int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const |
0a61b0df | 860 | { |
861 | if (hashBlock == 0 || nIndex == -1) | |
862 | return 0; | |
863 | ||
864 | // Find the block it claims to be in | |
865 | map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock); | |
866 | if (mi == mapBlockIndex.end()) | |
867 | return 0; | |
868 | CBlockIndex* pindex = (*mi).second; | |
869 | if (!pindex || !pindex->IsInMainChain()) | |
870 | return 0; | |
871 | ||
872 | // Make sure the merkle branch connects to this block | |
873 | if (!fMerkleVerified) | |
874 | { | |
875 | if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot) | |
876 | return 0; | |
877 | fMerkleVerified = true; | |
878 | } | |
879 | ||
30ab2c9c | 880 | pindexRet = pindex; |
0a61b0df | 881 | return pindexBest->nHeight - pindex->nHeight + 1; |
882 | } | |
883 | ||
884 | ||
885 | int CMerkleTx::GetBlocksToMaturity() const | |
886 | { | |
887 | if (!IsCoinBase()) | |
888 | return 0; | |
889 | return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain()); | |
890 | } | |
891 | ||
892 | ||
ae8bfd12 | 893 | bool CMerkleTx::AcceptToMemoryPool(bool fCheckInputs) |
0a61b0df | 894 | { |
895 | if (fClient) | |
896 | { | |
450cbb09 | 897 | if (!IsInMainChain() && !ClientCheckInputs()) |
0a61b0df | 898 | return false; |
ae8bfd12 | 899 | return CTransaction::AcceptToMemoryPool(false); |
0a61b0df | 900 | } |
901 | else | |
902 | { | |
ae8bfd12 | 903 | return CTransaction::AcceptToMemoryPool(fCheckInputs); |
0a61b0df | 904 | } |
905 | } | |
906 | ||
907 | ||
908 | ||
ae8bfd12 | 909 | bool CWalletTx::AcceptWalletTransaction(bool fCheckInputs) |
0a61b0df | 910 | { |
0a61b0df | 911 | { |
235507ae | 912 | LOCK(mempool.cs); |
f1e1fb4b | 913 | // Add previous supporting transactions first |
223b6f1b | 914 | BOOST_FOREACH(CMerkleTx& tx, vtxPrev) |
0a61b0df | 915 | { |
916 | if (!tx.IsCoinBase()) | |
917 | { | |
918 | uint256 hash = tx.GetHash(); | |
ae8bfd12 PW |
919 | if (!mempool.exists(hash) && pcoinsTip->HaveCoins(hash)) |
920 | tx.AcceptToMemoryPool(fCheckInputs); | |
0a61b0df | 921 | } |
922 | } | |
ae8bfd12 | 923 | return AcceptToMemoryPool(fCheckInputs); |
0a61b0df | 924 | } |
f1e1fb4b | 925 | return false; |
0a61b0df | 926 | } |
927 | ||
395c1f44 | 928 | |
c73ba23e | 929 | // Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock |
450cbb09 | 930 | bool GetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock, bool fAllowSlow) |
c73ba23e | 931 | { |
450cbb09 | 932 | CBlockIndex *pindexSlow = NULL; |
c73ba23e PW |
933 | { |
934 | LOCK(cs_main); | |
935 | { | |
936 | LOCK(mempool.cs); | |
937 | if (mempool.exists(hash)) | |
938 | { | |
450cbb09 | 939 | txOut = mempool.lookup(hash); |
c73ba23e PW |
940 | return true; |
941 | } | |
942 | } | |
450cbb09 PW |
943 | |
944 | if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it | |
945 | int nHeight = -1; | |
946 | { | |
ae8bfd12 | 947 | CCoinsViewCache &view = *pcoinsTip; |
450cbb09 PW |
948 | CCoins coins; |
949 | if (view.GetCoins(hash, coins)) | |
950 | nHeight = coins.nHeight; | |
951 | } | |
952 | if (nHeight > 0) | |
953 | pindexSlow = FindBlockByHeight(nHeight); | |
c73ba23e PW |
954 | } |
955 | } | |
0a61b0df | 956 | |
450cbb09 PW |
957 | if (pindexSlow) { |
958 | CBlock block; | |
959 | if (block.ReadFromDisk(pindexSlow)) { | |
960 | BOOST_FOREACH(const CTransaction &tx, block.vtx) { | |
961 | if (tx.GetHash() == hash) { | |
962 | txOut = tx; | |
963 | hashBlock = pindexSlow->GetBlockHash(); | |
964 | return true; | |
965 | } | |
966 | } | |
967 | } | |
968 | } | |
0a61b0df | 969 | |
450cbb09 PW |
970 | return false; |
971 | } | |
0a61b0df | 972 | |
973 | ||
974 | ||
975 | ||
976 | ||
977 | ||
978 | ////////////////////////////////////////////////////////////////////////////// | |
979 | // | |
980 | // CBlock and CBlockIndex | |
981 | // | |
982 | ||
1be06419 LD |
983 | static CBlockIndex* pblockindexFBBHLast; |
984 | CBlockIndex* FindBlockByHeight(int nHeight) | |
985 | { | |
986 | CBlockIndex *pblockindex; | |
987 | if (nHeight < nBestHeight / 2) | |
988 | pblockindex = pindexGenesisBlock; | |
989 | else | |
990 | pblockindex = pindexBest; | |
991 | if (pblockindexFBBHLast && abs(nHeight - pblockindex->nHeight) > abs(nHeight - pblockindexFBBHLast->nHeight)) | |
992 | pblockindex = pblockindexFBBHLast; | |
993 | while (pblockindex->nHeight > nHeight) | |
994 | pblockindex = pblockindex->pprev; | |
995 | while (pblockindex->nHeight < nHeight) | |
996 | pblockindex = pblockindex->pnext; | |
997 | pblockindexFBBHLast = pblockindex; | |
998 | return pblockindex; | |
999 | } | |
1000 | ||
e754cf41 | 1001 | bool CBlock::ReadFromDisk(const CBlockIndex* pindex) |
0a61b0df | 1002 | { |
e754cf41 | 1003 | if (!ReadFromDisk(pindex->GetBlockPos())) |
0a61b0df | 1004 | return false; |
1005 | if (GetHash() != pindex->GetBlockHash()) | |
1006 | return error("CBlock::ReadFromDisk() : GetHash() doesn't match index"); | |
1007 | return true; | |
1008 | } | |
1009 | ||
e754cf41 | 1010 | uint256 static GetOrphanRoot(const CBlockHeader* pblock) |
0a61b0df | 1011 | { |
1012 | // Work back to the first block in the orphan chain | |
1013 | while (mapOrphanBlocks.count(pblock->hashPrevBlock)) | |
1014 | pblock = mapOrphanBlocks[pblock->hashPrevBlock]; | |
1015 | return pblock->GetHash(); | |
1016 | } | |
1017 | ||
bde280b9 | 1018 | int64 static GetBlockValue(int nHeight, int64 nFees) |
0a61b0df | 1019 | { |
bde280b9 | 1020 | int64 nSubsidy = 50 * COIN; |
0a61b0df | 1021 | |
5f2e4b05 | 1022 | // Subsidy is cut in half every 210000 blocks, which will occur approximately every 4 years |
0a61b0df | 1023 | nSubsidy >>= (nHeight / 210000); |
1024 | ||
1025 | return nSubsidy + nFees; | |
1026 | } | |
1027 | ||
bde280b9 WL |
1028 | static const int64 nTargetTimespan = 14 * 24 * 60 * 60; // two weeks |
1029 | static const int64 nTargetSpacing = 10 * 60; | |
1030 | static const int64 nInterval = nTargetTimespan / nTargetSpacing; | |
10fd7f66 GA |
1031 | |
1032 | // | |
1033 | // minimum amount of work that could possibly be required nTime after | |
1034 | // minimum work required was nBase | |
1035 | // | |
bde280b9 | 1036 | unsigned int ComputeMinWork(unsigned int nBase, int64 nTime) |
10fd7f66 | 1037 | { |
c52296a7 GA |
1038 | // Testnet has min-difficulty blocks |
1039 | // after nTargetSpacing*2 time between blocks: | |
1040 | if (fTestNet && nTime > nTargetSpacing*2) | |
1041 | return bnProofOfWorkLimit.GetCompact(); | |
1042 | ||
10fd7f66 GA |
1043 | CBigNum bnResult; |
1044 | bnResult.SetCompact(nBase); | |
1045 | while (nTime > 0 && bnResult < bnProofOfWorkLimit) | |
1046 | { | |
1047 | // Maximum 400% adjustment... | |
1048 | bnResult *= 4; | |
1049 | // ... in best-case exactly 4-times-normal target time | |
1050 | nTime -= nTargetTimespan*4; | |
1051 | } | |
1052 | if (bnResult > bnProofOfWorkLimit) | |
1053 | bnResult = bnProofOfWorkLimit; | |
1054 | return bnResult.GetCompact(); | |
1055 | } | |
1056 | ||
e754cf41 | 1057 | unsigned int static GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock) |
0a61b0df | 1058 | { |
c52296a7 | 1059 | unsigned int nProofOfWorkLimit = bnProofOfWorkLimit.GetCompact(); |
0a61b0df | 1060 | |
1061 | // Genesis block | |
1062 | if (pindexLast == NULL) | |
c52296a7 | 1063 | return nProofOfWorkLimit; |
0a61b0df | 1064 | |
1065 | // Only change once per interval | |
1066 | if ((pindexLast->nHeight+1) % nInterval != 0) | |
c52296a7 | 1067 | { |
248bceb3 GA |
1068 | // Special difficulty rule for testnet: |
1069 | if (fTestNet) | |
c52296a7 GA |
1070 | { |
1071 | // If the new block's timestamp is more than 2* 10 minutes | |
1072 | // then allow mining of a min-difficulty block. | |
248bceb3 | 1073 | if (pblock->nTime > pindexLast->nTime + nTargetSpacing*2) |
c52296a7 GA |
1074 | return nProofOfWorkLimit; |
1075 | else | |
1076 | { | |
1077 | // Return the last non-special-min-difficulty-rules-block | |
1078 | const CBlockIndex* pindex = pindexLast; | |
1079 | while (pindex->pprev && pindex->nHeight % nInterval != 0 && pindex->nBits == nProofOfWorkLimit) | |
1080 | pindex = pindex->pprev; | |
1081 | return pindex->nBits; | |
1082 | } | |
1083 | } | |
1084 | ||
0a61b0df | 1085 | return pindexLast->nBits; |
c52296a7 | 1086 | } |
0a61b0df | 1087 | |
1088 | // Go back by what we want to be 14 days worth of blocks | |
1089 | const CBlockIndex* pindexFirst = pindexLast; | |
1090 | for (int i = 0; pindexFirst && i < nInterval-1; i++) | |
1091 | pindexFirst = pindexFirst->pprev; | |
1092 | assert(pindexFirst); | |
1093 | ||
1094 | // Limit adjustment step | |
bde280b9 | 1095 | int64 nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime(); |
0a61b0df | 1096 | printf(" nActualTimespan = %"PRI64d" before bounds\n", nActualTimespan); |
1097 | if (nActualTimespan < nTargetTimespan/4) | |
1098 | nActualTimespan = nTargetTimespan/4; | |
1099 | if (nActualTimespan > nTargetTimespan*4) | |
1100 | nActualTimespan = nTargetTimespan*4; | |
1101 | ||
1102 | // Retarget | |
1103 | CBigNum bnNew; | |
1104 | bnNew.SetCompact(pindexLast->nBits); | |
1105 | bnNew *= nActualTimespan; | |
1106 | bnNew /= nTargetTimespan; | |
1107 | ||
1108 | if (bnNew > bnProofOfWorkLimit) | |
1109 | bnNew = bnProofOfWorkLimit; | |
1110 | ||
1111 | /// debug print | |
1112 | printf("GetNextWorkRequired RETARGET\n"); | |
1113 | printf("nTargetTimespan = %"PRI64d" nActualTimespan = %"PRI64d"\n", nTargetTimespan, nActualTimespan); | |
1114 | printf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str()); | |
1115 | printf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str()); | |
1116 | ||
1117 | return bnNew.GetCompact(); | |
1118 | } | |
1119 | ||
1120 | bool CheckProofOfWork(uint256 hash, unsigned int nBits) | |
1121 | { | |
1122 | CBigNum bnTarget; | |
1123 | bnTarget.SetCompact(nBits); | |
1124 | ||
1125 | // Check range | |
1126 | if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit) | |
1127 | return error("CheckProofOfWork() : nBits below minimum work"); | |
1128 | ||
1129 | // Check proof of work matches claimed amount | |
1130 | if (hash > bnTarget.getuint256()) | |
1131 | return error("CheckProofOfWork() : hash doesn't match nBits"); | |
1132 | ||
1133 | return true; | |
1134 | } | |
1135 | ||
c5aa1b13 | 1136 | // Return maximum amount of blocks that other nodes claim to have |
d33cc2b5 | 1137 | int GetNumBlocksOfPeers() |
c5aa1b13 | 1138 | { |
eb5fff9e | 1139 | return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate()); |
c5aa1b13 WL |
1140 | } |
1141 | ||
0a61b0df | 1142 | bool IsInitialBlockDownload() |
1143 | { | |
7fea4846 | 1144 | if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate() || fReindex || fImporting) |
0a61b0df | 1145 | return true; |
bde280b9 | 1146 | static int64 nLastUpdate; |
0a61b0df | 1147 | static CBlockIndex* pindexLastBest; |
1148 | if (pindexBest != pindexLastBest) | |
1149 | { | |
1150 | pindexLastBest = pindexBest; | |
1151 | nLastUpdate = GetTime(); | |
1152 | } | |
1153 | return (GetTime() - nLastUpdate < 10 && | |
1154 | pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60); | |
1155 | } | |
1156 | ||
64c7ee7e | 1157 | void static InvalidChainFound(CBlockIndex* pindexNew) |
0a61b0df | 1158 | { |
1159 | if (pindexNew->bnChainWork > bnBestInvalidWork) | |
1160 | { | |
1161 | bnBestInvalidWork = pindexNew->bnChainWork; | |
d979e6e3 | 1162 | pblocktree->WriteBestInvalidWork(bnBestInvalidWork); |
ab1b288f | 1163 | uiInterface.NotifyBlocksChanged(); |
0a61b0df | 1164 | } |
e69a7979 | 1165 | printf("InvalidChainFound: invalid block=%s height=%d work=%s date=%s\n", |
f3a84c3a | 1166 | BlockHashStr(pindexNew->GetBlockHash()).c_str(), pindexNew->nHeight, |
e69a7979 B |
1167 | pindexNew->bnChainWork.ToString().c_str(), DateTimeStrFormat("%x %H:%M:%S", |
1168 | pindexNew->GetBlockTime()).c_str()); | |
1169 | printf("InvalidChainFound: current best=%s height=%d work=%s date=%s\n", | |
f3a84c3a | 1170 | BlockHashStr(hashBestChain).c_str(), nBestHeight, bnBestChainWork.ToString().c_str(), |
e69a7979 | 1171 | DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str()); |
0a61b0df | 1172 | if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6) |
e6bc9c35 | 1173 | printf("InvalidChainFound: Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.\n"); |
0a61b0df | 1174 | } |
1175 | ||
857c61df PW |
1176 | void static InvalidBlockFound(CBlockIndex *pindex) { |
1177 | pindex->nStatus |= BLOCK_FAILED_VALID; | |
d979e6e3 | 1178 | pblocktree->WriteBlockIndex(CDiskBlockIndex(pindex)); |
857c61df PW |
1179 | setBlockIndexValid.erase(pindex); |
1180 | InvalidChainFound(pindex); | |
1181 | if (pindex->pnext) | |
1182 | ConnectBestBlock(); // reorganise away from the failed block | |
1183 | } | |
1184 | ||
1185 | bool ConnectBestBlock() { | |
1186 | do { | |
1187 | CBlockIndex *pindexNewBest; | |
1188 | ||
1189 | { | |
1190 | std::set<CBlockIndex*,CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexValid.rbegin(); | |
1191 | if (it == setBlockIndexValid.rend()) | |
1192 | return true; | |
1193 | pindexNewBest = *it; | |
1194 | } | |
1195 | ||
cd6dc96c | 1196 | if (pindexNewBest == pindexBest || (pindexBest && pindexNewBest->bnChainWork == pindexBest->bnChainWork)) |
857c61df PW |
1197 | return true; // nothing to do |
1198 | ||
1199 | // check ancestry | |
1200 | CBlockIndex *pindexTest = pindexNewBest; | |
1201 | std::vector<CBlockIndex*> vAttach; | |
1202 | do { | |
1203 | if (pindexTest->nStatus & BLOCK_FAILED_MASK) { | |
1204 | // mark descendants failed | |
857c61df PW |
1205 | CBlockIndex *pindexFailed = pindexNewBest; |
1206 | while (pindexTest != pindexFailed) { | |
1207 | pindexFailed->nStatus |= BLOCK_FAILED_CHILD; | |
1208 | setBlockIndexValid.erase(pindexFailed); | |
d979e6e3 | 1209 | pblocktree->WriteBlockIndex(CDiskBlockIndex(pindexFailed)); |
857c61df PW |
1210 | pindexFailed = pindexFailed->pprev; |
1211 | } | |
1212 | InvalidChainFound(pindexNewBest); | |
1213 | break; | |
1214 | } | |
1215 | ||
1216 | if (pindexBest == NULL || pindexTest->bnChainWork > pindexBest->bnChainWork) | |
1217 | vAttach.push_back(pindexTest); | |
1218 | ||
1219 | if (pindexTest->pprev == NULL || pindexTest->pnext != NULL) { | |
1220 | reverse(vAttach.begin(), vAttach.end()); | |
1221 | BOOST_FOREACH(CBlockIndex *pindexSwitch, vAttach) | |
1222 | if (!SetBestChain(pindexSwitch)) | |
1223 | return false; | |
1224 | return true; | |
1225 | } | |
1226 | pindexTest = pindexTest->pprev; | |
1227 | } while(true); | |
1228 | } while(true); | |
1229 | } | |
1230 | ||
e754cf41 | 1231 | void CBlockHeader::UpdateTime(const CBlockIndex* pindexPrev) |
0f8cb5db GA |
1232 | { |
1233 | nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime()); | |
1234 | ||
1235 | // Updating time can change work required on testnet: | |
1236 | if (fTestNet) | |
1237 | nBits = GetNextWorkRequired(pindexPrev, this); | |
1238 | } | |
1239 | ||
0a61b0df | 1240 | |
1241 | ||
1242 | ||
1243 | ||
1244 | ||
1245 | ||
1246 | ||
1247 | ||
1248 | ||
1249 | ||
13c51f20 | 1250 | const CTxOut &CTransaction::GetOutputFor(const CTxIn& input, CCoinsViewCache& view) |
e679ec96 | 1251 | { |
13c51f20 PW |
1252 | const CCoins &coins = view.GetCoins(input.prevout.hash); |
1253 | assert(coins.IsAvailable(input.prevout.n)); | |
1254 | return coins.vout[input.prevout.n]; | |
8d7849b6 GA |
1255 | } |
1256 | ||
13c51f20 | 1257 | int64 CTransaction::GetValueIn(CCoinsViewCache& inputs) const |
8d7849b6 GA |
1258 | { |
1259 | if (IsCoinBase()) | |
1260 | return 0; | |
1261 | ||
1262 | int64 nResult = 0; | |
c376ac35 | 1263 | for (unsigned int i = 0; i < vin.size(); i++) |
8d7849b6 | 1264 | nResult += GetOutputFor(vin[i], inputs).nValue; |
8d7849b6 | 1265 | |
450cbb09 | 1266 | return nResult; |
8d7849b6 GA |
1267 | } |
1268 | ||
13c51f20 | 1269 | unsigned int CTransaction::GetP2SHSigOpCount(CCoinsViewCache& inputs) const |
8d7849b6 GA |
1270 | { |
1271 | if (IsCoinBase()) | |
1272 | return 0; | |
1273 | ||
7bd9c3a3 | 1274 | unsigned int nSigOps = 0; |
c376ac35 | 1275 | for (unsigned int i = 0; i < vin.size(); i++) |
8d7849b6 | 1276 | { |
13c51f20 | 1277 | const CTxOut &prevout = GetOutputFor(vin[i], inputs); |
137d0685 GA |
1278 | if (prevout.scriptPubKey.IsPayToScriptHash()) |
1279 | nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig); | |
8d7849b6 GA |
1280 | } |
1281 | return nSigOps; | |
1282 | } | |
1283 | ||
13c51f20 | 1284 | bool CTransaction::UpdateCoins(CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight, const uint256 &txhash) const |
450cbb09 | 1285 | { |
450cbb09 PW |
1286 | // mark inputs spent |
1287 | if (!IsCoinBase()) { | |
1288 | BOOST_FOREACH(const CTxIn &txin, vin) { | |
13c51f20 | 1289 | CCoins &coins = inputs.GetCoins(txin.prevout.hash); |
450cbb09 PW |
1290 | CTxInUndo undo; |
1291 | if (!coins.Spend(txin.prevout, undo)) | |
1292 | return error("UpdateCoins() : cannot spend input"); | |
1293 | txundo.vprevout.push_back(undo); | |
450cbb09 PW |
1294 | } |
1295 | } | |
1296 | ||
1297 | // add outputs | |
64dd46fd | 1298 | if (!inputs.SetCoins(txhash, CCoins(*this, nHeight))) |
450cbb09 PW |
1299 | return error("UpdateCoins() : cannot update output"); |
1300 | ||
1301 | return true; | |
1302 | } | |
1303 | ||
13c51f20 | 1304 | bool CTransaction::HaveInputs(CCoinsViewCache &inputs) const |
450cbb09 | 1305 | { |
729b1806 | 1306 | if (!IsCoinBase()) { |
450cbb09 PW |
1307 | // first check whether information about the prevout hash is available |
1308 | for (unsigned int i = 0; i < vin.size(); i++) { | |
1309 | const COutPoint &prevout = vin[i].prevout; | |
1310 | if (!inputs.HaveCoins(prevout.hash)) | |
1311 | return false; | |
1312 | } | |
1313 | ||
1314 | // then check whether the actual outputs are available | |
1315 | for (unsigned int i = 0; i < vin.size(); i++) { | |
1316 | const COutPoint &prevout = vin[i].prevout; | |
13c51f20 | 1317 | const CCoins &coins = inputs.GetCoins(prevout.hash); |
450cbb09 PW |
1318 | if (!coins.IsAvailable(prevout.n)) |
1319 | return false; | |
1320 | } | |
1321 | } | |
1322 | return true; | |
1323 | } | |
1324 | ||
99d0d0f3 | 1325 | bool CTransaction::CheckInputs(CCoinsViewCache &inputs, enum CheckSig_mode csmode, unsigned int flags) const |
0a61b0df | 1326 | { |
0a61b0df | 1327 | if (!IsCoinBase()) |
1328 | { | |
13c51f20 PW |
1329 | // This doesn't trigger the DoS code on purpose; if it did, it would make it easier |
1330 | // for an attacker to attempt to split the network. | |
1331 | if (!HaveInputs(inputs)) | |
1332 | return error("CheckInputs() : %s inputs unavailable", GetHash().ToString().substr(0,10).c_str()); | |
1333 | ||
56424040 PW |
1334 | // While checking, GetBestBlock() refers to the parent block. |
1335 | // This is also true for mempool checks. | |
13e5cce4 | 1336 | int nSpendHeight = inputs.GetBestBlock()->nHeight + 1; |
bde280b9 | 1337 | int64 nValueIn = 0; |
8d7849b6 | 1338 | int64 nFees = 0; |
c376ac35 | 1339 | for (unsigned int i = 0; i < vin.size(); i++) |
0a61b0df | 1340 | { |
450cbb09 | 1341 | const COutPoint &prevout = vin[i].prevout; |
13c51f20 | 1342 | const CCoins &coins = inputs.GetCoins(prevout.hash); |
0a61b0df | 1343 | |
1344 | // If prev is coinbase, check that it's matured | |
450cbb09 | 1345 | if (coins.IsCoinBase()) { |
56424040 PW |
1346 | if (nSpendHeight - coins.nHeight < COINBASE_MATURITY) |
1347 | return error("CheckInputs() : tried to spend coinbase at depth %d", nSpendHeight - coins.nHeight); | |
450cbb09 | 1348 | } |
0a61b0df | 1349 | |
4add41a2 | 1350 | // Check for negative or overflow input values |
450cbb09 PW |
1351 | nValueIn += coins.vout[prevout.n].nValue; |
1352 | if (!MoneyRange(coins.vout[prevout.n].nValue) || !MoneyRange(nValueIn)) | |
1353 | return DoS(100, error("CheckInputs() : txin values out of range")); | |
4add41a2 GA |
1354 | |
1355 | } | |
450cbb09 PW |
1356 | |
1357 | if (nValueIn < GetValueOut()) | |
1358 | return DoS(100, error("ChecktInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str())); | |
1359 | ||
1360 | // Tally transaction fees | |
1361 | int64 nTxFee = nValueIn - GetValueOut(); | |
1362 | if (nTxFee < 0) | |
1363 | return DoS(100, error("CheckInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str())); | |
1364 | nFees += nTxFee; | |
1365 | if (!MoneyRange(nFees)) | |
1366 | return DoS(100, error("CheckInputs() : nFees out of range")); | |
1367 | ||
4add41a2 GA |
1368 | // The first loop above does all the inexpensive checks. |
1369 | // Only if ALL inputs pass do we perform expensive ECDSA signature checks. | |
1370 | // Helps prevent CPU exhaustion attacks. | |
4add41a2 | 1371 | |
450cbb09 | 1372 | // Skip ECDSA signature verification when connecting blocks |
729b1806 | 1373 | // before the last block chain checkpoint. This is safe because block merkle hashes are |
450cbb09 | 1374 | // still computed and checked, and any change will be caught at the next checkpoint. |
729b1806 | 1375 | if (csmode == CS_ALWAYS || |
450cbb09 PW |
1376 | (csmode == CS_AFTER_CHECKPOINT && inputs.GetBestBlock()->nHeight >= Checkpoints::GetTotalBlocksEstimate())) { |
1377 | for (unsigned int i = 0; i < vin.size(); i++) { | |
1378 | const COutPoint &prevout = vin[i].prevout; | |
13c51f20 | 1379 | const CCoins &coins = inputs.GetCoins(prevout.hash); |
8d7849b6 | 1380 | |
b14bd4df | 1381 | // Verify signature |
99d0d0f3 | 1382 | if (!VerifySignature(coins, *this, i, flags, 0)) |
450cbb09 | 1383 | return DoS(100,error("CheckInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str())); |
2a45a494 | 1384 | } |
0a61b0df | 1385 | } |
0a61b0df | 1386 | } |
1387 | ||
0a61b0df | 1388 | return true; |
1389 | } | |
1390 | ||
1391 | ||
450cbb09 | 1392 | bool CTransaction::ClientCheckInputs() const |
0a61b0df | 1393 | { |
1394 | if (IsCoinBase()) | |
1395 | return false; | |
1396 | ||
1397 | // Take over previous transactions' spent pointers | |
0a61b0df | 1398 | { |
235507ae | 1399 | LOCK(mempool.cs); |
bde280b9 | 1400 | int64 nValueIn = 0; |
c376ac35 | 1401 | for (unsigned int i = 0; i < vin.size(); i++) |
0a61b0df | 1402 | { |
1403 | // Get prev tx from single transactions in memory | |
1404 | COutPoint prevout = vin[i].prevout; | |
ca4c4c53 | 1405 | if (!mempool.exists(prevout.hash)) |
0a61b0df | 1406 | return false; |
ca4c4c53 | 1407 | CTransaction& txPrev = mempool.lookup(prevout.hash); |
0a61b0df | 1408 | |
1409 | if (prevout.n >= txPrev.vout.size()) | |
1410 | return false; | |
1411 | ||
1412 | // Verify signature | |
99d0d0f3 | 1413 | if (!VerifySignature(CCoins(txPrev, -1), *this, i, SCRIPT_VERIFY_P2SH, 0)) |
0a61b0df | 1414 | return error("ConnectInputs() : VerifySignature failed"); |
1415 | ||
235507ae JG |
1416 | ///// this is redundant with the mempool.mapNextTx stuff, |
1417 | ///// not sure which I want to get rid of | |
0a61b0df | 1418 | ///// this has to go away now that posNext is gone |
1419 | // // Check for conflicts | |
1420 | // if (!txPrev.vout[prevout.n].posNext.IsNull()) | |
1421 | // return error("ConnectInputs() : prev tx already used"); | |
1422 | // | |
1423 | // // Flag outpoints as used | |
1424 | // txPrev.vout[prevout.n].posNext = posThisTx; | |
1425 | ||
1426 | nValueIn += txPrev.vout[prevout.n].nValue; | |
f1e1fb4b | 1427 | |
1428 | if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn)) | |
1429 | return error("ClientConnectInputs() : txin values out of range"); | |
0a61b0df | 1430 | } |
1431 | if (GetValueOut() > nValueIn) | |
1432 | return false; | |
1433 | } | |
1434 | ||
1435 | return true; | |
1436 | } | |
1437 | ||
1438 | ||
1439 | ||
1440 | ||
13c51f20 | 1441 | bool CBlock::DisconnectBlock(CBlockIndex *pindex, CCoinsViewCache &view) |
0a61b0df | 1442 | { |
450cbb09 | 1443 | assert(pindex == view.GetBestBlock()); |
0a61b0df | 1444 | |
450cbb09 | 1445 | CBlockUndo blockUndo; |
0a61b0df | 1446 | { |
450cbb09 PW |
1447 | CDiskBlockPos pos = pindex->GetUndoPos(); |
1448 | if (pos.IsNull()) | |
1449 | return error("DisconnectBlock() : no undo data available"); | |
1450 | FILE *file = OpenUndoFile(pos, true); | |
1451 | if (file == NULL) | |
1452 | return error("DisconnectBlock() : undo file not available"); | |
1453 | CAutoFile fileUndo(file, SER_DISK, CLIENT_VERSION); | |
1454 | fileUndo >> blockUndo; | |
0a61b0df | 1455 | } |
1456 | ||
450cbb09 PW |
1457 | assert(blockUndo.vtxundo.size() + 1 == vtx.size()); |
1458 | ||
1459 | // undo transactions in reverse order | |
1460 | for (int i = vtx.size() - 1; i >= 0; i--) { | |
1461 | const CTransaction &tx = vtx[i]; | |
1462 | uint256 hash = tx.GetHash(); | |
1463 | ||
1464 | // check that all outputs are available | |
13c51f20 | 1465 | if (!view.HaveCoins(hash)) |
450cbb09 | 1466 | return error("DisconnectBlock() : outputs still spent? database corrupted"); |
13c51f20 | 1467 | CCoins &outs = view.GetCoins(hash); |
450cbb09 PW |
1468 | |
1469 | CCoins outsBlock = CCoins(tx, pindex->nHeight); | |
1470 | if (outs != outsBlock) | |
1471 | return error("DisconnectBlock() : added transaction mismatch? database corrupted"); | |
1472 | ||
1473 | // remove outputs | |
13c51f20 | 1474 | outs = CCoins(); |
450cbb09 PW |
1475 | |
1476 | // restore inputs | |
1477 | if (i > 0) { // not coinbases | |
1478 | const CTxUndo &txundo = blockUndo.vtxundo[i-1]; | |
1479 | assert(txundo.vprevout.size() == tx.vin.size()); | |
1480 | for (unsigned int j = tx.vin.size(); j-- > 0;) { | |
1481 | const COutPoint &out = tx.vin[j].prevout; | |
1482 | const CTxInUndo &undo = txundo.vprevout[j]; | |
1483 | CCoins coins; | |
1484 | view.GetCoins(out.hash, coins); // this can fail if the prevout was already entirely spent | |
1485 | if (coins.IsPruned()) { | |
1486 | if (undo.nHeight == 0) | |
1487 | return error("DisconnectBlock() : undo data doesn't contain tx metadata? database corrupted"); | |
1488 | coins.fCoinBase = undo.fCoinBase; | |
1489 | coins.nHeight = undo.nHeight; | |
1490 | coins.nVersion = undo.nVersion; | |
1491 | } else { | |
1492 | if (undo.nHeight != 0) | |
1493 | return error("DisconnectBlock() : undo data contains unneeded tx metadata? database corrupted"); | |
1494 | } | |
1495 | if (coins.IsAvailable(out.n)) | |
1496 | return error("DisconnectBlock() : prevout output not spent? database corrupted"); | |
1497 | if (coins.vout.size() < out.n+1) | |
1498 | coins.vout.resize(out.n+1); | |
1499 | coins.vout[out.n] = undo.txout; | |
1500 | if (!view.SetCoins(out.hash, coins)) | |
1501 | return error("DisconnectBlock() : cannot restore coin inputs"); | |
1502 | } | |
1503 | } | |
1504 | } | |
1505 | ||
1506 | // move best block pointer to prevout block | |
1507 | view.SetBestBlock(pindex->pprev); | |
1508 | ||
0a61b0df | 1509 | return true; |
1510 | } | |
1511 | ||
44d40f26 PW |
1512 | void static FlushBlockFile() |
1513 | { | |
1514 | LOCK(cs_LastBlockFile); | |
1515 | ||
1516 | CDiskBlockPos posOld; | |
1517 | posOld.nFile = nLastBlockFile; | |
1518 | posOld.nPos = 0; | |
1519 | ||
1520 | FILE *fileOld = OpenBlockFile(posOld); | |
1521 | FileCommit(fileOld); | |
1522 | fclose(fileOld); | |
1523 | ||
1524 | fileOld = OpenUndoFile(posOld); | |
1525 | FileCommit(fileOld); | |
1526 | fclose(fileOld); | |
1527 | } | |
1528 | ||
d979e6e3 | 1529 | bool FindUndoPos(int nFile, CDiskBlockPos &pos, unsigned int nAddSize); |
5382bcf8 | 1530 | |
13c51f20 | 1531 | bool CBlock::ConnectBlock(CBlockIndex* pindex, CCoinsViewCache &view, bool fJustCheck) |
0a61b0df | 1532 | { |
1533 | // Check it again in case a previous version let a bad block in | |
3cd01fdf | 1534 | if (!CheckBlock(!fJustCheck, !fJustCheck)) |
0a61b0df | 1535 | return false; |
1536 | ||
450cbb09 PW |
1537 | // verify that the view's current state corresponds to the previous block |
1538 | assert(pindex->pprev == view.GetBestBlock()); | |
1539 | ||
a206b0ea PW |
1540 | // Do not allow blocks that contain transactions which 'overwrite' older transactions, |
1541 | // unless those are already completely spent. | |
1542 | // If such overwrites are allowed, coinbases and transactions depending upon those | |
1543 | // can be duplicated to remove the ability to spend the first instance -- even after | |
1544 | // being sent to another address. | |
1545 | // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information. | |
1546 | // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool | |
b49f1398 | 1547 | // already refuses previously-known transaction ids entirely. |
ab91bf39 GM |
1548 | // This rule was originally applied all blocks whose timestamp was after March 15, 2012, 0:00 UTC. |
1549 | // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the | |
1550 | // two in the chain that violate it. This prevents exploiting the issue against nodes in their | |
1551 | // initial block download. | |
faff50d1 GM |
1552 | bool fEnforceBIP30 = (!pindex->phashBlock) || // Enforce on CreateNewBlock invocations which don't have a hash. |
1553 | !((pindex->nHeight==91842 && pindex->GetBlockHash() == uint256("0x00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")) || | |
ab91bf39 | 1554 | (pindex->nHeight==91880 && pindex->GetBlockHash() == uint256("0x00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721"))); |
450cbb09 | 1555 | if (fEnforceBIP30) { |
64dd46fd PW |
1556 | for (unsigned int i=0; i<vtx.size(); i++) { |
1557 | uint256 hash = GetTxHash(i); | |
13c51f20 | 1558 | if (view.HaveCoins(hash) && !view.GetCoins(hash).IsPruned()) |
450cbb09 PW |
1559 | return error("ConnectBlock() : tried to overwrite transaction"); |
1560 | } | |
1561 | } | |
a206b0ea | 1562 | |
e6332751 GM |
1563 | // BIP16 didn't become active until Apr 1 2012 |
1564 | int64 nBIP16SwitchTime = 1333238400; | |
8f188ece | 1565 | bool fStrictPayToScriptHash = (pindex->nTime >= nBIP16SwitchTime); |
137d0685 | 1566 | |
8adf48dc PW |
1567 | CBlockUndo blockundo; |
1568 | ||
bde280b9 | 1569 | int64 nFees = 0; |
7bd9c3a3 | 1570 | unsigned int nSigOps = 0; |
64dd46fd | 1571 | for (unsigned int i=0; i<vtx.size(); i++) |
0a61b0df | 1572 | { |
64dd46fd PW |
1573 | const CTransaction &tx = vtx[i]; |
1574 | ||
137d0685 GA |
1575 | nSigOps += tx.GetLegacySigOpCount(); |
1576 | if (nSigOps > MAX_BLOCK_SIGOPS) | |
1577 | return DoS(100, error("ConnectBlock() : too many sigops")); | |
1578 | ||
8d7849b6 GA |
1579 | if (!tx.IsCoinBase()) |
1580 | { | |
450cbb09 PW |
1581 | if (!tx.HaveInputs(view)) |
1582 | return DoS(100, error("ConnectBlock() : inputs missing/spent")); | |
922e8e29 | 1583 | |
137d0685 GA |
1584 | if (fStrictPayToScriptHash) |
1585 | { | |
1586 | // Add in sigops done by pay-to-script-hash inputs; | |
1587 | // this is to prevent a "rogue miner" from creating | |
1588 | // an incredibly-expensive-to-validate block. | |
450cbb09 | 1589 | nSigOps += tx.GetP2SHSigOpCount(view); |
137d0685 | 1590 | if (nSigOps > MAX_BLOCK_SIGOPS) |
450cbb09 | 1591 | return DoS(100, error("ConnectBlock() : too many sigops")); |
137d0685 | 1592 | } |
922e8e29 | 1593 | |
450cbb09 | 1594 | nFees += tx.GetValueIn(view)-tx.GetValueOut(); |
8adf48dc | 1595 | |
99d0d0f3 | 1596 | if (!tx.CheckInputs(view, CS_AFTER_CHECKPOINT, fStrictPayToScriptHash ? SCRIPT_VERIFY_P2SH : SCRIPT_VERIFY_NONE)) |
40634605 | 1597 | return false; |
8d7849b6 GA |
1598 | } |
1599 | ||
450cbb09 | 1600 | CTxUndo txundo; |
64dd46fd | 1601 | if (!tx.UpdateCoins(view, txundo, pindex->nHeight, GetTxHash(i))) |
450cbb09 PW |
1602 | return error("ConnectBlock() : UpdateInputs failed"); |
1603 | if (!tx.IsCoinBase()) | |
1604 | blockundo.vtxundo.push_back(txundo); | |
0a61b0df | 1605 | } |
e679ec96 | 1606 | |
9e957fb3 | 1607 | if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees)) |
11406c89 | 1608 | return error("ConnectBlock() : coinbase pays too much (actual=%"PRI64d" vs limit=%"PRI64d")", vtx[0].GetValueOut(), GetBlockValue(pindex->nHeight, nFees)); |
9e957fb3 | 1609 | |
3cd01fdf LD |
1610 | if (fJustCheck) |
1611 | return true; | |
1612 | ||
5382bcf8 | 1613 | // Write undo information to disk |
857c61df | 1614 | if (pindex->GetUndoPos().IsNull() || (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) |
5382bcf8 | 1615 | { |
857c61df PW |
1616 | if (pindex->GetUndoPos().IsNull()) { |
1617 | CDiskBlockPos pos; | |
d979e6e3 | 1618 | if (!FindUndoPos(pindex->nFile, pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 8)) |
857c61df PW |
1619 | return error("ConnectBlock() : FindUndoPos failed"); |
1620 | if (!blockundo.WriteToDisk(pos)) | |
1621 | return error("ConnectBlock() : CBlockUndo::WriteToDisk failed"); | |
1622 | ||
1623 | // update nUndoPos in block index | |
1624 | pindex->nUndoPos = pos.nPos; | |
1625 | pindex->nStatus |= BLOCK_HAVE_UNDO; | |
1626 | } | |
1627 | ||
1628 | pindex->nStatus = (pindex->nStatus & ~BLOCK_VALID_MASK) | BLOCK_VALID_SCRIPTS; | |
1629 | ||
450cbb09 | 1630 | CDiskBlockIndex blockindex(pindex); |
d979e6e3 | 1631 | if (!pblocktree->WriteBlockIndex(blockindex)) |
b22c8842 | 1632 | return error("ConnectBlock() : WriteBlockIndex failed"); |
0a61b0df | 1633 | } |
1634 | ||
729b1806 | 1635 | // add this block to the view's block chain |
450cbb09 PW |
1636 | if (!view.SetBestBlock(pindex)) |
1637 | return false; | |
1638 | ||
0a61b0df | 1639 | // Watch for transactions paying to me |
64dd46fd PW |
1640 | for (unsigned int i=0; i<vtx.size(); i++) |
1641 | SyncWithWallets(GetTxHash(i), vtx[i], this, true); | |
0a61b0df | 1642 | |
1643 | return true; | |
1644 | } | |
1645 | ||
857c61df | 1646 | bool SetBestChain(CBlockIndex* pindexNew) |
0a61b0df | 1647 | { |
ae8bfd12 | 1648 | CCoinsViewCache &view = *pcoinsTip; |
450cbb09 PW |
1649 | |
1650 | // special case for attaching the genesis block | |
1651 | // note that no ConnectBlock is called, so its coinbase output is non-spendable | |
1652 | if (pindexGenesisBlock == NULL && pindexNew->GetBlockHash() == hashGenesisBlock) | |
1653 | { | |
ae8bfd12 PW |
1654 | view.SetBestBlock(pindexNew); |
1655 | if (!view.Flush()) | |
1656 | return false; | |
450cbb09 PW |
1657 | pindexGenesisBlock = pindexNew; |
1658 | pindexBest = pindexNew; | |
1659 | hashBestChain = pindexNew->GetBlockHash(); | |
1660 | nBestHeight = pindexBest->nHeight; | |
1661 | bnBestChainWork = pindexNew->bnChainWork; | |
1662 | return true; | |
1663 | } | |
1664 | ||
450cbb09 PW |
1665 | // Find the fork (typically, there is none) |
1666 | CBlockIndex* pfork = view.GetBestBlock(); | |
0a61b0df | 1667 | CBlockIndex* plonger = pindexNew; |
1668 | while (pfork != plonger) | |
1669 | { | |
1670 | while (plonger->nHeight > pfork->nHeight) | |
1671 | if (!(plonger = plonger->pprev)) | |
450cbb09 | 1672 | return error("SetBestChain() : plonger->pprev is null"); |
0a61b0df | 1673 | if (pfork == plonger) |
1674 | break; | |
1675 | if (!(pfork = pfork->pprev)) | |
450cbb09 | 1676 | return error("SetBestChain() : pfork->pprev is null"); |
0a61b0df | 1677 | } |
1678 | ||
450cbb09 | 1679 | // List of what to disconnect (typically nothing) |
0a61b0df | 1680 | vector<CBlockIndex*> vDisconnect; |
450cbb09 | 1681 | for (CBlockIndex* pindex = view.GetBestBlock(); pindex != pfork; pindex = pindex->pprev) |
0a61b0df | 1682 | vDisconnect.push_back(pindex); |
1683 | ||
450cbb09 | 1684 | // List of what to connect (typically only pindexNew) |
0a61b0df | 1685 | vector<CBlockIndex*> vConnect; |
1686 | for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev) | |
1687 | vConnect.push_back(pindex); | |
1688 | reverse(vConnect.begin(), vConnect.end()); | |
1689 | ||
450cbb09 | 1690 | if (vDisconnect.size() > 0) { |
f3a84c3a LD |
1691 | printf("REORGANIZE: Disconnect %"PRIszu" blocks; %s..%s\n", vDisconnect.size(), BlockHashStr(pfork->GetBlockHash()).c_str(), BlockHashStr(pindexBest->GetBlockHash()).c_str()); |
1692 | printf("REORGANIZE: Connect %"PRIszu" blocks; %s..%s\n", vConnect.size(), BlockHashStr(pfork->GetBlockHash()).c_str(), BlockHashStr(pindexNew->GetBlockHash()).c_str()); | |
450cbb09 | 1693 | } |
a1a0469f | 1694 | |
0a61b0df | 1695 | // Disconnect shorter branch |
1696 | vector<CTransaction> vResurrect; | |
450cbb09 | 1697 | BOOST_FOREACH(CBlockIndex* pindex, vDisconnect) { |
0a61b0df | 1698 | CBlock block; |
1699 | if (!block.ReadFromDisk(pindex)) | |
450cbb09 | 1700 | return error("SetBestBlock() : ReadFromDisk for disconnect failed"); |
ae8bfd12 PW |
1701 | CCoinsViewCache viewTemp(view, true); |
1702 | if (!block.DisconnectBlock(pindex, viewTemp)) | |
f3a84c3a | 1703 | return error("SetBestBlock() : DisconnectBlock %s failed", BlockHashStr(pindex->GetBlockHash()).c_str()); |
ae8bfd12 PW |
1704 | if (!viewTemp.Flush()) |
1705 | return error("SetBestBlock() : Cache flush failed after disconnect"); | |
0a61b0df | 1706 | |
1707 | // Queue memory transactions to resurrect | |
223b6f1b | 1708 | BOOST_FOREACH(const CTransaction& tx, block.vtx) |
0a61b0df | 1709 | if (!tx.IsCoinBase()) |
1710 | vResurrect.push_back(tx); | |
1711 | } | |
1712 | ||
1713 | // Connect longer branch | |
1714 | vector<CTransaction> vDelete; | |
450cbb09 | 1715 | BOOST_FOREACH(CBlockIndex *pindex, vConnect) { |
0a61b0df | 1716 | CBlock block; |
857c61df PW |
1717 | if (!block.ReadFromDisk(pindex)) |
1718 | return error("SetBestBlock() : ReadFromDisk for connect failed"); | |
ae8bfd12 | 1719 | CCoinsViewCache viewTemp(view, true); |
857c61df | 1720 | if (!block.ConnectBlock(pindex, viewTemp)) { |
450cbb09 | 1721 | InvalidChainFound(pindexNew); |
857c61df | 1722 | InvalidBlockFound(pindex); |
f3a84c3a | 1723 | return error("SetBestBlock() : ConnectBlock %s failed", BlockHashStr(pindex->GetBlockHash()).c_str()); |
0a61b0df | 1724 | } |
ae8bfd12 PW |
1725 | if (!viewTemp.Flush()) |
1726 | return error("SetBestBlock() : Cache flush failed after connect"); | |
0a61b0df | 1727 | |
1728 | // Queue memory transactions to delete | |
857c61df | 1729 | BOOST_FOREACH(const CTransaction& tx, block.vtx) |
0a61b0df | 1730 | vDelete.push_back(tx); |
1731 | } | |
0a61b0df | 1732 | |
b22c8842 | 1733 | // Make sure it's successfully written to disk before changing memory structure |
ae8bfd12 | 1734 | bool fIsInitialDownload = IsInitialBlockDownload(); |
1c83b0a3 | 1735 | if (!fIsInitialDownload || view.GetCacheSize() > nCoinCacheSize) { |
44d40f26 | 1736 | FlushBlockFile(); |
2d8a4829 | 1737 | pblocktree->Sync(); |
ae8bfd12 PW |
1738 | if (!view.Flush()) |
1739 | return false; | |
44d40f26 | 1740 | } |
450cbb09 PW |
1741 | |
1742 | // At this point, all changes have been done to the database. | |
1743 | // Proceed by updating the memory structures. | |
0a61b0df | 1744 | |
1745 | // Disconnect shorter branch | |
223b6f1b | 1746 | BOOST_FOREACH(CBlockIndex* pindex, vDisconnect) |
0a61b0df | 1747 | if (pindex->pprev) |
1748 | pindex->pprev->pnext = NULL; | |
1749 | ||
1750 | // Connect longer branch | |
223b6f1b | 1751 | BOOST_FOREACH(CBlockIndex* pindex, vConnect) |
0a61b0df | 1752 | if (pindex->pprev) |
1753 | pindex->pprev->pnext = pindex; | |
1754 | ||
1755 | // Resurrect memory transactions that were in the disconnected branch | |
223b6f1b | 1756 | BOOST_FOREACH(CTransaction& tx, vResurrect) |
ae8bfd12 | 1757 | tx.AcceptToMemoryPool(false); |
0a61b0df | 1758 | |
1759 | // Delete redundant memory transactions that are in the connected branch | |
223b6f1b | 1760 | BOOST_FOREACH(CTransaction& tx, vDelete) |
8e45ed66 | 1761 | mempool.remove(tx); |
0a61b0df | 1762 | |
6a76c60e | 1763 | // Update best block in wallet (so we can detect restored wallets) |
d237f62c | 1764 | if (!fIsInitialDownload) |
6a76c60e | 1765 | { |
6a76c60e | 1766 | const CBlockLocator locator(pindexNew); |
64c7ee7e | 1767 | ::SetBestChain(locator); |
6a76c60e PW |
1768 | } |
1769 | ||
0a61b0df | 1770 | // New best block |
450cbb09 | 1771 | hashBestChain = pindexNew->GetBlockHash(); |
0a61b0df | 1772 | pindexBest = pindexNew; |
1be06419 | 1773 | pblockindexFBBHLast = NULL; |
0a61b0df | 1774 | nBestHeight = pindexBest->nHeight; |
1775 | bnBestChainWork = pindexNew->bnChainWork; | |
1776 | nTimeBestReceived = GetTime(); | |
1777 | nTransactionsUpdated++; | |
857c61df | 1778 | printf("SetBestChain: new best=%s height=%d work=%s tx=%lu date=%s\n", |
f3a84c3a | 1779 | BlockHashStr(hashBestChain).c_str(), nBestHeight, bnBestChainWork.ToString().c_str(), (unsigned long)pindexNew->nChainTx, |
e69a7979 | 1780 | DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str()); |
0a61b0df | 1781 | |
2a919e39 GA |
1782 | // Check the version of the last 100 blocks to see if we need to upgrade: |
1783 | if (!fIsInitialDownload) | |
1784 | { | |
1785 | int nUpgraded = 0; | |
1786 | const CBlockIndex* pindex = pindexBest; | |
1787 | for (int i = 0; i < 100 && pindex != NULL; i++) | |
1788 | { | |
1789 | if (pindex->nVersion > CBlock::CURRENT_VERSION) | |
1790 | ++nUpgraded; | |
1791 | pindex = pindex->pprev; | |
1792 | } | |
1793 | if (nUpgraded > 0) | |
1794 | printf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, CBlock::CURRENT_VERSION); | |
1795 | if (nUpgraded > 100/2) | |
1796 | // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user: | |
e6bc9c35 | 1797 | strMiscWarning = _("Warning: This version is obsolete, upgrade required!"); |
2a919e39 GA |
1798 | } |
1799 | ||
d237f62c GA |
1800 | std::string strCmd = GetArg("-blocknotify", ""); |
1801 | ||
1802 | if (!fIsInitialDownload && !strCmd.empty()) | |
1803 | { | |
1804 | boost::replace_all(strCmd, "%s", hashBestChain.GetHex()); | |
1805 | boost::thread t(runCommand, strCmd); // thread runs free | |
1806 | } | |
1807 | ||
0a61b0df | 1808 | return true; |
1809 | } | |
1810 | ||
1811 | ||
630fd8dc | 1812 | bool CBlock::AddToBlockIndex(const CDiskBlockPos &pos) |
0a61b0df | 1813 | { |
1814 | // Check for duplicate | |
1815 | uint256 hash = GetHash(); | |
1816 | if (mapBlockIndex.count(hash)) | |
f3a84c3a | 1817 | return error("AddToBlockIndex() : %s already exists", BlockHashStr(hash).c_str()); |
0a61b0df | 1818 | |
1819 | // Construct new block index object | |
630fd8dc | 1820 | CBlockIndex* pindexNew = new CBlockIndex(*this); |
0a61b0df | 1821 | if (!pindexNew) |
1822 | return error("AddToBlockIndex() : new CBlockIndex failed"); | |
1823 | map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first; | |
1824 | pindexNew->phashBlock = &((*mi).first); | |
1825 | map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock); | |
1826 | if (miPrev != mapBlockIndex.end()) | |
1827 | { | |
1828 | pindexNew->pprev = (*miPrev).second; | |
1829 | pindexNew->nHeight = pindexNew->pprev->nHeight + 1; | |
1830 | } | |
857c61df | 1831 | pindexNew->nTx = vtx.size(); |
0a61b0df | 1832 | pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork(); |
857c61df PW |
1833 | pindexNew->nChainTx = (pindexNew->pprev ? pindexNew->pprev->nChainTx : 0) + pindexNew->nTx; |
1834 | pindexNew->nFile = pos.nFile; | |
1835 | pindexNew->nDataPos = pos.nPos; | |
5382bcf8 | 1836 | pindexNew->nUndoPos = 0; |
857c61df PW |
1837 | pindexNew->nStatus = BLOCK_VALID_TRANSACTIONS | BLOCK_HAVE_DATA; |
1838 | setBlockIndexValid.insert(pindexNew); | |
0a61b0df | 1839 | |
d979e6e3 | 1840 | pblocktree->WriteBlockIndex(CDiskBlockIndex(pindexNew)); |
0a61b0df | 1841 | |
857c61df PW |
1842 | // New best? |
1843 | if (!ConnectBestBlock()) | |
ae8bfd12 | 1844 | return false; |
0a61b0df | 1845 | |
1846 | if (pindexNew == pindexBest) | |
1847 | { | |
1848 | // Notify UI to display prev block's coinbase if it was ours | |
1849 | static uint256 hashPrevBestCoinBase; | |
64c7ee7e | 1850 | UpdatedTransaction(hashPrevBestCoinBase); |
64dd46fd | 1851 | hashPrevBestCoinBase = GetTxHash(0); |
0a61b0df | 1852 | } |
1853 | ||
d979e6e3 PW |
1854 | pblocktree->Flush(); |
1855 | ||
ab1b288f | 1856 | uiInterface.NotifyBlocksChanged(); |
0a61b0df | 1857 | return true; |
1858 | } | |
1859 | ||
1860 | ||
7fea4846 | 1861 | bool FindBlockPos(CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64 nTime, bool fKnown = false) |
5382bcf8 PW |
1862 | { |
1863 | bool fUpdatedLast = false; | |
1864 | ||
1865 | LOCK(cs_LastBlockFile); | |
1866 | ||
7fea4846 PW |
1867 | if (fKnown) { |
1868 | if (nLastBlockFile != pos.nFile) { | |
1869 | nLastBlockFile = pos.nFile; | |
1870 | infoLastBlockFile.SetNull(); | |
1871 | pblocktree->ReadBlockFileInfo(nLastBlockFile, infoLastBlockFile); | |
1872 | } | |
1873 | } else { | |
1874 | while (infoLastBlockFile.nSize + nAddSize >= MAX_BLOCKFILE_SIZE) { | |
1875 | printf("Leaving block file %i: %s\n", nLastBlockFile, infoLastBlockFile.ToString().c_str()); | |
1876 | FlushBlockFile(); | |
1877 | nLastBlockFile++; | |
1878 | infoLastBlockFile.SetNull(); | |
1879 | pblocktree->ReadBlockFileInfo(nLastBlockFile, infoLastBlockFile); // check whether data for the new file somehow already exist; can fail just fine | |
1880 | fUpdatedLast = true; | |
1881 | } | |
1882 | pos.nFile = nLastBlockFile; | |
1883 | pos.nPos = infoLastBlockFile.nSize; | |
5382bcf8 PW |
1884 | } |
1885 | ||
5382bcf8 PW |
1886 | infoLastBlockFile.nSize += nAddSize; |
1887 | infoLastBlockFile.AddBlock(nHeight, nTime); | |
1888 | ||
7fea4846 PW |
1889 | if (!fKnown) { |
1890 | unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE; | |
1891 | unsigned int nNewChunks = (infoLastBlockFile.nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE; | |
1892 | if (nNewChunks > nOldChunks) { | |
1893 | FILE *file = OpenBlockFile(pos); | |
1894 | if (file) { | |
1895 | printf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile); | |
1896 | AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos); | |
13e5cce4 | 1897 | fclose(file); |
7fea4846 | 1898 | } |
bba89aa8 | 1899 | } |
bba89aa8 PW |
1900 | } |
1901 | ||
d979e6e3 | 1902 | if (!pblocktree->WriteBlockFileInfo(nLastBlockFile, infoLastBlockFile)) |
5382bcf8 PW |
1903 | return error("FindBlockPos() : cannot write updated block info"); |
1904 | if (fUpdatedLast) | |
d979e6e3 | 1905 | pblocktree->WriteLastBlockFile(nLastBlockFile); |
5382bcf8 PW |
1906 | |
1907 | return true; | |
1908 | } | |
1909 | ||
d979e6e3 | 1910 | bool FindUndoPos(int nFile, CDiskBlockPos &pos, unsigned int nAddSize) |
5382bcf8 PW |
1911 | { |
1912 | pos.nFile = nFile; | |
1913 | ||
1914 | LOCK(cs_LastBlockFile); | |
1915 | ||
bba89aa8 | 1916 | unsigned int nNewSize; |
5382bcf8 PW |
1917 | if (nFile == nLastBlockFile) { |
1918 | pos.nPos = infoLastBlockFile.nUndoSize; | |
bba89aa8 | 1919 | nNewSize = (infoLastBlockFile.nUndoSize += nAddSize); |
d979e6e3 | 1920 | if (!pblocktree->WriteBlockFileInfo(nLastBlockFile, infoLastBlockFile)) |
5382bcf8 | 1921 | return error("FindUndoPos() : cannot write updated block info"); |
bba89aa8 PW |
1922 | } else { |
1923 | CBlockFileInfo info; | |
d979e6e3 | 1924 | if (!pblocktree->ReadBlockFileInfo(nFile, info)) |
bba89aa8 PW |
1925 | return error("FindUndoPos() : cannot read block info"); |
1926 | pos.nPos = info.nUndoSize; | |
1927 | nNewSize = (info.nUndoSize += nAddSize); | |
d979e6e3 | 1928 | if (!pblocktree->WriteBlockFileInfo(nFile, info)) |
bba89aa8 PW |
1929 | return error("FindUndoPos() : cannot write updated block info"); |
1930 | } | |
1931 | ||
1932 | unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE; | |
1933 | unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE; | |
1934 | if (nNewChunks > nOldChunks) { | |
1935 | FILE *file = OpenUndoFile(pos); | |
1936 | if (file) { | |
1937 | printf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile); | |
1938 | AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos); | |
13e5cce4 | 1939 | fclose(file); |
bba89aa8 | 1940 | } |
5382bcf8 PW |
1941 | } |
1942 | ||
5382bcf8 PW |
1943 | return true; |
1944 | } | |
1945 | ||
0a61b0df | 1946 | |
3cd01fdf | 1947 | bool CBlock::CheckBlock(bool fCheckPOW, bool fCheckMerkleRoot) const |
0a61b0df | 1948 | { |
1949 | // These are checks that are independent of context | |
1950 | // that can be verified before saving an orphan block. | |
1951 | ||
1952 | // Size limits | |
6b6aaa16 | 1953 | if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE) |
3e52aaf2 | 1954 | return DoS(100, error("CheckBlock() : size limits failed")); |
0a61b0df | 1955 | |
172f0060 | 1956 | // Check proof of work matches claimed amount |
3cd01fdf | 1957 | if (fCheckPOW && !CheckProofOfWork(GetHash(), nBits)) |
3e52aaf2 | 1958 | return DoS(50, error("CheckBlock() : proof of work failed")); |
172f0060 | 1959 | |
0a61b0df | 1960 | // Check timestamp |
1961 | if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60) | |
1962 | return error("CheckBlock() : block timestamp too far in the future"); | |
1963 | ||
1964 | // First transaction must be coinbase, the rest must not be | |
1965 | if (vtx.empty() || !vtx[0].IsCoinBase()) | |
3e52aaf2 | 1966 | return DoS(100, error("CheckBlock() : first tx is not coinbase")); |
c376ac35 | 1967 | for (unsigned int i = 1; i < vtx.size(); i++) |
0a61b0df | 1968 | if (vtx[i].IsCoinBase()) |
3e52aaf2 | 1969 | return DoS(100, error("CheckBlock() : more than one coinbase")); |
0a61b0df | 1970 | |
1971 | // Check transactions | |
223b6f1b | 1972 | BOOST_FOREACH(const CTransaction& tx, vtx) |
0a61b0df | 1973 | if (!tx.CheckTransaction()) |
3e52aaf2 | 1974 | return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed")); |
0a61b0df | 1975 | |
c2ed184f PW |
1976 | // Build the merkle tree already. We need it anyway later, and it makes the |
1977 | // block cache the transaction hashes, which means they don't need to be | |
1978 | // recalculated many times during this block's validation. | |
1979 | BuildMerkleTree(); | |
1980 | ||
be8651dd GA |
1981 | // Check for duplicate txids. This is caught by ConnectInputs(), |
1982 | // but catching it earlier avoids a potential DoS attack: | |
1983 | set<uint256> uniqueTx; | |
64dd46fd PW |
1984 | for (unsigned int i=0; i<vtx.size(); i++) { |
1985 | uniqueTx.insert(GetTxHash(i)); | |
be8651dd GA |
1986 | } |
1987 | if (uniqueTx.size() != vtx.size()) | |
1988 | return DoS(100, error("CheckBlock() : duplicate transaction")); | |
1989 | ||
7bd9c3a3 | 1990 | unsigned int nSigOps = 0; |
e679ec96 GA |
1991 | BOOST_FOREACH(const CTransaction& tx, vtx) |
1992 | { | |
922e8e29 | 1993 | nSigOps += tx.GetLegacySigOpCount(); |
e679ec96 GA |
1994 | } |
1995 | if (nSigOps > MAX_BLOCK_SIGOPS) | |
3e52aaf2 | 1996 | return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount")); |
0a61b0df | 1997 | |
814efd6f | 1998 | // Check merkle root |
3cd01fdf | 1999 | if (fCheckMerkleRoot && hashMerkleRoot != BuildMerkleTree()) |
3e52aaf2 | 2000 | return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch")); |
0a61b0df | 2001 | |
2002 | return true; | |
2003 | } | |
2004 | ||
7fea4846 | 2005 | bool CBlock::AcceptBlock(CDiskBlockPos *dbp) |
0a61b0df | 2006 | { |
2007 | // Check for duplicate | |
2008 | uint256 hash = GetHash(); | |
2009 | if (mapBlockIndex.count(hash)) | |
2010 | return error("AcceptBlock() : block already in mapBlockIndex"); | |
2011 | ||
2012 | // Get prev block index | |
7fea4846 PW |
2013 | CBlockIndex* pindexPrev = NULL; |
2014 | int nHeight = 0; | |
2015 | if (hash != hashGenesisBlock) { | |
b56585d0 PK |
2016 | map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock); |
2017 | if (mi == mapBlockIndex.end()) | |
2018 | return DoS(10, error("AcceptBlock() : prev block not found")); | |
2019 | pindexPrev = (*mi).second; | |
2020 | nHeight = pindexPrev->nHeight+1; | |
2021 | ||
2022 | // Check proof of work | |
2023 | if (nBits != GetNextWorkRequired(pindexPrev, this)) | |
2024 | return DoS(100, error("AcceptBlock() : incorrect proof of work")); | |
2025 | ||
2026 | // Check timestamp against prev | |
2027 | if (GetBlockTime() <= pindexPrev->GetMedianTimePast()) | |
2028 | return error("AcceptBlock() : block's timestamp is too early"); | |
2029 | ||
2030 | // Check that all transactions are finalized | |
2031 | BOOST_FOREACH(const CTransaction& tx, vtx) | |
2032 | if (!tx.IsFinal(nHeight, GetBlockTime())) | |
2033 | return DoS(10, error("AcceptBlock() : contains a non-final transaction")); | |
2034 | ||
2035 | // Check that the block chain matches the known block chain up to a checkpoint | |
2036 | if (!Checkpoints::CheckBlock(nHeight, hash)) | |
2037 | return DoS(100, error("AcceptBlock() : rejected by checkpoint lock-in at %d", nHeight)); | |
2038 | ||
2039 | // Reject block.nVersion=1 blocks when 95% (75% on testnet) of the network has upgraded: | |
2040 | if (nVersion < 2) | |
d18f2fd9 | 2041 | { |
b56585d0 PK |
2042 | if ((!fTestNet && CBlockIndex::IsSuperMajority(2, pindexPrev, 950, 1000)) || |
2043 | (fTestNet && CBlockIndex::IsSuperMajority(2, pindexPrev, 75, 100))) | |
2044 | { | |
2045 | return error("AcceptBlock() : rejected nVersion=1 block"); | |
2046 | } | |
d18f2fd9 | 2047 | } |
b56585d0 PK |
2048 | // Enforce block.nVersion=2 rule that the coinbase starts with serialized block height |
2049 | if (nVersion >= 2) | |
de237cbf | 2050 | { |
b56585d0 PK |
2051 | // if 750 of the last 1,000 blocks are version 2 or greater (51/100 if testnet): |
2052 | if ((!fTestNet && CBlockIndex::IsSuperMajority(2, pindexPrev, 750, 1000)) || | |
2053 | (fTestNet && CBlockIndex::IsSuperMajority(2, pindexPrev, 51, 100))) | |
2054 | { | |
2055 | CScript expect = CScript() << nHeight; | |
2056 | if (!std::equal(expect.begin(), expect.end(), vtx[0].vin[0].scriptSig.begin())) | |
2057 | return DoS(100, error("AcceptBlock() : block height mismatch in coinbase")); | |
2058 | } | |
de237cbf GA |
2059 | } |
2060 | } | |
2061 | ||
0a61b0df | 2062 | // Write block to history file |
5382bcf8 | 2063 | unsigned int nBlockSize = ::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION); |
5382bcf8 | 2064 | CDiskBlockPos blockPos; |
7fea4846 PW |
2065 | if (dbp == NULL) { |
2066 | if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION))) | |
2067 | return error("AcceptBlock() : out of disk space"); | |
2068 | } else { | |
2069 | blockPos = *dbp; | |
2070 | } | |
2071 | if (!FindBlockPos(blockPos, nBlockSize+8, nHeight, nTime, dbp != NULL)) | |
d979e6e3 | 2072 | return error("AcceptBlock() : FindBlockPos failed"); |
7fea4846 PW |
2073 | if (dbp == NULL) |
2074 | if (!WriteToDisk(blockPos)) | |
2075 | return error("AcceptBlock() : WriteToDisk failed"); | |
630fd8dc | 2076 | if (!AddToBlockIndex(blockPos)) |
0a61b0df | 2077 | return error("AcceptBlock() : AddToBlockIndex failed"); |
2078 | ||
2079 | // Relay inventory, but don't relay old inventory during initial block download | |
eae82d8e | 2080 | int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate(); |
0a61b0df | 2081 | if (hashBestChain == hash) |
f8dcd5ca PW |
2082 | { |
2083 | LOCK(cs_vNodes); | |
2084 | BOOST_FOREACH(CNode* pnode, vNodes) | |
2085 | if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate)) | |
2086 | pnode->PushInventory(CInv(MSG_BLOCK, hash)); | |
2087 | } | |
0a61b0df | 2088 | |
2089 | return true; | |
2090 | } | |
2091 | ||
de237cbf GA |
2092 | bool CBlockIndex::IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired, unsigned int nToCheck) |
2093 | { | |
2094 | unsigned int nFound = 0; | |
2095 | for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++) | |
2096 | { | |
2097 | if (pstart->nVersion >= minVersion) | |
2098 | ++nFound; | |
2099 | pstart = pstart->pprev; | |
2100 | } | |
2101 | return (nFound >= nRequired); | |
2102 | } | |
2103 | ||
7fea4846 | 2104 | bool ProcessBlock(CNode* pfrom, CBlock* pblock, CDiskBlockPos *dbp) |
0a61b0df | 2105 | { |
2106 | // Check for duplicate | |
2107 | uint256 hash = pblock->GetHash(); | |
2108 | if (mapBlockIndex.count(hash)) | |
f3a84c3a | 2109 | return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, BlockHashStr(hash).c_str()); |
0a61b0df | 2110 | if (mapOrphanBlocks.count(hash)) |
f3a84c3a | 2111 | return error("ProcessBlock() : already have block (orphan) %s", BlockHashStr(hash).c_str()); |
0a61b0df | 2112 | |
2113 | // Preliminary checks | |
2114 | if (!pblock->CheckBlock()) | |
0a61b0df | 2115 | return error("ProcessBlock() : CheckBlock FAILED"); |
0a61b0df | 2116 | |
10fd7f66 GA |
2117 | CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(mapBlockIndex); |
2118 | if (pcheckpoint && pblock->hashPrevBlock != hashBestChain) | |
2119 | { | |
2120 | // Extra checks to prevent "fill up memory by spamming with bogus blocks" | |
bde280b9 | 2121 | int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime; |
10fd7f66 GA |
2122 | if (deltaTime < 0) |
2123 | { | |
73aa0421 PW |
2124 | if (pfrom) |
2125 | pfrom->Misbehaving(100); | |
10fd7f66 GA |
2126 | return error("ProcessBlock() : block with timestamp before last checkpoint"); |
2127 | } | |
2128 | CBigNum bnNewBlock; | |
2129 | bnNewBlock.SetCompact(pblock->nBits); | |
2130 | CBigNum bnRequired; | |
2131 | bnRequired.SetCompact(ComputeMinWork(pcheckpoint->nBits, deltaTime)); | |
2132 | if (bnNewBlock > bnRequired) | |
2133 | { | |
73aa0421 PW |
2134 | if (pfrom) |
2135 | pfrom->Misbehaving(100); | |
10fd7f66 GA |
2136 | return error("ProcessBlock() : block with too little proof-of-work"); |
2137 | } | |
2138 | } | |
2139 | ||
2140 | ||
5c88e3c1 | 2141 | // If we don't already have its previous block, shunt it off to holding area until we get it |
7fea4846 | 2142 | if (pblock->hashPrevBlock != 0 && !mapBlockIndex.count(pblock->hashPrevBlock)) |
0a61b0df | 2143 | { |
f3a84c3a | 2144 | printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", BlockHashStr(pblock->hashPrevBlock).c_str()); |
0a61b0df | 2145 | |
5c88e3c1 PW |
2146 | // Accept orphans as long as there is a node to request its parents from |
2147 | if (pfrom) { | |
2148 | CBlock* pblock2 = new CBlock(*pblock); | |
2149 | mapOrphanBlocks.insert(make_pair(hash, pblock2)); | |
2150 | mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2)); | |
2151 | ||
2152 | // Ask this guy to fill in what we're missing | |
776d0f34 | 2153 | pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2)); |
5c88e3c1 | 2154 | } |
0a61b0df | 2155 | return true; |
2156 | } | |
2157 | ||
2158 | // Store to disk | |
7fea4846 | 2159 | if (!pblock->AcceptBlock(dbp)) |
0a61b0df | 2160 | return error("ProcessBlock() : AcceptBlock FAILED"); |
0a61b0df | 2161 | |
2162 | // Recursively process any orphan blocks that depended on this one | |
2163 | vector<uint256> vWorkQueue; | |
2164 | vWorkQueue.push_back(hash); | |
c376ac35 | 2165 | for (unsigned int i = 0; i < vWorkQueue.size(); i++) |
0a61b0df | 2166 | { |
2167 | uint256 hashPrev = vWorkQueue[i]; | |
2168 | for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev); | |
2169 | mi != mapOrphanBlocksByPrev.upper_bound(hashPrev); | |
2170 | ++mi) | |
2171 | { | |
2172 | CBlock* pblockOrphan = (*mi).second; | |
2173 | if (pblockOrphan->AcceptBlock()) | |
2174 | vWorkQueue.push_back(pblockOrphan->GetHash()); | |
2175 | mapOrphanBlocks.erase(pblockOrphan->GetHash()); | |
2176 | delete pblockOrphan; | |
2177 | } | |
2178 | mapOrphanBlocksByPrev.erase(hashPrev); | |
2179 | } | |
2180 | ||
2181 | printf("ProcessBlock: ACCEPTED\n"); | |
2182 | return true; | |
2183 | } | |
2184 | ||
2185 | ||
2186 | ||
2187 | ||
2188 | ||
2189 | ||
2190 | ||
2191 | ||
bde280b9 | 2192 | bool CheckDiskSpace(uint64 nAdditionalBytes) |
0a61b0df | 2193 | { |
bde280b9 | 2194 | uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available; |
0a61b0df | 2195 | |
966ae00f PK |
2196 | // Check for nMinDiskSpace bytes (currently 50MB) |
2197 | if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes) | |
0a61b0df | 2198 | { |
2199 | fShutdown = true; | |
e6bc9c35 | 2200 | string strMessage = _("Warning: Disk space is low!"); |
0a61b0df | 2201 | strMiscWarning = strMessage; |
2202 | printf("*** %s\n", strMessage.c_str()); | |
239c11d0 | 2203 | uiInterface.ThreadSafeMessageBox(strMessage, "Bitcoin", CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL); |
9247134e | 2204 | StartShutdown(); |
0a61b0df | 2205 | return false; |
2206 | } | |
2207 | return true; | |
2208 | } | |
2209 | ||
5382bcf8 PW |
2210 | CCriticalSection cs_LastBlockFile; |
2211 | CBlockFileInfo infoLastBlockFile; | |
2212 | int nLastBlockFile = 0; | |
2213 | ||
2214 | FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly) | |
42613c97 | 2215 | { |
450cbb09 | 2216 | if (pos.IsNull()) |
0a61b0df | 2217 | return NULL; |
5382bcf8 PW |
2218 | boost::filesystem::path path = GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile); |
2219 | boost::filesystem::create_directories(path.parent_path()); | |
2220 | FILE* file = fopen(path.string().c_str(), "rb+"); | |
2221 | if (!file && !fReadOnly) | |
2222 | file = fopen(path.string().c_str(), "wb+"); | |
450cbb09 PW |
2223 | if (!file) { |
2224 | printf("Unable to open file %s\n", path.string().c_str()); | |
0a61b0df | 2225 | return NULL; |
450cbb09 | 2226 | } |
5382bcf8 PW |
2227 | if (pos.nPos) { |
2228 | if (fseek(file, pos.nPos, SEEK_SET)) { | |
2229 | printf("Unable to seek to position %u of %s\n", pos.nPos, path.string().c_str()); | |
2230 | fclose(file); | |
2231 | return NULL; | |
2232 | } | |
2233 | } | |
0a61b0df | 2234 | return file; |
2235 | } | |
2236 | ||
5382bcf8 PW |
2237 | FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) { |
2238 | return OpenDiskFile(pos, "blk", fReadOnly); | |
2239 | } | |
2240 | ||
2241 | FILE *OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) { | |
2242 | return OpenDiskFile(pos, "rev", fReadOnly); | |
2243 | } | |
2244 | ||
2d8a4829 PW |
2245 | CBlockIndex * InsertBlockIndex(uint256 hash) |
2246 | { | |
2247 | if (hash == 0) | |
2248 | return NULL; | |
2249 | ||
2250 | // Return existing | |
2251 | map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash); | |
2252 | if (mi != mapBlockIndex.end()) | |
2253 | return (*mi).second; | |
2254 | ||
2255 | // Create new | |
2256 | CBlockIndex* pindexNew = new CBlockIndex(); | |
2257 | if (!pindexNew) | |
2258 | throw runtime_error("LoadBlockIndex() : new CBlockIndex failed"); | |
2259 | mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first; | |
2260 | pindexNew->phashBlock = &((*mi).first); | |
2261 | ||
2262 | return pindexNew; | |
2263 | } | |
2264 | ||
2265 | bool static LoadBlockIndexDB() | |
2266 | { | |
2267 | if (!pblocktree->LoadBlockIndexGuts()) | |
2268 | return false; | |
2269 | ||
2270 | if (fRequestShutdown) | |
2271 | return true; | |
2272 | ||
2273 | // Calculate bnChainWork | |
2274 | vector<pair<int, CBlockIndex*> > vSortedByHeight; | |
2275 | vSortedByHeight.reserve(mapBlockIndex.size()); | |
2276 | BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex) | |
2277 | { | |
2278 | CBlockIndex* pindex = item.second; | |
2279 | vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex)); | |
2280 | } | |
2281 | sort(vSortedByHeight.begin(), vSortedByHeight.end()); | |
2282 | BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight) | |
2283 | { | |
2284 | CBlockIndex* pindex = item.second; | |
2285 | pindex->bnChainWork = (pindex->pprev ? pindex->pprev->bnChainWork : 0) + pindex->GetBlockWork(); | |
2286 | pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx; | |
2287 | if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS && !(pindex->nStatus & BLOCK_FAILED_MASK)) | |
2288 | setBlockIndexValid.insert(pindex); | |
2289 | } | |
2290 | ||
2291 | // Load block file info | |
2292 | pblocktree->ReadLastBlockFile(nLastBlockFile); | |
2293 | printf("LoadBlockIndex(): last block file = %i\n", nLastBlockFile); | |
2294 | if (pblocktree->ReadBlockFileInfo(nLastBlockFile, infoLastBlockFile)) | |
2295 | printf("LoadBlockIndex(): last block file: %s\n", infoLastBlockFile.ToString().c_str()); | |
729b1806 | 2296 | |
2d8a4829 PW |
2297 | // Load hashBestChain pointer to end of best chain |
2298 | pindexBest = pcoinsTip->GetBestBlock(); | |
2299 | if (pindexBest == NULL) | |
2300 | { | |
2301 | if (pindexGenesisBlock == NULL) | |
2302 | return true; | |
2303 | } | |
2304 | hashBestChain = pindexBest->GetBlockHash(); | |
2305 | nBestHeight = pindexBest->nHeight; | |
2306 | bnBestChainWork = pindexBest->bnChainWork; | |
2307 | ||
2308 | // set 'next' pointers in best chain | |
2309 | CBlockIndex *pindex = pindexBest; | |
2310 | while(pindex != NULL && pindex->pprev != NULL) { | |
2311 | CBlockIndex *pindexPrev = pindex->pprev; | |
2312 | pindexPrev->pnext = pindex; | |
2313 | pindex = pindexPrev; | |
2314 | } | |
2315 | printf("LoadBlockIndex(): hashBestChain=%s height=%d date=%s\n", | |
f3a84c3a | 2316 | BlockHashStr(hashBestChain).c_str(), nBestHeight, |
2d8a4829 PW |
2317 | DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str()); |
2318 | ||
2319 | // Load bnBestInvalidWork, OK if it doesn't exist | |
2320 | pblocktree->ReadBestInvalidWork(bnBestInvalidWork); | |
2321 | ||
7fea4846 PW |
2322 | // Check whether we need to continue reindexing |
2323 | bool fReindexing = false; | |
2324 | pblocktree->ReadReindexing(fReindexing); | |
2325 | fReindex |= fReindexing; | |
2326 | ||
2d8a4829 PW |
2327 | // Verify blocks in the best chain |
2328 | int nCheckLevel = GetArg("-checklevel", 1); | |
2329 | int nCheckDepth = GetArg( "-checkblocks", 2500); | |
2330 | if (nCheckDepth == 0) | |
2331 | nCheckDepth = 1000000000; // suffices until the year 19000 | |
2332 | if (nCheckDepth > nBestHeight) | |
2333 | nCheckDepth = nBestHeight; | |
2334 | printf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel); | |
2335 | CBlockIndex* pindexFork = NULL; | |
2336 | for (CBlockIndex* pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev) | |
2337 | { | |
2338 | if (fRequestShutdown || pindex->nHeight < nBestHeight-nCheckDepth) | |
2339 | break; | |
2340 | CBlock block; | |
2341 | if (!block.ReadFromDisk(pindex)) | |
2342 | return error("LoadBlockIndex() : block.ReadFromDisk failed"); | |
2343 | // check level 1: verify block validity | |
2344 | if (nCheckLevel>0 && !block.CheckBlock()) | |
2345 | { | |
2346 | printf("LoadBlockIndex() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str()); | |
2347 | pindexFork = pindex->pprev; | |
2348 | } | |
2349 | // TODO: stronger verifications | |
2350 | } | |
2351 | if (pindexFork && !fRequestShutdown) | |
2352 | { | |
2353 | // TODO: reorg back | |
2354 | return error("LoadBlockIndex(): chain database corrupted"); | |
2355 | } | |
2356 | ||
2357 | return true; | |
2358 | } | |
2359 | ||
7fea4846 | 2360 | bool LoadBlockIndex() |
0a61b0df | 2361 | { |
5cbf7532 | 2362 | if (fTestNet) |
2363 | { | |
a9d811a9 GM |
2364 | pchMessageStart[0] = 0x0b; |
2365 | pchMessageStart[1] = 0x11; | |
2366 | pchMessageStart[2] = 0x09; | |
2367 | pchMessageStart[3] = 0x07; | |
feeb761b | 2368 | hashGenesisBlock = uint256("000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943"); |
5cbf7532 | 2369 | } |
2370 | ||
7fea4846 PW |
2371 | if (fReindex) |
2372 | return true; | |
2373 | ||
0a61b0df | 2374 | // |
d979e6e3 | 2375 | // Load block index from databases |
0a61b0df | 2376 | // |
d979e6e3 | 2377 | if (!LoadBlockIndexDB()) |
0a61b0df | 2378 | return false; |
0a61b0df | 2379 | |
2380 | // | |
2381 | // Init with genesis block | |
2382 | // | |
2383 | if (mapBlockIndex.empty()) | |
2384 | { | |
0a61b0df | 2385 | // Genesis Block: |
2386 | // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1) | |
2387 | // CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0) | |
2388 | // CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73) | |
2389 | // CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B) | |
2390 | // vMerkleTree: 4a5e1e | |
2391 | ||
2392 | // Genesis block | |
2393 | const char* pszTimestamp = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks"; | |
2394 | CTransaction txNew; | |
2395 | txNew.vin.resize(1); | |
2396 | txNew.vout.resize(1); | |
2397 | txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); | |
2398 | txNew.vout[0].nValue = 50 * COIN; | |
2399 | txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG; | |
2400 | CBlock block; | |
2401 | block.vtx.push_back(txNew); | |
2402 | block.hashPrevBlock = 0; | |
2403 | block.hashMerkleRoot = block.BuildMerkleTree(); | |
2404 | block.nVersion = 1; | |
2405 | block.nTime = 1231006505; | |
2406 | block.nBits = 0x1d00ffff; | |
2407 | block.nNonce = 2083236893; | |
2408 | ||
5cbf7532 | 2409 | if (fTestNet) |
2410 | { | |
98ba262a | 2411 | block.nTime = 1296688602; |
feeb761b | 2412 | block.nNonce = 414098458; |
5cbf7532 | 2413 | } |
0a61b0df | 2414 | |
5cbf7532 | 2415 | //// debug print |
630fd8dc PW |
2416 | uint256 hash = block.GetHash(); |
2417 | printf("%s\n", hash.ToString().c_str()); | |
5cbf7532 | 2418 | printf("%s\n", hashGenesisBlock.ToString().c_str()); |
2419 | printf("%s\n", block.hashMerkleRoot.ToString().c_str()); | |
2420 | assert(block.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b")); | |
2421 | block.print(); | |
630fd8dc | 2422 | assert(hash == hashGenesisBlock); |
0a61b0df | 2423 | |
2424 | // Start new block file | |
5382bcf8 PW |
2425 | unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION); |
2426 | CDiskBlockPos blockPos; | |
d979e6e3 PW |
2427 | if (!FindBlockPos(blockPos, nBlockSize+8, 0, block.nTime)) |
2428 | return error("AcceptBlock() : FindBlockPos failed"); | |
630fd8dc | 2429 | if (!block.WriteToDisk(blockPos)) |
0a61b0df | 2430 | return error("LoadBlockIndex() : writing genesis block to disk failed"); |
630fd8dc | 2431 | if (!block.AddToBlockIndex(blockPos)) |
0a61b0df | 2432 | return error("LoadBlockIndex() : genesis block not accepted"); |
2433 | } | |
2434 | ||
2435 | return true; | |
2436 | } | |
2437 | ||
2438 | ||
2439 | ||
2440 | void PrintBlockTree() | |
2441 | { | |
814efd6f | 2442 | // pre-compute tree structure |
0a61b0df | 2443 | map<CBlockIndex*, vector<CBlockIndex*> > mapNext; |
2444 | for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi) | |
2445 | { | |
2446 | CBlockIndex* pindex = (*mi).second; | |
2447 | mapNext[pindex->pprev].push_back(pindex); | |
2448 | // test | |
2449 | //while (rand() % 3 == 0) | |
2450 | // mapNext[pindex->pprev].push_back(pindex); | |
2451 | } | |
2452 | ||
2453 | vector<pair<int, CBlockIndex*> > vStack; | |
2454 | vStack.push_back(make_pair(0, pindexGenesisBlock)); | |
2455 | ||
2456 | int nPrevCol = 0; | |
2457 | while (!vStack.empty()) | |
2458 | { | |
2459 | int nCol = vStack.back().first; | |
2460 | CBlockIndex* pindex = vStack.back().second; | |
2461 | vStack.pop_back(); | |
2462 | ||
2463 | // print split or gap | |
2464 | if (nCol > nPrevCol) | |
2465 | { | |
2466 | for (int i = 0; i < nCol-1; i++) | |
2467 | printf("| "); | |
2468 | printf("|\\\n"); | |
2469 | } | |
2470 | else if (nCol < nPrevCol) | |
2471 | { | |
2472 | for (int i = 0; i < nCol; i++) | |
2473 | printf("| "); | |
2474 | printf("|\n"); | |
64c7ee7e | 2475 | } |
0a61b0df | 2476 | nPrevCol = nCol; |
2477 | ||
2478 | // print columns | |
2479 | for (int i = 0; i < nCol; i++) | |
2480 | printf("| "); | |
2481 | ||
2482 | // print item | |
2483 | CBlock block; | |
2484 | block.ReadFromDisk(pindex); | |
450cbb09 | 2485 | printf("%d (blk%05u.dat:0x%x) %s tx %"PRIszu"", |
0a61b0df | 2486 | pindex->nHeight, |
5382bcf8 | 2487 | pindex->GetBlockPos().nFile, pindex->GetBlockPos().nPos, |
0a61b0df | 2488 | DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(), |
2489 | block.vtx.size()); | |
2490 | ||
64c7ee7e | 2491 | PrintWallets(block); |
0a61b0df | 2492 | |
814efd6f | 2493 | // put the main time-chain first |
0a61b0df | 2494 | vector<CBlockIndex*>& vNext = mapNext[pindex]; |
c376ac35 | 2495 | for (unsigned int i = 0; i < vNext.size(); i++) |
0a61b0df | 2496 | { |
2497 | if (vNext[i]->pnext) | |
2498 | { | |
2499 | swap(vNext[0], vNext[i]); | |
2500 | break; | |
2501 | } | |
2502 | } | |
2503 | ||
2504 | // iterate children | |
c376ac35 | 2505 | for (unsigned int i = 0; i < vNext.size(); i++) |
0a61b0df | 2506 | vStack.push_back(make_pair(nCol+i, vNext[i])); |
2507 | } | |
2508 | } | |
2509 | ||
7fea4846 | 2510 | bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp) |
1d740055 | 2511 | { |
746f502a PK |
2512 | int64 nStart = GetTimeMillis(); |
2513 | ||
1d740055 PW |
2514 | int nLoaded = 0; |
2515 | { | |
05d97268 | 2516 | CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SIZE, MAX_BLOCK_SIZE+8, SER_DISK, CLIENT_VERSION); |
7fea4846 PW |
2517 | uint64 nStartByte = 0; |
2518 | if (dbp) { | |
2519 | // (try to) skip already indexed part | |
2520 | CBlockFileInfo info; | |
2521 | if (pblocktree->ReadBlockFileInfo(dbp->nFile, info)) { | |
2522 | nStartByte = info.nSize; | |
2523 | blkdat.Seek(info.nSize); | |
2524 | } | |
2525 | } | |
05d97268 PW |
2526 | uint64 nRewind = blkdat.GetPos(); |
2527 | while (blkdat.good() && !blkdat.eof() && !fShutdown) { | |
2528 | blkdat.SetPos(nRewind); | |
2529 | nRewind++; // start one byte further next time, in case of failure | |
2530 | blkdat.SetLimit(); // remove former limit | |
7fea4846 | 2531 | unsigned int nSize = 0; |
05d97268 PW |
2532 | try { |
2533 | // locate a header | |
2534 | unsigned char buf[4]; | |
2535 | blkdat.FindByte(pchMessageStart[0]); | |
2536 | nRewind = blkdat.GetPos()+1; | |
2537 | blkdat >> FLATDATA(buf); | |
2538 | if (memcmp(buf, pchMessageStart, 4)) | |
2539 | continue; | |
2540 | // read size | |
1d740055 | 2541 | blkdat >> nSize; |
05d97268 PW |
2542 | if (nSize < 80 || nSize > MAX_BLOCK_SIZE) |
2543 | continue; | |
7fea4846 PW |
2544 | } catch (std::exception &e) { |
2545 | // no valid block header found; don't complain | |
2546 | break; | |
2547 | } | |
2548 | try { | |
05d97268 | 2549 | // read block |
7fea4846 PW |
2550 | uint64 nBlockPos = blkdat.GetPos(); |
2551 | blkdat.SetLimit(nBlockPos + nSize); | |
05d97268 PW |
2552 | CBlock block; |
2553 | blkdat >> block; | |
2554 | nRewind = blkdat.GetPos(); | |
7fea4846 PW |
2555 | |
2556 | // process block | |
2557 | if (nBlockPos >= nStartByte) { | |
66b02c93 | 2558 | LOCK(cs_main); |
7fea4846 PW |
2559 | if (dbp) |
2560 | dbp->nPos = nBlockPos; | |
2561 | if (ProcessBlock(NULL, &block, dbp)) | |
1d740055 | 2562 | nLoaded++; |
1d740055 | 2563 | } |
05d97268 PW |
2564 | } catch (std::exception &e) { |
2565 | printf("%s() : Deserialize or I/O error caught during load\n", __PRETTY_FUNCTION__); | |
1d740055 PW |
2566 | } |
2567 | } | |
05d97268 | 2568 | fclose(fileIn); |
1d740055 | 2569 | } |
7fea4846 PW |
2570 | if (nLoaded > 0) |
2571 | printf("Loaded %i blocks from external file in %"PRI64d"ms\n", nLoaded, GetTimeMillis() - nStart); | |
1d740055 PW |
2572 | return nLoaded > 0; |
2573 | } | |
0a61b0df | 2574 | |
66b02c93 | 2575 | |
0a61b0df | 2576 | |
2577 | ||
2578 | ||
2579 | ||
2580 | ||
2581 | ||
2582 | ||
2583 | ||
2584 | ////////////////////////////////////////////////////////////////////////////// | |
2585 | // | |
2586 | // CAlert | |
2587 | // | |
2588 | ||
f35c6c4f GA |
2589 | extern map<uint256, CAlert> mapAlerts; |
2590 | extern CCriticalSection cs_mapAlerts; | |
0a61b0df | 2591 | |
2592 | string GetWarnings(string strFor) | |
2593 | { | |
2594 | int nPriority = 0; | |
2595 | string strStatusBar; | |
2596 | string strRPC; | |
62e21fb5 | 2597 | |
bdde31d7 | 2598 | if (GetBoolArg("-testsafemode")) |
0a61b0df | 2599 | strRPC = "test"; |
2600 | ||
62e21fb5 WL |
2601 | if (!CLIENT_VERSION_IS_RELEASE) |
2602 | strStatusBar = _("This is a pre-release test build - use at your own risk - do not use for mining or merchant applications"); | |
2603 | ||
0a61b0df | 2604 | // Misc warnings like out of disk space and clock is wrong |
2605 | if (strMiscWarning != "") | |
2606 | { | |
2607 | nPriority = 1000; | |
2608 | strStatusBar = strMiscWarning; | |
2609 | } | |
2610 | ||
2611 | // Longer invalid proof-of-work chain | |
2612 | if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6) | |
2613 | { | |
2614 | nPriority = 2000; | |
e6bc9c35 | 2615 | strStatusBar = strRPC = _("Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade."); |
0a61b0df | 2616 | } |
2617 | ||
2618 | // Alerts | |
0a61b0df | 2619 | { |
f8dcd5ca | 2620 | LOCK(cs_mapAlerts); |
223b6f1b | 2621 | BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts) |
0a61b0df | 2622 | { |
2623 | const CAlert& alert = item.second; | |
2624 | if (alert.AppliesToMe() && alert.nPriority > nPriority) | |
2625 | { | |
2626 | nPriority = alert.nPriority; | |
2627 | strStatusBar = alert.strStatusBar; | |
0a61b0df | 2628 | } |
2629 | } | |
2630 | } | |
2631 | ||
2632 | if (strFor == "statusbar") | |
2633 | return strStatusBar; | |
2634 | else if (strFor == "rpc") | |
2635 | return strRPC; | |
ecf1c79a | 2636 | assert(!"GetWarnings() : invalid parameter"); |
0a61b0df | 2637 | return "error"; |
2638 | } | |
2639 | ||
0a61b0df | 2640 | |
2641 | ||
2642 | ||
2643 | ||
2644 | ||
2645 | ||
2646 | ||
2647 | ////////////////////////////////////////////////////////////////////////////// | |
2648 | // | |
2649 | // Messages | |
2650 | // | |
2651 | ||
2652 | ||
ae8bfd12 | 2653 | bool static AlreadyHave(const CInv& inv) |
0a61b0df | 2654 | { |
2655 | switch (inv.type) | |
2656 | { | |
8deb9822 JG |
2657 | case MSG_TX: |
2658 | { | |
450cbb09 | 2659 | bool txInMap = false; |
ce8c9349 | 2660 | { |
450cbb09 PW |
2661 | LOCK(mempool.cs); |
2662 | txInMap = mempool.exists(inv.hash); | |
ce8c9349 | 2663 | } |
450cbb09 | 2664 | return txInMap || mapOrphanTransactions.count(inv.hash) || |
ae8bfd12 | 2665 | pcoinsTip->HaveCoins(inv.hash); |
8deb9822 | 2666 | } |
8deb9822 JG |
2667 | case MSG_BLOCK: |
2668 | return mapBlockIndex.count(inv.hash) || | |
2669 | mapOrphanBlocks.count(inv.hash); | |
0a61b0df | 2670 | } |
2671 | // Don't know what it is, just say we already got one | |
2672 | return true; | |
2673 | } | |
2674 | ||
2675 | ||
2676 | ||
2677 | ||
5cbf7532 | 2678 | // The message start string is designed to be unlikely to occur in normal data. |
814efd6f | 2679 | // The characters are rarely used upper ASCII, not valid as UTF-8, and produce |
5cbf7532 | 2680 | // a large 4-byte int at any alignment. |
25133bd7 | 2681 | unsigned char pchMessageStart[4] = { 0xf9, 0xbe, 0xb4, 0xd9 }; |
0a61b0df | 2682 | |
2683 | ||
64c7ee7e | 2684 | bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv) |
0a61b0df | 2685 | { |
0a61b0df | 2686 | RandAddSeedPerfmon(); |
0985816b | 2687 | if (fDebug) |
d210f4f5 | 2688 | printf("received: %s (%"PRIszu" bytes)\n", strCommand.c_str(), vRecv.size()); |
0a61b0df | 2689 | if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0) |
2690 | { | |
2691 | printf("dropmessagestest DROPPING RECV MESSAGE\n"); | |
2692 | return true; | |
2693 | } | |
2694 | ||
2695 | ||
2696 | ||
2697 | ||
2698 | ||
2699 | if (strCommand == "version") | |
2700 | { | |
2701 | // Each connection can only send one version message | |
2702 | if (pfrom->nVersion != 0) | |
806704c2 GA |
2703 | { |
2704 | pfrom->Misbehaving(1); | |
0a61b0df | 2705 | return false; |
806704c2 | 2706 | } |
0a61b0df | 2707 | |
bde280b9 | 2708 | int64 nTime; |
0a61b0df | 2709 | CAddress addrMe; |
2710 | CAddress addrFrom; | |
bde280b9 | 2711 | uint64 nNonce = 1; |
0a61b0df | 2712 | vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe; |
8b09cd3a | 2713 | if (pfrom->nVersion < MIN_PROTO_VERSION) |
18c0fa97 | 2714 | { |
27adfb2e | 2715 | // Since February 20, 2012, the protocol is initiated at version 209, |
18c0fa97 PW |
2716 | // and earlier versions are no longer supported |
2717 | printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion); | |
2718 | pfrom->fDisconnect = true; | |
2719 | return false; | |
2720 | } | |
2721 | ||
0a61b0df | 2722 | if (pfrom->nVersion == 10300) |
2723 | pfrom->nVersion = 300; | |
18c0fa97 | 2724 | if (!vRecv.empty()) |
0a61b0df | 2725 | vRecv >> addrFrom >> nNonce; |
18c0fa97 | 2726 | if (!vRecv.empty()) |
0a61b0df | 2727 | vRecv >> pfrom->strSubVer; |
18c0fa97 | 2728 | if (!vRecv.empty()) |
0a61b0df | 2729 | vRecv >> pfrom->nStartingHeight; |
2730 | ||
39857190 PW |
2731 | if (pfrom->fInbound && addrMe.IsRoutable()) |
2732 | { | |
2733 | pfrom->addrLocal = addrMe; | |
2734 | SeenLocal(addrMe); | |
2735 | } | |
2736 | ||
0a61b0df | 2737 | // Disconnect if we connected to ourself |
2738 | if (nNonce == nLocalHostNonce && nNonce > 1) | |
2739 | { | |
b22c8842 | 2740 | printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str()); |
0a61b0df | 2741 | pfrom->fDisconnect = true; |
2742 | return true; | |
2743 | } | |
2744 | ||
cbc920d4 GA |
2745 | // Be shy and don't send version until we hear |
2746 | if (pfrom->fInbound) | |
2747 | pfrom->PushVersion(); | |
2748 | ||
0a61b0df | 2749 | pfrom->fClient = !(pfrom->nServices & NODE_NETWORK); |
0a61b0df | 2750 | |
67a42f92 | 2751 | AddTimeData(pfrom->addr, nTime); |
0a61b0df | 2752 | |
2753 | // Change version | |
18c0fa97 | 2754 | pfrom->PushMessage("verack"); |
f8ded588 | 2755 | pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION)); |
0a61b0df | 2756 | |
c891967b | 2757 | if (!pfrom->fInbound) |
2758 | { | |
2759 | // Advertise our address | |
587f929c | 2760 | if (!fNoListen && !IsInitialBlockDownload()) |
c891967b | 2761 | { |
39857190 PW |
2762 | CAddress addr = GetLocalAddress(&pfrom->addr); |
2763 | if (addr.IsRoutable()) | |
2764 | pfrom->PushAddress(addr); | |
c891967b | 2765 | } |
2766 | ||
2767 | // Get recent addresses | |
478b01d9 | 2768 | if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000) |
c891967b | 2769 | { |
2770 | pfrom->PushMessage("getaddr"); | |
2771 | pfrom->fGetAddr = true; | |
2772 | } | |
5fee401f PW |
2773 | addrman.Good(pfrom->addr); |
2774 | } else { | |
2775 | if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom) | |
2776 | { | |
2777 | addrman.Add(addrFrom, addrFrom); | |
2778 | addrman.Good(addrFrom); | |
2779 | } | |
c891967b | 2780 | } |
2781 | ||
0a61b0df | 2782 | // Ask the first connected node for block updates |
9ef7fa34 | 2783 | static int nAskedForBlocks = 0; |
7fea4846 | 2784 | if (!pfrom->fClient && !pfrom->fOneShot && !fImporting && !fReindex && |
93dd68e9 | 2785 | (pfrom->nStartingHeight > (nBestHeight - 144)) && |
8b09cd3a | 2786 | (pfrom->nVersion < NOBLKS_VERSION_START || |
ce8c9349 | 2787 | pfrom->nVersion >= NOBLKS_VERSION_END) && |
ec74e8a4 | 2788 | (nAskedForBlocks < 1 || vNodes.size() <= 1)) |
0a61b0df | 2789 | { |
2790 | nAskedForBlocks++; | |
2791 | pfrom->PushGetBlocks(pindexBest, uint256(0)); | |
2792 | } | |
2793 | ||
2794 | // Relay alerts | |
f8dcd5ca PW |
2795 | { |
2796 | LOCK(cs_mapAlerts); | |
223b6f1b | 2797 | BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts) |
0a61b0df | 2798 | item.second.RelayTo(pfrom); |
f8dcd5ca | 2799 | } |
0a61b0df | 2800 | |
2801 | pfrom->fSuccessfullyConnected = true; | |
2802 | ||
863e995b | 2803 | printf("receive version message: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", pfrom->nVersion, pfrom->nStartingHeight, addrMe.ToString().c_str(), addrFrom.ToString().c_str(), pfrom->addr.ToString().c_str()); |
a8b95ce6 WL |
2804 | |
2805 | cPeerBlockCounts.input(pfrom->nStartingHeight); | |
0a61b0df | 2806 | } |
2807 | ||
2808 | ||
2809 | else if (pfrom->nVersion == 0) | |
2810 | { | |
2811 | // Must have a version message before anything else | |
806704c2 | 2812 | pfrom->Misbehaving(1); |
0a61b0df | 2813 | return false; |
2814 | } | |
2815 | ||
2816 | ||
2817 | else if (strCommand == "verack") | |
2818 | { | |
f8ded588 | 2819 | pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION)); |
0a61b0df | 2820 | } |
2821 | ||
2822 | ||
2823 | else if (strCommand == "addr") | |
2824 | { | |
2825 | vector<CAddress> vAddr; | |
2826 | vRecv >> vAddr; | |
c891967b | 2827 | |
2828 | // Don't want addr from older versions unless seeding | |
8b09cd3a | 2829 | if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000) |
0a61b0df | 2830 | return true; |
2831 | if (vAddr.size() > 1000) | |
806704c2 GA |
2832 | { |
2833 | pfrom->Misbehaving(20); | |
d210f4f5 | 2834 | return error("message addr size() = %"PRIszu"", vAddr.size()); |
806704c2 | 2835 | } |
0a61b0df | 2836 | |
2837 | // Store the new addresses | |
090e5b40 | 2838 | vector<CAddress> vAddrOk; |
bde280b9 WL |
2839 | int64 nNow = GetAdjustedTime(); |
2840 | int64 nSince = nNow - 10 * 60; | |
223b6f1b | 2841 | BOOST_FOREACH(CAddress& addr, vAddr) |
0a61b0df | 2842 | { |
2843 | if (fShutdown) | |
2844 | return true; | |
c891967b | 2845 | if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60) |
2846 | addr.nTime = nNow - 5 * 24 * 60 * 60; | |
0a61b0df | 2847 | pfrom->AddAddressKnown(addr); |
090e5b40 | 2848 | bool fReachable = IsReachable(addr); |
c891967b | 2849 | if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable()) |
0a61b0df | 2850 | { |
2851 | // Relay to a limited number of other nodes | |
0a61b0df | 2852 | { |
f8dcd5ca | 2853 | LOCK(cs_vNodes); |
5cbf7532 | 2854 | // Use deterministic randomness to send to the same nodes for 24 hours |
2855 | // at a time so the setAddrKnowns of the chosen nodes prevent repeats | |
0a61b0df | 2856 | static uint256 hashSalt; |
2857 | if (hashSalt == 0) | |
f718aedd | 2858 | hashSalt = GetRandHash(); |
4843b55f | 2859 | uint64 hashAddr = addr.GetHash(); |
67a42f92 | 2860 | uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60)); |
5cbf7532 | 2861 | hashRand = Hash(BEGIN(hashRand), END(hashRand)); |
0a61b0df | 2862 | multimap<uint256, CNode*> mapMix; |
223b6f1b | 2863 | BOOST_FOREACH(CNode* pnode, vNodes) |
5cbf7532 | 2864 | { |
8b09cd3a | 2865 | if (pnode->nVersion < CADDR_TIME_VERSION) |
c891967b | 2866 | continue; |
5cbf7532 | 2867 | unsigned int nPointer; |
2868 | memcpy(&nPointer, &pnode, sizeof(nPointer)); | |
2869 | uint256 hashKey = hashRand ^ nPointer; | |
2870 | hashKey = Hash(BEGIN(hashKey), END(hashKey)); | |
2871 | mapMix.insert(make_pair(hashKey, pnode)); | |
2872 | } | |
090e5b40 | 2873 | int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s) |
0a61b0df | 2874 | for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi) |
2875 | ((*mi).second)->PushAddress(addr); | |
2876 | } | |
2877 | } | |
090e5b40 PW |
2878 | // Do not store addresses outside our network |
2879 | if (fReachable) | |
2880 | vAddrOk.push_back(addr); | |
0a61b0df | 2881 | } |
090e5b40 | 2882 | addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60); |
0a61b0df | 2883 | if (vAddr.size() < 1000) |
2884 | pfrom->fGetAddr = false; | |
478b01d9 PW |
2885 | if (pfrom->fOneShot) |
2886 | pfrom->fDisconnect = true; | |
0a61b0df | 2887 | } |
2888 | ||
2889 | ||
2890 | else if (strCommand == "inv") | |
2891 | { | |
2892 | vector<CInv> vInv; | |
2893 | vRecv >> vInv; | |
05a85b2b | 2894 | if (vInv.size() > MAX_INV_SZ) |
806704c2 GA |
2895 | { |
2896 | pfrom->Misbehaving(20); | |
d210f4f5 | 2897 | return error("message inv size() = %"PRIszu"", vInv.size()); |
806704c2 | 2898 | } |
0a61b0df | 2899 | |
68601333 PW |
2900 | // find last block in inv vector |
2901 | unsigned int nLastBlock = (unsigned int)(-1); | |
2902 | for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) { | |
385f730f | 2903 | if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) { |
68601333 | 2904 | nLastBlock = vInv.size() - 1 - nInv; |
385f730f PW |
2905 | break; |
2906 | } | |
68601333 | 2907 | } |
c376ac35 | 2908 | for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) |
0a61b0df | 2909 | { |
0aa89c08 PW |
2910 | const CInv &inv = vInv[nInv]; |
2911 | ||
0a61b0df | 2912 | if (fShutdown) |
2913 | return true; | |
2914 | pfrom->AddInventoryKnown(inv); | |
2915 | ||
ae8bfd12 | 2916 | bool fAlreadyHave = AlreadyHave(inv); |
59090133 NS |
2917 | if (fDebug) |
2918 | printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new"); | |
0a61b0df | 2919 | |
66b02c93 | 2920 | if (!fAlreadyHave) { |
7fea4846 | 2921 | if (!fImporting && !fReindex) |
66b02c93 PW |
2922 | pfrom->AskFor(inv); |
2923 | } else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) { | |
0a61b0df | 2924 | pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash])); |
385f730f PW |
2925 | } else if (nInv == nLastBlock) { |
2926 | // In case we are on a very long side-chain, it is possible that we already have | |
2927 | // the last block in an inv bundle sent in response to getblocks. Try to detect | |
2928 | // this situation and push another getblocks to continue. | |
385f730f PW |
2929 | pfrom->PushGetBlocks(mapBlockIndex[inv.hash], uint256(0)); |
2930 | if (fDebug) | |
2931 | printf("force request: %s\n", inv.ToString().c_str()); | |
2932 | } | |
0a61b0df | 2933 | |
2934 | // Track requests for our stuff | |
64c7ee7e | 2935 | Inventory(inv.hash); |
0a61b0df | 2936 | } |
2937 | } | |
2938 | ||
2939 | ||
2940 | else if (strCommand == "getdata") | |
2941 | { | |
2942 | vector<CInv> vInv; | |
2943 | vRecv >> vInv; | |
05a85b2b | 2944 | if (vInv.size() > MAX_INV_SZ) |
806704c2 GA |
2945 | { |
2946 | pfrom->Misbehaving(20); | |
d210f4f5 | 2947 | return error("message getdata size() = %"PRIszu"", vInv.size()); |
806704c2 | 2948 | } |
0a61b0df | 2949 | |
983e4bde | 2950 | if (fDebugNet || (vInv.size() != 1)) |
d210f4f5 | 2951 | printf("received getdata (%"PRIszu" invsz)\n", vInv.size()); |
983e4bde | 2952 | |
223b6f1b | 2953 | BOOST_FOREACH(const CInv& inv, vInv) |
0a61b0df | 2954 | { |
2955 | if (fShutdown) | |
2956 | return true; | |
983e4bde JG |
2957 | if (fDebugNet || (vInv.size() == 1)) |
2958 | printf("received getdata for: %s\n", inv.ToString().c_str()); | |
0a61b0df | 2959 | |
2960 | if (inv.type == MSG_BLOCK) | |
2961 | { | |
2962 | // Send block from disk | |
2963 | map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash); | |
2964 | if (mi != mapBlockIndex.end()) | |
2965 | { | |
0a61b0df | 2966 | CBlock block; |
f03304a9 | 2967 | block.ReadFromDisk((*mi).second); |
0a61b0df | 2968 | pfrom->PushMessage("block", block); |
2969 | ||
2970 | // Trigger them to send a getblocks request for the next batch of inventory | |
2971 | if (inv.hash == pfrom->hashContinue) | |
2972 | { | |
2973 | // Bypass PushInventory, this must send even if redundant, | |
2974 | // and we want it right after the last block so they don't | |
2975 | // wait for other stuff first. | |
2976 | vector<CInv> vInv; | |
2977 | vInv.push_back(CInv(MSG_BLOCK, hashBestChain)); | |
2978 | pfrom->PushMessage("inv", vInv); | |
2979 | pfrom->hashContinue = 0; | |
2980 | } | |
2981 | } | |
2982 | } | |
2983 | else if (inv.IsKnownType()) | |
2984 | { | |
2985 | // Send stream from relay memory | |
05a85b2b | 2986 | bool pushed = false; |
0a61b0df | 2987 | { |
f8dcd5ca | 2988 | LOCK(cs_mapRelay); |
0a61b0df | 2989 | map<CInv, CDataStream>::iterator mi = mapRelay.find(inv); |
05a85b2b | 2990 | if (mi != mapRelay.end()) { |
0a61b0df | 2991 | pfrom->PushMessage(inv.GetCommand(), (*mi).second); |
05a85b2b JG |
2992 | pushed = true; |
2993 | } | |
2994 | } | |
2995 | if (!pushed && inv.type == MSG_TX) { | |
2996 | LOCK(mempool.cs); | |
2997 | if (mempool.exists(inv.hash)) { | |
2998 | CTransaction tx = mempool.lookup(inv.hash); | |
2999 | CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); | |
3000 | ss.reserve(1000); | |
3001 | ss << tx; | |
3002 | pfrom->PushMessage("tx", ss); | |
3003 | } | |
0a61b0df | 3004 | } |
3005 | } | |
3006 | ||
3007 | // Track requests for our stuff | |
64c7ee7e | 3008 | Inventory(inv.hash); |
0a61b0df | 3009 | } |
3010 | } | |
3011 | ||
3012 | ||
3013 | else if (strCommand == "getblocks") | |
3014 | { | |
3015 | CBlockLocator locator; | |
3016 | uint256 hashStop; | |
3017 | vRecv >> locator >> hashStop; | |
3018 | ||
f03304a9 | 3019 | // Find the last block the caller has in the main chain |
0a61b0df | 3020 | CBlockIndex* pindex = locator.GetBlockIndex(); |
3021 | ||
3022 | // Send the rest of the chain | |
3023 | if (pindex) | |
3024 | pindex = pindex->pnext; | |
9d6cd04b | 3025 | int nLimit = 500; |
f3a84c3a | 3026 | printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), BlockHashStr(hashStop).c_str(), nLimit); |
0a61b0df | 3027 | for (; pindex; pindex = pindex->pnext) |
3028 | { | |
3029 | if (pindex->GetBlockHash() == hashStop) | |
3030 | { | |
f3a84c3a | 3031 | printf(" getblocks stopping at %d %s\n", pindex->nHeight, BlockHashStr(pindex->GetBlockHash()).c_str()); |
0a61b0df | 3032 | break; |
3033 | } | |
3034 | pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash())); | |
9d6cd04b | 3035 | if (--nLimit <= 0) |
0a61b0df | 3036 | { |
3037 | // When this block is requested, we'll send an inv that'll make them | |
3038 | // getblocks the next batch of inventory. | |
f3a84c3a | 3039 | printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, BlockHashStr(pindex->GetBlockHash()).c_str()); |
0a61b0df | 3040 | pfrom->hashContinue = pindex->GetBlockHash(); |
3041 | break; | |
3042 | } | |
3043 | } | |
3044 | } | |
3045 | ||
3046 | ||
f03304a9 | 3047 | else if (strCommand == "getheaders") |
3048 | { | |
3049 | CBlockLocator locator; | |
3050 | uint256 hashStop; | |
3051 | vRecv >> locator >> hashStop; | |
3052 | ||
3053 | CBlockIndex* pindex = NULL; | |
3054 | if (locator.IsNull()) | |
3055 | { | |
3056 | // If locator is null, return the hashStop block | |
3057 | map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop); | |
3058 | if (mi == mapBlockIndex.end()) | |
3059 | return true; | |
3060 | pindex = (*mi).second; | |
3061 | } | |
3062 | else | |
3063 | { | |
3064 | // Find the last block the caller has in the main chain | |
3065 | pindex = locator.GetBlockIndex(); | |
3066 | if (pindex) | |
3067 | pindex = pindex->pnext; | |
3068 | } | |
3069 | ||
e754cf41 | 3070 | // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end |
f03304a9 | 3071 | vector<CBlock> vHeaders; |
ecf07f27 | 3072 | int nLimit = 2000; |
f3a84c3a | 3073 | printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), BlockHashStr(hashStop).c_str()); |
f03304a9 | 3074 | for (; pindex; pindex = pindex->pnext) |
3075 | { | |
3076 | vHeaders.push_back(pindex->GetBlockHeader()); | |
3077 | if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop) | |
3078 | break; | |
3079 | } | |
3080 | pfrom->PushMessage("headers", vHeaders); | |
3081 | } | |
3082 | ||
3083 | ||
0a61b0df | 3084 | else if (strCommand == "tx") |
3085 | { | |
3086 | vector<uint256> vWorkQueue; | |
7a15109c | 3087 | vector<uint256> vEraseQueue; |
0a61b0df | 3088 | CDataStream vMsg(vRecv); |
3089 | CTransaction tx; | |
3090 | vRecv >> tx; | |
3091 | ||
3092 | CInv inv(MSG_TX, tx.GetHash()); | |
3093 | pfrom->AddInventoryKnown(inv); | |
3094 | ||
3095 | bool fMissingInputs = false; | |
ae8bfd12 | 3096 | if (tx.AcceptToMemoryPool(true, &fMissingInputs)) |
0a61b0df | 3097 | { |
64dd46fd | 3098 | SyncWithWallets(inv.hash, tx, NULL, true); |
0a61b0df | 3099 | RelayMessage(inv, vMsg); |
3100 | mapAlreadyAskedFor.erase(inv); | |
3101 | vWorkQueue.push_back(inv.hash); | |
7a15109c | 3102 | vEraseQueue.push_back(inv.hash); |
0a61b0df | 3103 | |
3104 | // Recursively process any orphan transactions that depended on this one | |
c376ac35 | 3105 | for (unsigned int i = 0; i < vWorkQueue.size(); i++) |
0a61b0df | 3106 | { |
3107 | uint256 hashPrev = vWorkQueue[i]; | |
77b99cf7 GA |
3108 | for (map<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin(); |
3109 | mi != mapOrphanTransactionsByPrev[hashPrev].end(); | |
0a61b0df | 3110 | ++mi) |
3111 | { | |
3112 | const CDataStream& vMsg = *((*mi).second); | |
3113 | CTransaction tx; | |
3114 | CDataStream(vMsg) >> tx; | |
3115 | CInv inv(MSG_TX, tx.GetHash()); | |
7a15109c | 3116 | bool fMissingInputs2 = false; |
0a61b0df | 3117 | |
ae8bfd12 | 3118 | if (tx.AcceptToMemoryPool(true, &fMissingInputs2)) |
0a61b0df | 3119 | { |
b22c8842 | 3120 | printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str()); |
64dd46fd | 3121 | SyncWithWallets(inv.hash, tx, NULL, true); |
0a61b0df | 3122 | RelayMessage(inv, vMsg); |
3123 | mapAlreadyAskedFor.erase(inv); | |
3124 | vWorkQueue.push_back(inv.hash); | |
7a15109c GA |
3125 | vEraseQueue.push_back(inv.hash); |
3126 | } | |
3127 | else if (!fMissingInputs2) | |
3128 | { | |
3129 | // invalid orphan | |
3130 | vEraseQueue.push_back(inv.hash); | |
3131 | printf(" removed invalid orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str()); | |
0a61b0df | 3132 | } |
3133 | } | |
3134 | } | |
3135 | ||
7a15109c | 3136 | BOOST_FOREACH(uint256 hash, vEraseQueue) |
0a61b0df | 3137 | EraseOrphanTx(hash); |
3138 | } | |
3139 | else if (fMissingInputs) | |
3140 | { | |
0a61b0df | 3141 | AddOrphanTx(vMsg); |
142e6041 GA |
3142 | |
3143 | // DoS prevention: do not allow mapOrphanTransactions to grow unbounded | |
7bd9c3a3 | 3144 | unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS); |
142e6041 | 3145 | if (nEvicted > 0) |
7bd9c3a3 | 3146 | printf("mapOrphan overflow, removed %u tx\n", nEvicted); |
0a61b0df | 3147 | } |
3e52aaf2 | 3148 | if (tx.nDoS) pfrom->Misbehaving(tx.nDoS); |
0a61b0df | 3149 | } |
3150 | ||
3151 | ||
7fea4846 | 3152 | else if (strCommand == "block" && !fImporting && !fReindex) // Ignore blocks received while importing |
0a61b0df | 3153 | { |
f03304a9 | 3154 | CBlock block; |
3155 | vRecv >> block; | |
0a61b0df | 3156 | |
f3a84c3a | 3157 | printf("received block %s\n", BlockHashStr(block.GetHash()).c_str()); |
f03304a9 | 3158 | // block.print(); |
0a61b0df | 3159 | |
f03304a9 | 3160 | CInv inv(MSG_BLOCK, block.GetHash()); |
0a61b0df | 3161 | pfrom->AddInventoryKnown(inv); |
3162 | ||
f03304a9 | 3163 | if (ProcessBlock(pfrom, &block)) |
0a61b0df | 3164 | mapAlreadyAskedFor.erase(inv); |
3e52aaf2 | 3165 | if (block.nDoS) pfrom->Misbehaving(block.nDoS); |
0a61b0df | 3166 | } |
3167 | ||
3168 | ||
3169 | else if (strCommand == "getaddr") | |
3170 | { | |
0a61b0df | 3171 | pfrom->vAddrToSend.clear(); |
5fee401f PW |
3172 | vector<CAddress> vAddr = addrman.GetAddr(); |
3173 | BOOST_FOREACH(const CAddress &addr, vAddr) | |
3174 | pfrom->PushAddress(addr); | |
0a61b0df | 3175 | } |
3176 | ||
3177 | ||
05a85b2b JG |
3178 | else if (strCommand == "mempool") |
3179 | { | |
3180 | std::vector<uint256> vtxid; | |
3181 | mempool.queryHashes(vtxid); | |
3182 | vector<CInv> vInv; | |
3183 | for (unsigned int i = 0; i < vtxid.size(); i++) { | |
3184 | CInv inv(MSG_TX, vtxid[i]); | |
3185 | vInv.push_back(inv); | |
3186 | if (i == (MAX_INV_SZ - 1)) | |
3187 | break; | |
3188 | } | |
3189 | if (vInv.size() > 0) | |
3190 | pfrom->PushMessage("inv", vInv); | |
3191 | } | |
3192 | ||
3193 | ||
0a61b0df | 3194 | else if (strCommand == "ping") |
3195 | { | |
93e447b6 JG |
3196 | if (pfrom->nVersion > BIP0031_VERSION) |
3197 | { | |
3198 | uint64 nonce = 0; | |
3199 | vRecv >> nonce; | |
3200 | // Echo the message back with the nonce. This allows for two useful features: | |
3201 | // | |
3202 | // 1) A remote node can quickly check if the connection is operational | |
3203 | // 2) Remote nodes can measure the latency of the network thread. If this node | |
3204 | // is overloaded it won't respond to pings quickly and the remote node can | |
3205 | // avoid sending us more work, like chain download requests. | |
3206 | // | |
3207 | // The nonce stops the remote getting confused between different pings: without | |
3208 | // it, if the remote node sends a ping once per second and this node takes 5 | |
3209 | // seconds to respond to each, the 5th ping the remote sends would appear to | |
3210 | // return very quickly. | |
3211 | pfrom->PushMessage("pong", nonce); | |
3212 | } | |
0a61b0df | 3213 | } |
3214 | ||
3215 | ||
3216 | else if (strCommand == "alert") | |
3217 | { | |
3218 | CAlert alert; | |
3219 | vRecv >> alert; | |
3220 | ||
d5a52d9b GA |
3221 | uint256 alertHash = alert.GetHash(); |
3222 | if (pfrom->setKnown.count(alertHash) == 0) | |
0a61b0df | 3223 | { |
d5a52d9b | 3224 | if (alert.ProcessAlert()) |
f8dcd5ca | 3225 | { |
d5a52d9b GA |
3226 | // Relay |
3227 | pfrom->setKnown.insert(alertHash); | |
3228 | { | |
3229 | LOCK(cs_vNodes); | |
3230 | BOOST_FOREACH(CNode* pnode, vNodes) | |
3231 | alert.RelayTo(pnode); | |
3232 | } | |
3233 | } | |
3234 | else { | |
3235 | // Small DoS penalty so peers that send us lots of | |
3236 | // duplicate/expired/invalid-signature/whatever alerts | |
3237 | // eventually get banned. | |
3238 | // This isn't a Misbehaving(100) (immediate ban) because the | |
3239 | // peer might be an older or different implementation with | |
3240 | // a different signature key, etc. | |
3241 | pfrom->Misbehaving(10); | |
f8dcd5ca | 3242 | } |
0a61b0df | 3243 | } |
3244 | } | |
3245 | ||
3246 | ||
3247 | else | |
3248 | { | |
3249 | // Ignore unknown commands for extensibility | |
3250 | } | |
3251 | ||
3252 | ||
3253 | // Update the last seen time for this node's address | |
3254 | if (pfrom->fNetworkNode) | |
3255 | if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping") | |
3256 | AddressCurrentlyConnected(pfrom->addr); | |
3257 | ||
3258 | ||
3259 | return true; | |
3260 | } | |
3261 | ||
e89b9f6a PW |
3262 | bool ProcessMessages(CNode* pfrom) |
3263 | { | |
3264 | CDataStream& vRecv = pfrom->vRecv; | |
3265 | if (vRecv.empty()) | |
3266 | return true; | |
3267 | //if (fDebug) | |
3268 | // printf("ProcessMessages(%u bytes)\n", vRecv.size()); | |
0a61b0df | 3269 | |
e89b9f6a PW |
3270 | // |
3271 | // Message format | |
3272 | // (4) message start | |
3273 | // (12) command | |
3274 | // (4) size | |
3275 | // (4) checksum | |
3276 | // (x) data | |
3277 | // | |
0a61b0df | 3278 | |
e89b9f6a PW |
3279 | loop |
3280 | { | |
9d6cd04b MC |
3281 | // Don't bother if send buffer is too full to respond anyway |
3282 | if (pfrom->vSend.size() >= SendBufferSize()) | |
3283 | break; | |
3284 | ||
e89b9f6a PW |
3285 | // Scan for message start |
3286 | CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart)); | |
3287 | int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader()); | |
3288 | if (vRecv.end() - pstart < nHeaderSize) | |
3289 | { | |
1d8c7a95 | 3290 | if ((int)vRecv.size() > nHeaderSize) |
e89b9f6a PW |
3291 | { |
3292 | printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n"); | |
3293 | vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize); | |
3294 | } | |
3295 | break; | |
3296 | } | |
3297 | if (pstart - vRecv.begin() > 0) | |
d210f4f5 | 3298 | printf("\n\nPROCESSMESSAGE SKIPPED %"PRIpdd" BYTES\n\n", pstart - vRecv.begin()); |
e89b9f6a | 3299 | vRecv.erase(vRecv.begin(), pstart); |
0a61b0df | 3300 | |
e89b9f6a PW |
3301 | // Read header |
3302 | vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize); | |
3303 | CMessageHeader hdr; | |
3304 | vRecv >> hdr; | |
3305 | if (!hdr.IsValid()) | |
3306 | { | |
3307 | printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str()); | |
3308 | continue; | |
3309 | } | |
3310 | string strCommand = hdr.GetCommand(); | |
3311 | ||
3312 | // Message size | |
3313 | unsigned int nMessageSize = hdr.nMessageSize; | |
3314 | if (nMessageSize > MAX_SIZE) | |
3315 | { | |
ea591ead | 3316 | printf("ProcessMessages(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize); |
e89b9f6a PW |
3317 | continue; |
3318 | } | |
3319 | if (nMessageSize > vRecv.size()) | |
3320 | { | |
3321 | // Rewind and wait for rest of message | |
3322 | vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end()); | |
3323 | break; | |
3324 | } | |
3325 | ||
3326 | // Checksum | |
18c0fa97 PW |
3327 | uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize); |
3328 | unsigned int nChecksum = 0; | |
3329 | memcpy(&nChecksum, &hash, sizeof(nChecksum)); | |
3330 | if (nChecksum != hdr.nChecksum) | |
e89b9f6a | 3331 | { |
ea591ead | 3332 | printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n", |
18c0fa97 PW |
3333 | strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum); |
3334 | continue; | |
e89b9f6a PW |
3335 | } |
3336 | ||
3337 | // Copy message to its own buffer | |
3338 | CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion); | |
3339 | vRecv.ignore(nMessageSize); | |
3340 | ||
3341 | // Process message | |
3342 | bool fRet = false; | |
3343 | try | |
3344 | { | |
f8dcd5ca PW |
3345 | { |
3346 | LOCK(cs_main); | |
e89b9f6a | 3347 | fRet = ProcessMessage(pfrom, strCommand, vMsg); |
f8dcd5ca | 3348 | } |
e89b9f6a PW |
3349 | if (fShutdown) |
3350 | return true; | |
3351 | } | |
3352 | catch (std::ios_base::failure& e) | |
3353 | { | |
3354 | if (strstr(e.what(), "end of data")) | |
3355 | { | |
814efd6f | 3356 | // Allow exceptions from under-length message on vRecv |
ea591ead | 3357 | printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught, normally caused by a message being shorter than its stated length\n", strCommand.c_str(), nMessageSize, e.what()); |
e89b9f6a PW |
3358 | } |
3359 | else if (strstr(e.what(), "size too large")) | |
3360 | { | |
814efd6f | 3361 | // Allow exceptions from over-long size |
ea591ead | 3362 | printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what()); |
e89b9f6a PW |
3363 | } |
3364 | else | |
3365 | { | |
ea591ead | 3366 | PrintExceptionContinue(&e, "ProcessMessages()"); |
e89b9f6a PW |
3367 | } |
3368 | } | |
3369 | catch (std::exception& e) { | |
ea591ead | 3370 | PrintExceptionContinue(&e, "ProcessMessages()"); |
e89b9f6a | 3371 | } catch (...) { |
ea591ead | 3372 | PrintExceptionContinue(NULL, "ProcessMessages()"); |
e89b9f6a PW |
3373 | } |
3374 | ||
3375 | if (!fRet) | |
3376 | printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize); | |
3377 | } | |
3378 | ||
3379 | vRecv.Compact(); | |
3380 | return true; | |
3381 | } | |
0a61b0df | 3382 | |
3383 | ||
0a61b0df | 3384 | bool SendMessages(CNode* pto, bool fSendTrickle) |
3385 | { | |
c581cc16 PW |
3386 | TRY_LOCK(cs_main, lockMain); |
3387 | if (lockMain) { | |
0a61b0df | 3388 | // Don't send anything until we get their version message |
3389 | if (pto->nVersion == 0) | |
3390 | return true; | |
3391 | ||
6d64a0bf | 3392 | // Keep-alive ping. We send a nonce of zero because we don't use it anywhere |
93e447b6 JG |
3393 | // right now. |
3394 | if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty()) { | |
c971112d | 3395 | uint64 nonce = 0; |
93e447b6 | 3396 | if (pto->nVersion > BIP0031_VERSION) |
c971112d | 3397 | pto->PushMessage("ping", nonce); |
93e447b6 JG |
3398 | else |
3399 | pto->PushMessage("ping"); | |
3400 | } | |
0a61b0df | 3401 | |
c891967b | 3402 | // Resend wallet transactions that haven't gotten in a block yet |
3403 | ResendWalletTransactions(); | |
3404 | ||
0a61b0df | 3405 | // Address refresh broadcast |
bde280b9 | 3406 | static int64 nLastRebroadcast; |
5d1b8f17 | 3407 | if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60)) |
0a61b0df | 3408 | { |
0a61b0df | 3409 | { |
f8dcd5ca | 3410 | LOCK(cs_vNodes); |
223b6f1b | 3411 | BOOST_FOREACH(CNode* pnode, vNodes) |
0a61b0df | 3412 | { |
3413 | // Periodically clear setAddrKnown to allow refresh broadcasts | |
5d1b8f17 GM |
3414 | if (nLastRebroadcast) |
3415 | pnode->setAddrKnown.clear(); | |
0a61b0df | 3416 | |
3417 | // Rebroadcast our address | |
587f929c | 3418 | if (!fNoListen) |
c891967b | 3419 | { |
39857190 PW |
3420 | CAddress addr = GetLocalAddress(&pnode->addr); |
3421 | if (addr.IsRoutable()) | |
3422 | pnode->PushAddress(addr); | |
c891967b | 3423 | } |
0a61b0df | 3424 | } |
3425 | } | |
5d1b8f17 | 3426 | nLastRebroadcast = GetTime(); |
0a61b0df | 3427 | } |
3428 | ||
0a61b0df | 3429 | // |
3430 | // Message: addr | |
3431 | // | |
3432 | if (fSendTrickle) | |
3433 | { | |
3434 | vector<CAddress> vAddr; | |
3435 | vAddr.reserve(pto->vAddrToSend.size()); | |
223b6f1b | 3436 | BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend) |
0a61b0df | 3437 | { |
3438 | // returns true if wasn't already contained in the set | |
3439 | if (pto->setAddrKnown.insert(addr).second) | |
3440 | { | |
3441 | vAddr.push_back(addr); | |
3442 | // receiver rejects addr messages larger than 1000 | |
3443 | if (vAddr.size() >= 1000) | |
3444 | { | |
3445 | pto->PushMessage("addr", vAddr); | |
3446 | vAddr.clear(); | |
3447 | } | |
3448 | } | |
3449 | } | |
3450 | pto->vAddrToSend.clear(); | |
3451 | if (!vAddr.empty()) | |
3452 | pto->PushMessage("addr", vAddr); | |
3453 | } | |
3454 | ||
3455 | ||
3456 | // | |
3457 | // Message: inventory | |
3458 | // | |
3459 | vector<CInv> vInv; | |
3460 | vector<CInv> vInvWait; | |
0a61b0df | 3461 | { |
f8dcd5ca | 3462 | LOCK(pto->cs_inventory); |
0a61b0df | 3463 | vInv.reserve(pto->vInventoryToSend.size()); |
3464 | vInvWait.reserve(pto->vInventoryToSend.size()); | |
223b6f1b | 3465 | BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend) |
0a61b0df | 3466 | { |
3467 | if (pto->setInventoryKnown.count(inv)) | |
3468 | continue; | |
3469 | ||
3470 | // trickle out tx inv to protect privacy | |
3471 | if (inv.type == MSG_TX && !fSendTrickle) | |
3472 | { | |
3473 | // 1/4 of tx invs blast to all immediately | |
3474 | static uint256 hashSalt; | |
3475 | if (hashSalt == 0) | |
f718aedd | 3476 | hashSalt = GetRandHash(); |
0a61b0df | 3477 | uint256 hashRand = inv.hash ^ hashSalt; |
3478 | hashRand = Hash(BEGIN(hashRand), END(hashRand)); | |
3479 | bool fTrickleWait = ((hashRand & 3) != 0); | |
3480 | ||
3481 | // always trickle our own transactions | |
3482 | if (!fTrickleWait) | |
3483 | { | |
64c7ee7e PW |
3484 | CWalletTx wtx; |
3485 | if (GetTransaction(inv.hash, wtx)) | |
3486 | if (wtx.fFromMe) | |
3487 | fTrickleWait = true; | |
0a61b0df | 3488 | } |
3489 | ||
3490 | if (fTrickleWait) | |
3491 | { | |
3492 | vInvWait.push_back(inv); | |
3493 | continue; | |
3494 | } | |
3495 | } | |
3496 | ||
3497 | // returns true if wasn't already contained in the set | |
3498 | if (pto->setInventoryKnown.insert(inv).second) | |
3499 | { | |
3500 | vInv.push_back(inv); | |
3501 | if (vInv.size() >= 1000) | |
3502 | { | |
3503 | pto->PushMessage("inv", vInv); | |
3504 | vInv.clear(); | |
3505 | } | |
3506 | } | |
3507 | } | |
3508 | pto->vInventoryToSend = vInvWait; | |
3509 | } | |
3510 | if (!vInv.empty()) | |
3511 | pto->PushMessage("inv", vInv); | |
3512 | ||
3513 | ||
3514 | // | |
3515 | // Message: getdata | |
3516 | // | |
3517 | vector<CInv> vGetData; | |
bde280b9 | 3518 | int64 nNow = GetTime() * 1000000; |
0a61b0df | 3519 | while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow) |
3520 | { | |
3521 | const CInv& inv = (*pto->mapAskFor.begin()).second; | |
ae8bfd12 | 3522 | if (!AlreadyHave(inv)) |
0a61b0df | 3523 | { |
d07eaba1 JG |
3524 | if (fDebugNet) |
3525 | printf("sending getdata: %s\n", inv.ToString().c_str()); | |
0a61b0df | 3526 | vGetData.push_back(inv); |
3527 | if (vGetData.size() >= 1000) | |
3528 | { | |
3529 | pto->PushMessage("getdata", vGetData); | |
3530 | vGetData.clear(); | |
3531 | } | |
757cec9d | 3532 | mapAlreadyAskedFor[inv] = nNow; |
0a61b0df | 3533 | } |
3534 | pto->mapAskFor.erase(pto->mapAskFor.begin()); | |
3535 | } | |
3536 | if (!vGetData.empty()) | |
3537 | pto->PushMessage("getdata", vGetData); | |
3538 | ||
3539 | } | |
3540 | return true; | |
3541 | } | |
3542 | ||
3543 | ||
3544 | ||
3545 | ||
3546 | ||
3547 | ||
3548 | ||
3549 | ||
3550 | ||
3551 | ||
3552 | ||
3553 | ||
3554 | ||
3555 | ||
3556 | ////////////////////////////////////////////////////////////////////////////// | |
3557 | // | |
3558 | // BitcoinMiner | |
3559 | // | |
3560 | ||
64c7ee7e | 3561 | int static FormatHashBlocks(void* pbuffer, unsigned int len) |
3df62878 | 3562 | { |
3563 | unsigned char* pdata = (unsigned char*)pbuffer; | |
3564 | unsigned int blocks = 1 + ((len + 8) / 64); | |
3565 | unsigned char* pend = pdata + 64 * blocks; | |
3566 | memset(pdata + len, 0, 64 * blocks - len); | |
3567 | pdata[len] = 0x80; | |
3568 | unsigned int bits = len * 8; | |
3569 | pend[-1] = (bits >> 0) & 0xff; | |
3570 | pend[-2] = (bits >> 8) & 0xff; | |
3571 | pend[-3] = (bits >> 16) & 0xff; | |
3572 | pend[-4] = (bits >> 24) & 0xff; | |
3573 | return blocks; | |
3574 | } | |
3575 | ||
3df62878 | 3576 | static const unsigned int pSHA256InitState[8] = |
3577 | {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19}; | |
3578 | ||
6ccff2cb | 3579 | void SHA256Transform(void* pstate, void* pinput, const void* pinit) |
3df62878 | 3580 | { |
6ccff2cb NS |
3581 | SHA256_CTX ctx; |
3582 | unsigned char data[64]; | |
3583 | ||
3584 | SHA256_Init(&ctx); | |
3585 | ||
3586 | for (int i = 0; i < 16; i++) | |
3587 | ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]); | |
3588 | ||
3589 | for (int i = 0; i < 8; i++) | |
3590 | ctx.h[i] = ((uint32_t*)pinit)[i]; | |
3591 | ||
3592 | SHA256_Update(&ctx, data, sizeof(data)); | |
6d64a0bf | 3593 | for (int i = 0; i < 8; i++) |
6ccff2cb | 3594 | ((uint32_t*)pstate)[i] = ctx.h[i]; |
3df62878 | 3595 | } |
3596 | ||
3597 | // | |
3598 | // ScanHash scans nonces looking for a hash with at least some zero bits. | |
3599 | // It operates on big endian data. Caller does the byte reversing. | |
3600 | // All input buffers are 16-byte aligned. nNonce is usually preserved | |
776d0f34 | 3601 | // between calls, but periodically or if nNonce is 0xffff0000 or above, |
3df62878 | 3602 | // the block is rebuilt and nNonce starts over at zero. |
3603 | // | |
64c7ee7e | 3604 | unsigned int static ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone) |
3df62878 | 3605 | { |
776d0f34 | 3606 | unsigned int& nNonce = *(unsigned int*)(pdata + 12); |
3df62878 | 3607 | for (;;) |
3608 | { | |
814efd6f | 3609 | // Crypto++ SHA256 |
776d0f34 | 3610 | // Hash pdata using pmidstate as the starting state into |
814efd6f | 3611 | // pre-formatted buffer phash1, then hash phash1 into phash |
3df62878 | 3612 | nNonce++; |
776d0f34 | 3613 | SHA256Transform(phash1, pdata, pmidstate); |
3df62878 | 3614 | SHA256Transform(phash, phash1, pSHA256InitState); |
3615 | ||
3616 | // Return the nonce if the hash has at least some zero bits, | |
3617 | // caller will check if it has enough to reach the target | |
3618 | if (((unsigned short*)phash)[14] == 0) | |
3619 | return nNonce; | |
3620 | ||
3621 | // If nothing found after trying for a while, return -1 | |
3622 | if ((nNonce & 0xffff) == 0) | |
3623 | { | |
3624 | nHashesDone = 0xffff+1; | |
1d8c7a95 | 3625 | return (unsigned int) -1; |
3df62878 | 3626 | } |
3627 | } | |
3628 | } | |
3629 | ||
d0d9486f | 3630 | // Some explaining would be appreciated |
683bcb91 | 3631 | class COrphan |
3632 | { | |
3633 | public: | |
3634 | CTransaction* ptx; | |
3635 | set<uint256> setDependsOn; | |
3636 | double dPriority; | |
c555400c | 3637 | double dFeePerKb; |
683bcb91 | 3638 | |
3639 | COrphan(CTransaction* ptxIn) | |
3640 | { | |
3641 | ptx = ptxIn; | |
c555400c | 3642 | dPriority = dFeePerKb = 0; |
683bcb91 | 3643 | } |
3644 | ||
3645 | void print() const | |
3646 | { | |
c555400c GA |
3647 | printf("COrphan(hash=%s, dPriority=%.1f, dFeePerKb=%.1f)\n", |
3648 | ptx->GetHash().ToString().substr(0,10).c_str(), dPriority, dFeePerKb); | |
223b6f1b | 3649 | BOOST_FOREACH(uint256 hash, setDependsOn) |
683bcb91 | 3650 | printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str()); |
3651 | } | |
3652 | }; | |
3653 | ||
3654 | ||
340f0876 LD |
3655 | uint64 nLastBlockTx = 0; |
3656 | uint64 nLastBlockSize = 0; | |
3657 | ||
c555400c GA |
3658 | // We want to sort transactions by priority and fee, so: |
3659 | typedef boost::tuple<double, double, CTransaction*> TxPriority; | |
3660 | class TxPriorityCompare | |
3661 | { | |
3662 | bool byFee; | |
3663 | public: | |
3664 | TxPriorityCompare(bool _byFee) : byFee(_byFee) { } | |
3665 | bool operator()(const TxPriority& a, const TxPriority& b) | |
3666 | { | |
3667 | if (byFee) | |
3668 | { | |
3669 | if (a.get<1>() == b.get<1>()) | |
3670 | return a.get<0>() < b.get<0>(); | |
3671 | return a.get<1>() < b.get<1>(); | |
3672 | } | |
3673 | else | |
3674 | { | |
3675 | if (a.get<0>() == b.get<0>()) | |
3676 | return a.get<1>() < b.get<1>(); | |
3677 | return a.get<0>() < b.get<0>(); | |
3678 | } | |
3679 | } | |
3680 | }; | |
3681 | ||
776d0f34 | 3682 | CBlock* CreateNewBlock(CReserveKey& reservekey) |
3683 | { | |
776d0f34 | 3684 | |
3685 | // Create new block | |
3686 | auto_ptr<CBlock> pblock(new CBlock()); | |
3687 | if (!pblock.get()) | |
3688 | return NULL; | |
3689 | ||
3690 | // Create coinbase tx | |
3691 | CTransaction txNew; | |
3692 | txNew.vin.resize(1); | |
3693 | txNew.vin[0].prevout.SetNull(); | |
3694 | txNew.vout.resize(1); | |
3695 | txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG; | |
3696 | ||
3697 | // Add our coinbase tx as first transaction | |
3698 | pblock->vtx.push_back(txNew); | |
3699 | ||
c555400c GA |
3700 | // Largest block you're willing to create: |
3701 | unsigned int nBlockMaxSize = GetArg("-blockmaxsize", MAX_BLOCK_SIZE_GEN/2); | |
3702 | // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity: | |
3703 | nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize)); | |
3704 | ||
3705 | // How much of the block should be dedicated to high-priority transactions, | |
3706 | // included regardless of the fees they pay | |
3707 | unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", 27000); | |
3708 | nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize); | |
3709 | ||
3710 | // Minimum block size you want to create; block will be filled with free transactions | |
3711 | // until there are no more or the block reaches this size: | |
3712 | unsigned int nBlockMinSize = GetArg("-blockminsize", 0); | |
3713 | nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize); | |
3714 | ||
3715 | // Fee-per-kilobyte amount considered the same as "free" | |
3716 | // Be careful setting this: if you set it to zero then | |
3717 | // a transaction spammer can cheaply fill blocks using | |
3718 | // 1-satoshi-fee transactions. It should be set above the real | |
3719 | // cost to you of processing a transaction. | |
3720 | int64 nMinTxFee = MIN_TX_FEE; | |
3721 | if (mapArgs.count("-mintxfee")) | |
3722 | ParseMoney(mapArgs["-mintxfee"], nMinTxFee); | |
3723 | ||
776d0f34 | 3724 | // Collect memory pool transactions into the block |
bde280b9 | 3725 | int64 nFees = 0; |
776d0f34 | 3726 | { |
235507ae | 3727 | LOCK2(cs_main, mempool.cs); |
faff50d1 | 3728 | CBlockIndex* pindexPrev = pindexBest; |
ae8bfd12 | 3729 | CCoinsViewCache view(*pcoinsTip, true); |
776d0f34 | 3730 | |
3731 | // Priority order to process transactions | |
3732 | list<COrphan> vOrphan; // list memory doesn't move | |
3733 | map<uint256, vector<COrphan*> > mapDependers; | |
c555400c GA |
3734 | |
3735 | // This vector will be sorted into a priority queue: | |
3736 | vector<TxPriority> vecPriority; | |
3737 | vecPriority.reserve(mempool.mapTx.size()); | |
235507ae | 3738 | for (map<uint256, CTransaction>::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi) |
776d0f34 | 3739 | { |
3740 | CTransaction& tx = (*mi).second; | |
3741 | if (tx.IsCoinBase() || !tx.IsFinal()) | |
3742 | continue; | |
3743 | ||
3744 | COrphan* porphan = NULL; | |
3745 | double dPriority = 0; | |
c555400c | 3746 | int64 nTotalIn = 0; |
e0e54740 | 3747 | bool fMissingInputs = false; |
223b6f1b | 3748 | BOOST_FOREACH(const CTxIn& txin, tx.vin) |
776d0f34 | 3749 | { |
3750 | // Read prev transaction | |
450cbb09 PW |
3751 | CCoins coins; |
3752 | if (!view.GetCoins(txin.prevout.hash, coins)) | |
776d0f34 | 3753 | { |
e0e54740 GA |
3754 | // This should never happen; all transactions in the memory |
3755 | // pool should connect to either transactions in the chain | |
3756 | // or other transactions in the memory pool. | |
3757 | if (!mempool.mapTx.count(txin.prevout.hash)) | |
3758 | { | |
3759 | printf("ERROR: mempool transaction missing input\n"); | |
3760 | if (fDebug) assert("mempool transaction missing input" == 0); | |
3761 | fMissingInputs = true; | |
3762 | if (porphan) | |
3763 | vOrphan.pop_back(); | |
3764 | break; | |
3765 | } | |
3766 | ||
776d0f34 | 3767 | // Has to wait for dependencies |
3768 | if (!porphan) | |
3769 | { | |
3770 | // Use list for automatic deletion | |
3771 | vOrphan.push_back(COrphan(&tx)); | |
3772 | porphan = &vOrphan.back(); | |
3773 | } | |
3774 | mapDependers[txin.prevout.hash].push_back(porphan); | |
3775 | porphan->setDependsOn.insert(txin.prevout.hash); | |
c555400c | 3776 | nTotalIn += mempool.mapTx[txin.prevout.hash].vout[txin.prevout.n].nValue; |
776d0f34 | 3777 | continue; |
3778 | } | |
450cbb09 PW |
3779 | |
3780 | int64 nValueIn = coins.vout[txin.prevout.n].nValue; | |
c555400c | 3781 | nTotalIn += nValueIn; |
776d0f34 | 3782 | |
1e64c2d5 | 3783 | int nConf = pindexPrev->nHeight - coins.nHeight + 1; |
450cbb09 | 3784 | |
776d0f34 | 3785 | dPriority += (double)nValueIn * nConf; |
776d0f34 | 3786 | } |
e0e54740 | 3787 | if (fMissingInputs) continue; |
776d0f34 | 3788 | |
3789 | // Priority is sum(valuein * age) / txsize | |
c555400c GA |
3790 | unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION); |
3791 | dPriority /= nTxSize; | |
776d0f34 | 3792 | |
c555400c GA |
3793 | // This is a more accurate fee-per-kilobyte than is used by the client code, because the |
3794 | // client code rounds up the size to the nearest 1K. That's good, because it gives an | |
3795 | // incentive to create smaller transactions. | |
3796 | double dFeePerKb = double(nTotalIn-tx.GetValueOut()) / (double(nTxSize)/1000.0); | |
776d0f34 | 3797 | |
c555400c | 3798 | if (porphan) |
776d0f34 | 3799 | { |
c555400c GA |
3800 | porphan->dPriority = dPriority; |
3801 | porphan->dFeePerKb = dFeePerKb; | |
776d0f34 | 3802 | } |
c555400c GA |
3803 | else |
3804 | vecPriority.push_back(TxPriority(dPriority, dFeePerKb, &(*mi).second)); | |
776d0f34 | 3805 | } |
3806 | ||
3807 | // Collect transactions into block | |
bde280b9 | 3808 | uint64 nBlockSize = 1000; |
340f0876 | 3809 | uint64 nBlockTx = 0; |
137d0685 | 3810 | int nBlockSigOps = 100; |
c555400c GA |
3811 | bool fSortedByFee = (nBlockPrioritySize <= 0); |
3812 | ||
3813 | TxPriorityCompare comparer(fSortedByFee); | |
3814 | std::make_heap(vecPriority.begin(), vecPriority.end(), comparer); | |
3815 | ||
3816 | while (!vecPriority.empty()) | |
776d0f34 | 3817 | { |
c555400c GA |
3818 | // Take highest priority transaction off the priority queue: |
3819 | double dPriority = vecPriority.front().get<0>(); | |
3820 | double dFeePerKb = vecPriority.front().get<1>(); | |
3821 | CTransaction& tx = *(vecPriority.front().get<2>()); | |
3822 | ||
3823 | std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer); | |
3824 | vecPriority.pop_back(); | |
776d0f34 | 3825 | |
450cbb09 PW |
3826 | // second layer cached modifications just for this transaction |
3827 | CCoinsViewCache viewTemp(view, true); | |
3828 | ||
776d0f34 | 3829 | // Size limits |
6b6aaa16 | 3830 | unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION); |
c555400c | 3831 | if (nBlockSize + nTxSize >= nBlockMaxSize) |
776d0f34 | 3832 | continue; |
776d0f34 | 3833 | |
922e8e29 | 3834 | // Legacy limits on sigOps: |
7bd9c3a3 | 3835 | unsigned int nTxSigOps = tx.GetLegacySigOpCount(); |
137d0685 | 3836 | if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS) |
922e8e29 GA |
3837 | continue; |
3838 | ||
c555400c GA |
3839 | // Skip free transactions if we're past the minimum block size: |
3840 | if (fSortedByFee && (dFeePerKb < nMinTxFee) && (nBlockSize + nTxSize >= nBlockMinSize)) | |
3841 | continue; | |
3842 | ||
3843 | // Prioritize by fee once past the priority size or we run out of high-priority | |
3844 | // transactions: | |
3845 | if (!fSortedByFee && | |
3846 | ((nBlockSize + nTxSize >= nBlockPrioritySize) || (dPriority < COIN * 144 / 250))) | |
3847 | { | |
3848 | fSortedByFee = true; | |
3849 | comparer = TxPriorityCompare(fSortedByFee); | |
3850 | std::make_heap(vecPriority.begin(), vecPriority.end(), comparer); | |
3851 | } | |
776d0f34 | 3852 | |
13c51f20 | 3853 | if (!tx.HaveInputs(viewTemp)) |
e679ec96 | 3854 | continue; |
922e8e29 | 3855 | |
450cbb09 | 3856 | int64 nTxFees = tx.GetValueIn(viewTemp)-tx.GetValueOut(); |
8d7849b6 | 3857 | |
450cbb09 | 3858 | nTxSigOps += tx.GetP2SHSigOpCount(viewTemp); |
137d0685 | 3859 | if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS) |
776d0f34 | 3860 | continue; |
8d7849b6 | 3861 | |
99d0d0f3 | 3862 | if (!tx.CheckInputs(viewTemp, CS_ALWAYS, SCRIPT_VERIFY_P2SH)) |
13c51f20 PW |
3863 | continue; |
3864 | ||
450cbb09 | 3865 | CTxUndo txundo; |
64dd46fd PW |
3866 | uint256 hash = tx.GetHash(); |
3867 | if (!tx.UpdateCoins(viewTemp, txundo, pindexPrev->nHeight+1, hash)) | |
8d7849b6 | 3868 | continue; |
450cbb09 PW |
3869 | |
3870 | // push changes from the second layer cache to the first one | |
3871 | viewTemp.Flush(); | |
776d0f34 | 3872 | |
3873 | // Added | |
3874 | pblock->vtx.push_back(tx); | |
3875 | nBlockSize += nTxSize; | |
340f0876 | 3876 | ++nBlockTx; |
137d0685 | 3877 | nBlockSigOps += nTxSigOps; |
68649bef | 3878 | nFees += nTxFees; |
776d0f34 | 3879 | |
c555400c GA |
3880 | if (fDebug && GetBoolArg("-printpriority")) |
3881 | { | |
3882 | printf("priority %.1f feeperkb %.1f txid %s\n", | |
3883 | dPriority, dFeePerKb, tx.GetHash().ToString().c_str()); | |
3884 | } | |
3885 | ||
776d0f34 | 3886 | // Add transactions that depend on this one to the priority queue |
776d0f34 | 3887 | if (mapDependers.count(hash)) |
3888 | { | |
223b6f1b | 3889 | BOOST_FOREACH(COrphan* porphan, mapDependers[hash]) |
776d0f34 | 3890 | { |
3891 | if (!porphan->setDependsOn.empty()) | |
3892 | { | |
3893 | porphan->setDependsOn.erase(hash); | |
3894 | if (porphan->setDependsOn.empty()) | |
c555400c GA |
3895 | { |
3896 | vecPriority.push_back(TxPriority(porphan->dPriority, porphan->dFeePerKb, porphan->ptx)); | |
3897 | std::push_heap(vecPriority.begin(), vecPriority.end(), comparer); | |
3898 | } | |
776d0f34 | 3899 | } |
3900 | } | |
3901 | } | |
3902 | } | |
340f0876 LD |
3903 | |
3904 | nLastBlockTx = nBlockTx; | |
3905 | nLastBlockSize = nBlockSize; | |
d210f4f5 | 3906 | printf("CreateNewBlock(): total size %"PRI64u"\n", nBlockSize); |
340f0876 | 3907 | |
450cbb09 | 3908 | pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees); |
776d0f34 | 3909 | |
450cbb09 PW |
3910 | // Fill in header |
3911 | pblock->hashPrevBlock = pindexPrev->GetBlockHash(); | |
3912 | pblock->UpdateTime(pindexPrev); | |
3913 | pblock->nBits = GetNextWorkRequired(pindexPrev, pblock.get()); | |
3914 | pblock->nNonce = 0; | |
4fbad912 | 3915 | pblock->vtx[0].vin[0].scriptSig = CScript() << OP_0 << OP_0; |
450cbb09 | 3916 | |
630fd8dc | 3917 | CBlockIndex indexDummy(*pblock); |
3cd01fdf LD |
3918 | indexDummy.pprev = pindexPrev; |
3919 | indexDummy.nHeight = pindexPrev->nHeight + 1; | |
ae8bfd12 | 3920 | CCoinsViewCache viewNew(*pcoinsTip, true); |
450cbb09 | 3921 | if (!pblock->ConnectBlock(&indexDummy, viewNew, true)) |
3cd01fdf LD |
3922 | throw std::runtime_error("CreateNewBlock() : ConnectBlock failed"); |
3923 | } | |
3924 | ||
776d0f34 | 3925 | return pblock.release(); |
3926 | } | |
3927 | ||
3928 | ||
83f4cd15 | 3929 | void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce) |
776d0f34 | 3930 | { |
3931 | // Update nExtraNonce | |
02d87b3a LD |
3932 | static uint256 hashPrevBlock; |
3933 | if (hashPrevBlock != pblock->hashPrevBlock) | |
776d0f34 | 3934 | { |
02d87b3a LD |
3935 | nExtraNonce = 0; |
3936 | hashPrevBlock = pblock->hashPrevBlock; | |
776d0f34 | 3937 | } |
02d87b3a | 3938 | ++nExtraNonce; |
de237cbf GA |
3939 | unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2 |
3940 | pblock->vtx[0].vin[0].scriptSig = (CScript() << nHeight << CBigNum(nExtraNonce)) + COINBASE_FLAGS; | |
d7062ef1 GA |
3941 | assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100); |
3942 | ||
776d0f34 | 3943 | pblock->hashMerkleRoot = pblock->BuildMerkleTree(); |
3944 | } | |
3945 | ||
3946 | ||
3947 | void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1) | |
3948 | { | |
3949 | // | |
814efd6f | 3950 | // Pre-build hash buffers |
776d0f34 | 3951 | // |
3952 | struct | |
3953 | { | |
3954 | struct unnamed2 | |
3955 | { | |
3956 | int nVersion; | |
3957 | uint256 hashPrevBlock; | |
3958 | uint256 hashMerkleRoot; | |
3959 | unsigned int nTime; | |
3960 | unsigned int nBits; | |
3961 | unsigned int nNonce; | |
3962 | } | |
3963 | block; | |
3964 | unsigned char pchPadding0[64]; | |
3965 | uint256 hash1; | |
3966 | unsigned char pchPadding1[64]; | |
3967 | } | |
3968 | tmp; | |
3969 | memset(&tmp, 0, sizeof(tmp)); | |
3970 | ||
3971 | tmp.block.nVersion = pblock->nVersion; | |
3972 | tmp.block.hashPrevBlock = pblock->hashPrevBlock; | |
3973 | tmp.block.hashMerkleRoot = pblock->hashMerkleRoot; | |
3974 | tmp.block.nTime = pblock->nTime; | |
3975 | tmp.block.nBits = pblock->nBits; | |
3976 | tmp.block.nNonce = pblock->nNonce; | |
3977 | ||
3978 | FormatHashBlocks(&tmp.block, sizeof(tmp.block)); | |
3979 | FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1)); | |
3980 | ||
3981 | // Byte swap all the input buffer | |
c376ac35 | 3982 | for (unsigned int i = 0; i < sizeof(tmp)/4; i++) |
776d0f34 | 3983 | ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]); |
3984 | ||
3985 | // Precalc the first half of the first hash, which stays constant | |
3986 | SHA256Transform(pmidstate, &tmp.block, pSHA256InitState); | |
3987 | ||
3988 | memcpy(pdata, &tmp.block, 128); | |
3989 | memcpy(phash1, &tmp.hash1, 64); | |
3990 | } | |
3991 | ||
3992 | ||
64c7ee7e | 3993 | bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey) |
776d0f34 | 3994 | { |
3995 | uint256 hash = pblock->GetHash(); | |
3996 | uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); | |
3997 | ||
3998 | if (hash > hashTarget) | |
3999 | return false; | |
4000 | ||
4001 | //// debug print | |
4002 | printf("BitcoinMiner:\n"); | |
4003 | printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str()); | |
4004 | pblock->print(); | |
776d0f34 | 4005 | printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str()); |
4006 | ||
4007 | // Found a solution | |
776d0f34 | 4008 | { |
f8dcd5ca | 4009 | LOCK(cs_main); |
776d0f34 | 4010 | if (pblock->hashPrevBlock != hashBestChain) |
4011 | return error("BitcoinMiner : generated block is stale"); | |
4012 | ||
4013 | // Remove key from key pool | |
4014 | reservekey.KeepKey(); | |
4015 | ||
4016 | // Track how many getdata requests this block gets | |
f8dcd5ca PW |
4017 | { |
4018 | LOCK(wallet.cs_wallet); | |
64c7ee7e | 4019 | wallet.mapRequestCount[pblock->GetHash()] = 0; |
f8dcd5ca | 4020 | } |
776d0f34 | 4021 | |
4022 | // Process this block the same as if we had received it from another node | |
4023 | if (!ProcessBlock(NULL, pblock)) | |
4024 | return error("BitcoinMiner : ProcessBlock, block not accepted"); | |
4025 | } | |
4026 | ||
776d0f34 | 4027 | return true; |
4028 | } | |
4029 | ||
64c7ee7e PW |
4030 | void static ThreadBitcoinMiner(void* parg); |
4031 | ||
972060ce GA |
4032 | static bool fGenerateBitcoins = false; |
4033 | static bool fLimitProcessors = false; | |
4034 | static int nLimitProcessors = -1; | |
4035 | ||
64c7ee7e | 4036 | void static BitcoinMiner(CWallet *pwallet) |
0a61b0df | 4037 | { |
4038 | printf("BitcoinMiner started\n"); | |
4039 | SetThreadPriority(THREAD_PRIORITY_LOWEST); | |
4040 | ||
96931d6f | 4041 | // Make this thread recognisable as the mining thread |
9f46ab62 | 4042 | RenameThread("bitcoin-miner"); |
96931d6f | 4043 | |
776d0f34 | 4044 | // Each thread has its own key and counter |
64c7ee7e | 4045 | CReserveKey reservekey(pwallet); |
5cbf7532 | 4046 | unsigned int nExtraNonce = 0; |
776d0f34 | 4047 | |
0a61b0df | 4048 | while (fGenerateBitcoins) |
4049 | { | |
0a61b0df | 4050 | if (fShutdown) |
4051 | return; | |
4052 | while (vNodes.empty() || IsInitialBlockDownload()) | |
4053 | { | |
4054 | Sleep(1000); | |
4055 | if (fShutdown) | |
4056 | return; | |
4057 | if (!fGenerateBitcoins) | |
4058 | return; | |
4059 | } | |
4060 | ||
0a61b0df | 4061 | |
4062 | // | |
4063 | // Create new block | |
4064 | // | |
776d0f34 | 4065 | unsigned int nTransactionsUpdatedLast = nTransactionsUpdated; |
4066 | CBlockIndex* pindexPrev = pindexBest; | |
4067 | ||
4068 | auto_ptr<CBlock> pblock(CreateNewBlock(reservekey)); | |
0a61b0df | 4069 | if (!pblock.get()) |
4070 | return; | |
83f4cd15 | 4071 | IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce); |
0a61b0df | 4072 | |
d210f4f5 | 4073 | printf("Running BitcoinMiner with %"PRIszu" transactions in block (%u bytes)\n", pblock->vtx.size(), |
c555400c | 4074 | ::GetSerializeSize(*pblock, SER_NETWORK, PROTOCOL_VERSION)); |
0a61b0df | 4075 | |
4076 | ||
4077 | // | |
814efd6f | 4078 | // Pre-build hash buffers |
0a61b0df | 4079 | // |
776d0f34 | 4080 | char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf); |
4081 | char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf); | |
4082 | char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf); | |
4083 | ||
4084 | FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1); | |
4085 | ||
4086 | unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4); | |
0f8cb5db | 4087 | unsigned int& nBlockBits = *(unsigned int*)(pdata + 64 + 8); |
776d0f34 | 4088 | unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12); |
0a61b0df | 4089 | |
4090 | ||
4091 | // | |
4092 | // Search | |
4093 | // | |
bde280b9 | 4094 | int64 nStart = GetTime(); |
0a61b0df | 4095 | uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); |
4096 | uint256 hashbuf[2]; | |
4097 | uint256& hash = *alignup<16>(hashbuf); | |
4098 | loop | |
4099 | { | |
3df62878 | 4100 | unsigned int nHashesDone = 0; |
4101 | unsigned int nNonceFound; | |
4102 | ||
814efd6f | 4103 | // Crypto++ SHA256 |
b26141e2 JG |
4104 | nNonceFound = ScanHash_CryptoPP(pmidstate, pdata + 64, phash1, |
4105 | (char*)&hash, nHashesDone); | |
0a61b0df | 4106 | |
3df62878 | 4107 | // Check if something found |
1d8c7a95 | 4108 | if (nNonceFound != (unsigned int) -1) |
0a61b0df | 4109 | { |
c376ac35 | 4110 | for (unsigned int i = 0; i < sizeof(hash)/4; i++) |
0a61b0df | 4111 | ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]); |
4112 | ||
4113 | if (hash <= hashTarget) | |
4114 | { | |
3df62878 | 4115 | // Found a solution |
4116 | pblock->nNonce = ByteReverse(nNonceFound); | |
0a61b0df | 4117 | assert(hash == pblock->GetHash()); |
4118 | ||
0a61b0df | 4119 | SetThreadPriority(THREAD_PRIORITY_NORMAL); |
64c7ee7e | 4120 | CheckWork(pblock.get(), *pwalletMain, reservekey); |
0a61b0df | 4121 | SetThreadPriority(THREAD_PRIORITY_LOWEST); |
0a61b0df | 4122 | break; |
4123 | } | |
4124 | } | |
4125 | ||
3df62878 | 4126 | // Meter hashes/sec |
bde280b9 | 4127 | static int64 nHashCounter; |
3df62878 | 4128 | if (nHPSTimerStart == 0) |
0a61b0df | 4129 | { |
3df62878 | 4130 | nHPSTimerStart = GetTimeMillis(); |
4131 | nHashCounter = 0; | |
4132 | } | |
4133 | else | |
4134 | nHashCounter += nHashesDone; | |
4135 | if (GetTimeMillis() - nHPSTimerStart > 4000) | |
4136 | { | |
4137 | static CCriticalSection cs; | |
0a61b0df | 4138 | { |
f8dcd5ca | 4139 | LOCK(cs); |
3df62878 | 4140 | if (GetTimeMillis() - nHPSTimerStart > 4000) |
0a61b0df | 4141 | { |
3df62878 | 4142 | dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart); |
4143 | nHPSTimerStart = GetTimeMillis(); | |
4144 | nHashCounter = 0; | |
bde280b9 | 4145 | static int64 nLogTime; |
3df62878 | 4146 | if (GetTime() - nLogTime > 30 * 60) |
0a61b0df | 4147 | { |
3df62878 | 4148 | nLogTime = GetTime(); |
c59881ea | 4149 | printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[THREAD_MINER], dHashesPerSec/1000.0); |
0a61b0df | 4150 | } |
4151 | } | |
4152 | } | |
3df62878 | 4153 | } |
0a61b0df | 4154 | |
3df62878 | 4155 | // Check for stop or if block needs to be rebuilt |
4156 | if (fShutdown) | |
4157 | return; | |
4158 | if (!fGenerateBitcoins) | |
4159 | return; | |
c59881ea | 4160 | if (fLimitProcessors && vnThreadsRunning[THREAD_MINER] > nLimitProcessors) |
3df62878 | 4161 | return; |
4162 | if (vNodes.empty()) | |
4163 | break; | |
776d0f34 | 4164 | if (nBlockNonce >= 0xffff0000) |
3df62878 | 4165 | break; |
4166 | if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60) | |
4167 | break; | |
4168 | if (pindexPrev != pindexBest) | |
4169 | break; | |
0a61b0df | 4170 | |
3df62878 | 4171 | // Update nTime every few seconds |
0f8cb5db | 4172 | pblock->UpdateTime(pindexPrev); |
776d0f34 | 4173 | nBlockTime = ByteReverse(pblock->nTime); |
0f8cb5db GA |
4174 | if (fTestNet) |
4175 | { | |
4176 | // Changing pblock->nTime can change work required on testnet: | |
4177 | nBlockBits = ByteReverse(pblock->nBits); | |
4178 | hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); | |
4179 | } | |
0a61b0df | 4180 | } |
4181 | } | |
4182 | } | |
4183 | ||
64c7ee7e | 4184 | void static ThreadBitcoinMiner(void* parg) |
0a61b0df | 4185 | { |
64c7ee7e | 4186 | CWallet* pwallet = (CWallet*)parg; |
e89b9f6a | 4187 | try |
0a61b0df | 4188 | { |
c59881ea | 4189 | vnThreadsRunning[THREAD_MINER]++; |
64c7ee7e | 4190 | BitcoinMiner(pwallet); |
c59881ea | 4191 | vnThreadsRunning[THREAD_MINER]--; |
aca3f961 | 4192 | } |
e89b9f6a | 4193 | catch (std::exception& e) { |
c59881ea | 4194 | vnThreadsRunning[THREAD_MINER]--; |
e89b9f6a PW |
4195 | PrintException(&e, "ThreadBitcoinMiner()"); |
4196 | } catch (...) { | |
c59881ea | 4197 | vnThreadsRunning[THREAD_MINER]--; |
e89b9f6a | 4198 | PrintException(NULL, "ThreadBitcoinMiner()"); |
0a61b0df | 4199 | } |
e89b9f6a | 4200 | nHPSTimerStart = 0; |
c59881ea | 4201 | if (vnThreadsRunning[THREAD_MINER] == 0) |
e89b9f6a | 4202 | dHashesPerSec = 0; |
c59881ea | 4203 | printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[THREAD_MINER]); |
e2a186af | 4204 | } |
4205 | ||
0a61b0df | 4206 | |
64c7ee7e | 4207 | void GenerateBitcoins(bool fGenerate, CWallet* pwallet) |
0a61b0df | 4208 | { |
972060ce GA |
4209 | fGenerateBitcoins = fGenerate; |
4210 | nLimitProcessors = GetArg("-genproclimit", -1); | |
4211 | if (nLimitProcessors == 0) | |
4212 | fGenerateBitcoins = false; | |
4213 | fLimitProcessors = (nLimitProcessors != -1); | |
4214 | ||
4215 | if (fGenerate) | |
0a61b0df | 4216 | { |
e89b9f6a PW |
4217 | int nProcessors = boost::thread::hardware_concurrency(); |
4218 | printf("%d processors\n", nProcessors); | |
4219 | if (nProcessors < 1) | |
4220 | nProcessors = 1; | |
4221 | if (fLimitProcessors && nProcessors > nLimitProcessors) | |
4222 | nProcessors = nLimitProcessors; | |
c59881ea | 4223 | int nAddThreads = nProcessors - vnThreadsRunning[THREAD_MINER]; |
e89b9f6a PW |
4224 | printf("Starting %d BitcoinMiner threads\n", nAddThreads); |
4225 | for (int i = 0; i < nAddThreads; i++) | |
0a61b0df | 4226 | { |
4d1d94c5 WL |
4227 | if (!NewThread(ThreadBitcoinMiner, pwallet)) |
4228 | printf("Error: NewThread(ThreadBitcoinMiner) failed\n"); | |
e89b9f6a | 4229 | Sleep(10); |
0a61b0df | 4230 | } |
f5f1878b | 4231 | } |
0a61b0df | 4232 | } |
0fa593d0 PW |
4233 | |
4234 | // Amount compression: | |
4235 | // * If the amount is 0, output 0 | |
4236 | // * first, divide the amount (in base units) by the largest power of 10 possible; call the exponent e (e is max 9) | |
4237 | // * if e<9, the last digit of the resulting number cannot be 0; store it as d, and drop it (divide by 10) | |
4238 | // * call the result n | |
4239 | // * output 1 + 10*(9*n + d - 1) + e | |
4240 | // * if e==9, we only know the resulting number is not zero, so output 1 + 10*(n - 1) + 9 | |
4241 | // (this is decodable, as d is in [1-9] and e is in [0-9]) | |
4242 | ||
4243 | uint64 CTxOutCompressor::CompressAmount(uint64 n) | |
4244 | { | |
4245 | if (n == 0) | |
4246 | return 0; | |
4247 | int e = 0; | |
4248 | while (((n % 10) == 0) && e < 9) { | |
4249 | n /= 10; | |
4250 | e++; | |
4251 | } | |
4252 | if (e < 9) { | |
4253 | int d = (n % 10); | |
4254 | assert(d >= 1 && d <= 9); | |
4255 | n /= 10; | |
4256 | return 1 + (n*9 + d - 1)*10 + e; | |
4257 | } else { | |
4258 | return 1 + (n - 1)*10 + 9; | |
4259 | } | |
4260 | } | |
4261 | ||
4262 | uint64 CTxOutCompressor::DecompressAmount(uint64 x) | |
4263 | { | |
4264 | // x = 0 OR x = 1+10*(9*n + d - 1) + e OR x = 1+10*(n - 1) + 9 | |
4265 | if (x == 0) | |
4266 | return 0; | |
4267 | x--; | |
4268 | // x = 10*(9*n + d - 1) + e | |
4269 | int e = x % 10; | |
4270 | x /= 10; | |
4271 | uint64 n = 0; | |
4272 | if (e < 9) { | |
4273 | // x = 9*n + d - 1 | |
4274 | int d = (x % 9) + 1; | |
4275 | x /= 9; | |
4276 | // x = n | |
4277 | n = x*10 + d; | |
4278 | } else { | |
4279 | n = x+1; | |
4280 | } | |
4281 | while (e) { | |
4282 | n *= 10; | |
4283 | e--; | |
4284 | } | |
4285 | return n; | |
4286 | } |