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