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