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