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