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