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