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