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