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