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