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