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