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