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