Merge with Bitcoin v0.6.3
[novacoin.git] / src / wallet.cpp
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Copyright (c) 2011-2012 The PPCoin developers
4 // Distributed under the MIT/X11 software license, see the accompanying
5 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6
7 #include "wallet.h"
8 #include "walletdb.h"
9 #include "crypter.h"
10 #include "checkpoints.h"
11 #include "ui_interface.h"
12
13 using namespace std;
14
15
16 //////////////////////////////////////////////////////////////////////////////
17 //
18 // mapWallet
19 //
20
21 std::vector<unsigned char> CWallet::GenerateNewKey()
22 {
23     bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
24
25     RandAddSeedPerfmon();
26     CKey key;
27     key.MakeNewKey(fCompressed);
28
29     // Compressed public keys were introduced in version 0.6.0
30     if (fCompressed)
31         SetMinVersion(FEATURE_COMPRPUBKEY);
32
33     if (!AddKey(key))
34         throw std::runtime_error("CWallet::GenerateNewKey() : AddKey failed");
35     return key.GetPubKey();
36 }
37
38 bool CWallet::AddKey(const CKey& key)
39 {
40     if (!CCryptoKeyStore::AddKey(key))
41         return false;
42     if (!fFileBacked)
43         return true;
44     if (!IsCrypted())
45         return CWalletDB(strWalletFile).WriteKey(key.GetPubKey(), key.GetPrivKey());
46     return true;
47 }
48
49 bool CWallet::AddCryptedKey(const vector<unsigned char> &vchPubKey, const vector<unsigned char> &vchCryptedSecret)
50 {
51     if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
52         return false;
53     if (!fFileBacked)
54         return true;
55     {
56         LOCK(cs_wallet);
57         if (pwalletdbEncryption)
58             return pwalletdbEncryption->WriteCryptedKey(vchPubKey, vchCryptedSecret);
59         else
60             return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret);
61     }
62     return false;
63 }
64
65 bool CWallet::AddCScript(const CScript& redeemScript)
66 {
67     if (!CCryptoKeyStore::AddCScript(redeemScript))
68         return false;
69     if (!fFileBacked)
70         return true;
71     return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript);
72 }
73
74 // ppcoin: optional setting to create coinstake only when unlocked;
75 //         serves to disable the trivial sendmoney when OS account compromised
76 bool fWalletUnlockStakeOnly = false;
77
78 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
79 {
80     if (!IsLocked())
81         return false;
82
83     CCrypter crypter;
84     CKeyingMaterial vMasterKey;
85
86     {
87         LOCK(cs_wallet);
88         BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
89         {
90             if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
91                 return false;
92             if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
93                 return false;
94             if (CCryptoKeyStore::Unlock(vMasterKey))
95                 return true;
96         }
97     }
98     return false;
99 }
100
101 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
102 {
103     bool fWasLocked = IsLocked();
104
105     {
106         LOCK(cs_wallet);
107         Lock();
108
109         CCrypter crypter;
110         CKeyingMaterial vMasterKey;
111         BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
112         {
113             if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
114                 return false;
115             if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
116                 return false;
117             if (CCryptoKeyStore::Unlock(vMasterKey))
118             {
119                 int64 nStartTime = GetTimeMillis();
120                 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
121                 pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
122
123                 nStartTime = GetTimeMillis();
124                 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
125                 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
126
127                 if (pMasterKey.second.nDeriveIterations < 25000)
128                     pMasterKey.second.nDeriveIterations = 25000;
129
130                 printf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
131
132                 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
133                     return false;
134                 if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
135                     return false;
136                 CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
137                 if (fWasLocked)
138                     Lock();
139                 return true;
140             }
141         }
142     }
143
144     return false;
145 }
146
147 void CWallet::SetBestChain(const CBlockLocator& loc)
148 {
149     CWalletDB walletdb(strWalletFile);
150     walletdb.WriteBestBlock(loc);
151 }
152
153 // This class implements an addrIncoming entry that causes pre-0.4
154 // clients to crash on startup if reading a private-key-encrypted wallet.
155 class CCorruptAddress
156 {
157 public:
158     IMPLEMENT_SERIALIZE
159     (
160         if (nType & SER_DISK)
161             READWRITE(nVersion);
162     )
163 };
164
165 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
166 {
167     if (nWalletVersion >= nVersion)
168         return true;
169
170     // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
171     if (fExplicit && nVersion > nWalletMaxVersion)
172             nVersion = FEATURE_LATEST;
173
174     nWalletVersion = nVersion;
175
176     if (nVersion > nWalletMaxVersion)
177         nWalletMaxVersion = nVersion;
178
179     if (fFileBacked)
180     {
181         CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile);
182         if (nWalletVersion >= 40000)
183         {
184             // Versions prior to 0.4.0 did not support the "minversion" record.
185             // Use a CCorruptAddress to make them crash instead.
186             CCorruptAddress corruptAddress;
187             pwalletdb->WriteSetting("addrIncoming", corruptAddress);
188         }
189         if (nWalletVersion > 40000)
190             pwalletdb->WriteMinVersion(nWalletVersion);
191         if (!pwalletdbIn)
192             delete pwalletdb;
193     }
194
195     return true;
196 }
197
198 bool CWallet::SetMaxVersion(int nVersion)
199 {
200     // cannot downgrade below current version
201     if (nWalletVersion > nVersion)
202         return false;
203
204     nWalletMaxVersion = nVersion;
205
206     return true;
207 }
208
209 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
210 {
211     if (IsCrypted())
212         return false;
213
214     CKeyingMaterial vMasterKey;
215     RandAddSeedPerfmon();
216
217     vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
218     RAND_bytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
219
220     CMasterKey kMasterKey;
221
222     RandAddSeedPerfmon();
223     kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
224     RAND_bytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
225
226     CCrypter crypter;
227     int64 nStartTime = GetTimeMillis();
228     crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
229     kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
230
231     nStartTime = GetTimeMillis();
232     crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
233     kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
234
235     if (kMasterKey.nDeriveIterations < 25000)
236         kMasterKey.nDeriveIterations = 25000;
237
238     printf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
239
240     if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
241         return false;
242     if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
243         return false;
244
245     {
246         LOCK(cs_wallet);
247         mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
248         if (fFileBacked)
249         {
250             pwalletdbEncryption = new CWalletDB(strWalletFile);
251             if (!pwalletdbEncryption->TxnBegin())
252                 return false;
253             pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
254         }
255
256         if (!EncryptKeys(vMasterKey))
257         {
258             if (fFileBacked)
259                 pwalletdbEncryption->TxnAbort();
260             exit(1); //We now probably have half of our keys encrypted in memory, and half not...die and let the user reload their unencrypted wallet.
261         }
262
263         // Encryption was introduced in version 0.4.0
264         SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
265
266         if (fFileBacked)
267         {
268             if (!pwalletdbEncryption->TxnCommit())
269                 exit(1); //We now have keys encrypted in memory, but no on disk...die to avoid confusion and let the user reload their unencrypted wallet.
270
271             delete pwalletdbEncryption;
272             pwalletdbEncryption = NULL;
273         }
274
275         Lock();
276         Unlock(strWalletPassphrase);
277         NewKeyPool();
278         Lock();
279
280         // Need to completely rewrite the wallet file; if we don't, bdb might keep
281         // bits of the unencrypted private key in slack space in the database file.
282         CDB::Rewrite(strWalletFile);
283     }
284
285     return true;
286 }
287
288 void CWallet::WalletUpdateSpent(const CTransaction &tx)
289 {
290     // Anytime a signature is successfully verified, it's proof the outpoint is spent.
291     // Update the wallet spent flag if it doesn't know due to wallet.dat being
292     // restored from backup or the user making copies of wallet.dat.
293     {
294         LOCK(cs_wallet);
295         BOOST_FOREACH(const CTxIn& txin, tx.vin)
296         {
297             map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
298             if (mi != mapWallet.end())
299             {
300                 CWalletTx& wtx = (*mi).second;
301                 if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n]))
302                 {
303                     printf("WalletUpdateSpent found spent coin %sppc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
304                     wtx.MarkSpent(txin.prevout.n);
305                     wtx.WriteToDisk();
306                     vWalletUpdated.push_back(txin.prevout.hash);
307                 }
308             }
309         }
310     }
311 }
312
313 void CWallet::MarkDirty()
314 {
315     {
316         LOCK(cs_wallet);
317         BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
318             item.second.MarkDirty();
319     }
320 }
321
322 bool CWallet::AddToWallet(const CWalletTx& wtxIn)
323 {
324     uint256 hash = wtxIn.GetHash();
325     {
326         LOCK(cs_wallet);
327         // Inserts only if not already there, returns tx inserted or tx found
328         pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
329         CWalletTx& wtx = (*ret.first).second;
330         wtx.BindWallet(this);
331         bool fInsertedNew = ret.second;
332         if (fInsertedNew)
333             wtx.nTimeReceived = GetAdjustedTime();
334
335         bool fUpdated = false;
336         if (!fInsertedNew)
337         {
338             // Merge
339             if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
340             {
341                 wtx.hashBlock = wtxIn.hashBlock;
342                 fUpdated = true;
343             }
344             if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
345             {
346                 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
347                 wtx.nIndex = wtxIn.nIndex;
348                 fUpdated = true;
349             }
350             if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
351             {
352                 wtx.fFromMe = wtxIn.fFromMe;
353                 fUpdated = true;
354             }
355             fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);
356         }
357
358         //// debug print
359         printf("AddToWallet %s  %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
360
361         // Write to disk
362         if (fInsertedNew || fUpdated)
363             if (!wtx.WriteToDisk())
364                 return false;
365 #ifndef QT_GUI
366         // If default receiving address gets used, replace it with a new one
367         CScript scriptDefaultKey;
368         scriptDefaultKey.SetBitcoinAddress(vchDefaultKey);
369         BOOST_FOREACH(const CTxOut& txout, wtx.vout)
370         {
371             if (txout.scriptPubKey == scriptDefaultKey)
372             {
373                 std::vector<unsigned char> newDefaultKey;
374                 if (GetKeyFromPool(newDefaultKey, false))
375                 {
376                     SetDefaultKey(newDefaultKey);
377                     SetAddressBookName(CBitcoinAddress(vchDefaultKey), "");
378                 }
379             }
380         }
381 #endif
382         // Notify UI
383         vWalletUpdated.push_back(hash);
384
385         // since AddToWallet is called directly for self-originating transactions, check for consumption of own coins
386         WalletUpdateSpent(wtx);
387     }
388
389     // Refresh UI
390     MainFrameRepaint();
391     return true;
392 }
393
394 // Add a transaction to the wallet, or update it.
395 // pblock is optional, but should be provided if the transaction is known to be in a block.
396 // If fUpdate is true, existing transactions will be updated.
397 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fFindBlock)
398 {
399     uint256 hash = tx.GetHash();
400     {
401         LOCK(cs_wallet);
402         bool fExisted = mapWallet.count(hash);
403         if (fExisted && !fUpdate) return false;
404         if (fExisted || IsMine(tx) || IsFromMe(tx))
405         {
406             CWalletTx wtx(this,tx);
407             // Get merkle branch if transaction was found in a block
408             if (pblock)
409                 wtx.SetMerkleBranch(pblock);
410             return AddToWallet(wtx);
411         }
412         else
413             WalletUpdateSpent(tx);
414     }
415     return false;
416 }
417
418 bool CWallet::EraseFromWallet(uint256 hash)
419 {
420     if (!fFileBacked)
421         return false;
422     {
423         LOCK(cs_wallet);
424         if (mapWallet.erase(hash))
425             CWalletDB(strWalletFile).EraseTx(hash);
426     }
427     return true;
428 }
429
430
431 bool CWallet::IsMine(const CTxIn &txin) const
432 {
433     {
434         LOCK(cs_wallet);
435         map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
436         if (mi != mapWallet.end())
437         {
438             const CWalletTx& prev = (*mi).second;
439             if (txin.prevout.n < prev.vout.size())
440                 if (IsMine(prev.vout[txin.prevout.n]))
441                     return true;
442         }
443     }
444     return false;
445 }
446
447 int64 CWallet::GetDebit(const CTxIn &txin) const
448 {
449     {
450         LOCK(cs_wallet);
451         map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
452         if (mi != mapWallet.end())
453         {
454             const CWalletTx& prev = (*mi).second;
455             if (txin.prevout.n < prev.vout.size())
456                 if (IsMine(prev.vout[txin.prevout.n]))
457                     return prev.vout[txin.prevout.n].nValue;
458         }
459     }
460     return 0;
461 }
462
463 bool CWallet::IsChange(const CTxOut& txout) const
464 {
465     CBitcoinAddress address;
466
467     // TODO: fix handling of 'change' outputs. The assumption is that any
468     // payment to a TX_PUBKEYHASH that is mine but isn't in the address book
469     // is change. That assumption is likely to break when we implement multisignature
470     // wallets that return change back into a multi-signature-protected address;
471     // a better way of identifying which outputs are 'the send' and which are
472     // 'the change' will need to be implemented (maybe extend CWalletTx to remember
473     // which output, if any, was change).
474     if (ExtractAddress(txout.scriptPubKey, address) && HaveKey(address))
475     {
476         LOCK(cs_wallet);
477         if (!mapAddressBook.count(address))
478             return true;
479     }
480     return false;
481 }
482
483 int64 CWalletTx::GetTxTime() const
484 {
485     return nTimeReceived;
486 }
487
488 int CWalletTx::GetRequestCount() const
489 {
490     // Returns -1 if it wasn't being tracked
491     int nRequests = -1;
492     {
493         LOCK(pwallet->cs_wallet);
494         if (IsCoinBase() || IsCoinStake())
495         {
496             // Generated block
497             if (hashBlock != 0)
498             {
499                 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
500                 if (mi != pwallet->mapRequestCount.end())
501                     nRequests = (*mi).second;
502             }
503         }
504         else
505         {
506             // Did anyone request this transaction?
507             map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
508             if (mi != pwallet->mapRequestCount.end())
509             {
510                 nRequests = (*mi).second;
511
512                 // How about the block it's in?
513                 if (nRequests == 0 && hashBlock != 0)
514                 {
515                     map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
516                     if (mi != pwallet->mapRequestCount.end())
517                         nRequests = (*mi).second;
518                     else
519                         nRequests = 1; // If it's in someone else's block it must have got out
520                 }
521             }
522         }
523     }
524     return nRequests;
525 }
526
527 void CWalletTx::GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, list<pair<CBitcoinAddress, int64> >& listReceived,
528                            list<pair<CBitcoinAddress, int64> >& listSent, int64& nFee, string& strSentAccount) const
529 {
530     nGeneratedImmature = nGeneratedMature = nFee = 0;
531     listReceived.clear();
532     listSent.clear();
533     strSentAccount = strFromAccount;
534
535     if (IsCoinBase() || IsCoinStake())
536     {
537         if (GetBlocksToMaturity() > 0)
538             nGeneratedImmature = pwallet->GetCredit(*this);
539         else
540             nGeneratedMature = GetCredit();
541         return;
542     }
543
544     // Compute fee:
545     int64 nDebit = GetDebit();
546     if (nDebit > 0) // debit>0 means we signed/sent this transaction
547     {
548         int64 nValueOut = GetValueOut();
549         nFee = nDebit - nValueOut;
550     }
551
552     // Sent/received.
553     BOOST_FOREACH(const CTxOut& txout, vout)
554     {
555         CBitcoinAddress address;
556         vector<unsigned char> vchPubKey;
557         if (!ExtractAddress(txout.scriptPubKey, address))
558         {
559             printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
560                    this->GetHash().ToString().c_str());
561             address = " unknown ";
562         }
563
564         // Don't report 'change' txouts
565         if (nDebit > 0 && pwallet->IsChange(txout))
566             continue;
567
568         if (nDebit > 0)
569             listSent.push_back(make_pair(address, txout.nValue));
570
571         if (pwallet->IsMine(txout))
572             listReceived.push_back(make_pair(address, txout.nValue));
573     }
574
575 }
576
577 void CWalletTx::GetAccountAmounts(const string& strAccount, int64& nGenerated, int64& nReceived, 
578                                   int64& nSent, int64& nFee) const
579 {
580     nGenerated = nReceived = nSent = nFee = 0;
581
582     int64 allGeneratedImmature, allGeneratedMature, allFee;
583     allGeneratedImmature = allGeneratedMature = allFee = 0;
584     string strSentAccount;
585     list<pair<CBitcoinAddress, int64> > listReceived;
586     list<pair<CBitcoinAddress, int64> > listSent;
587     GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount);
588
589     if (strAccount == "")
590         nGenerated = allGeneratedMature;
591     if (strAccount == strSentAccount)
592     {
593         BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress,int64)& s, listSent)
594             nSent += s.second;
595         nFee = allFee;
596     }
597     {
598         LOCK(pwallet->cs_wallet);
599         BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress,int64)& r, listReceived)
600         {
601             if (pwallet->mapAddressBook.count(r.first))
602             {
603                 map<CBitcoinAddress, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);
604                 if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)
605                     nReceived += r.second;
606             }
607             else if (strAccount.empty())
608             {
609                 nReceived += r.second;
610             }
611         }
612     }
613 }
614
615 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
616 {
617     vtxPrev.clear();
618
619     const int COPY_DEPTH = 3;
620     if (SetMerkleBranch() < COPY_DEPTH)
621     {
622         vector<uint256> vWorkQueue;
623         BOOST_FOREACH(const CTxIn& txin, vin)
624             vWorkQueue.push_back(txin.prevout.hash);
625
626         // This critsect is OK because txdb is already open
627         {
628             LOCK(pwallet->cs_wallet);
629             map<uint256, const CMerkleTx*> mapWalletPrev;
630             set<uint256> setAlreadyDone;
631             for (unsigned int i = 0; i < vWorkQueue.size(); i++)
632             {
633                 uint256 hash = vWorkQueue[i];
634                 if (setAlreadyDone.count(hash))
635                     continue;
636                 setAlreadyDone.insert(hash);
637
638                 CMerkleTx tx;
639                 map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
640                 if (mi != pwallet->mapWallet.end())
641                 {
642                     tx = (*mi).second;
643                     BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev)
644                         mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
645                 }
646                 else if (mapWalletPrev.count(hash))
647                 {
648                     tx = *mapWalletPrev[hash];
649                 }
650                 else if (!fClient && txdb.ReadDiskTx(hash, tx))
651                 {
652                     ;
653                 }
654                 else
655                 {
656                     printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
657                     continue;
658                 }
659
660                 int nDepth = tx.SetMerkleBranch();
661                 vtxPrev.push_back(tx);
662
663                 if (nDepth < COPY_DEPTH)
664                 {
665                     BOOST_FOREACH(const CTxIn& txin, tx.vin)
666                         vWorkQueue.push_back(txin.prevout.hash);
667                 }
668             }
669         }
670     }
671
672     reverse(vtxPrev.begin(), vtxPrev.end());
673 }
674
675 bool CWalletTx::WriteToDisk()
676 {
677     return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
678 }
679
680 // Scan the block chain (starting in pindexStart) for transactions
681 // from or to us. If fUpdate is true, found transactions that already
682 // exist in the wallet will be updated.
683 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
684 {
685     int ret = 0;
686
687     CBlockIndex* pindex = pindexStart;
688     {
689         LOCK(cs_wallet);
690         while (pindex)
691         {
692             CBlock block;
693             block.ReadFromDisk(pindex, true);
694             BOOST_FOREACH(CTransaction& tx, block.vtx)
695             {
696                 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
697                     ret++;
698             }
699             pindex = pindex->pnext;
700         }
701     }
702     return ret;
703 }
704
705 int CWallet::ScanForWalletTransaction(const uint256& hashTx)
706 {
707     CTransaction tx;
708     tx.ReadFromDisk(COutPoint(hashTx, 0));
709     if (AddToWalletIfInvolvingMe(tx, NULL, true, true))
710         return 1;
711     return 0;
712 }
713
714 void CWallet::ReacceptWalletTransactions()
715 {
716     CTxDB txdb("r");
717     bool fRepeat = true;
718     while (fRepeat)
719     {
720         LOCK(cs_wallet);
721         fRepeat = false;
722         vector<CDiskTxPos> vMissingTx;
723         BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
724         {
725             CWalletTx& wtx = item.second;
726             if ((wtx.IsCoinBase() && wtx.IsSpent(0)) || (wtx.IsCoinStake() && wtx.IsSpent(1)))
727                 continue;
728
729             CTxIndex txindex;
730             bool fUpdated = false;
731             if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
732             {
733                 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
734                 if (txindex.vSpent.size() != wtx.vout.size())
735                 {
736                     printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %d != wtx.vout.size() %d\n", txindex.vSpent.size(), wtx.vout.size());
737                     continue;
738                 }
739                 for (unsigned int i = 0; i < txindex.vSpent.size(); i++)
740                 {
741                     if (wtx.IsSpent(i))
742                         continue;
743                     if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i]))
744                     {
745                         wtx.MarkSpent(i);
746                         fUpdated = true;
747                         vMissingTx.push_back(txindex.vSpent[i]);
748                     }
749                 }
750                 if (fUpdated)
751                 {
752                     printf("ReacceptWalletTransactions found spent coin %sppc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
753                     wtx.MarkDirty();
754                     wtx.WriteToDisk();
755                 }
756             }
757             else
758             {
759                 // Reaccept any txes of ours that aren't already in a block
760                 if (!(wtx.IsCoinBase() || wtx.IsCoinStake()))
761                     wtx.AcceptWalletTransaction(txdb, false);
762             }
763         }
764         if (!vMissingTx.empty())
765         {
766             // TODO: optimize this to scan just part of the block chain?
767             if (ScanForWalletTransactions(pindexGenesisBlock))
768                 fRepeat = true;  // Found missing transactions: re-do Reaccept.
769         }
770     }
771 }
772
773 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
774 {
775     BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
776     {
777         if (!(tx.IsCoinBase() || tx.IsCoinStake()))
778         {
779             uint256 hash = tx.GetHash();
780             if (!txdb.ContainsTx(hash))
781                 RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx);
782         }
783     }
784     if (!(IsCoinBase() || IsCoinStake()))
785     {
786         uint256 hash = GetHash();
787         if (!txdb.ContainsTx(hash))
788         {
789             printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
790             RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this);
791         }
792     }
793 }
794
795 void CWalletTx::RelayWalletTransaction()
796 {
797    CTxDB txdb("r");
798    RelayWalletTransaction(txdb);
799 }
800
801 void CWallet::ResendWalletTransactions()
802 {
803     // Do this infrequently and randomly to avoid giving away
804     // that these are our transactions.
805     static int64 nNextTime;
806     if (GetTime() < nNextTime)
807         return;
808     bool fFirst = (nNextTime == 0);
809     nNextTime = GetTime() + GetRand(30 * 60);
810     if (fFirst)
811         return;
812
813     // Only do it if there's been a new block since last time
814     static int64 nLastTime;
815     if (nTimeBestReceived < nLastTime)
816         return;
817     nLastTime = GetTime();
818
819     // Rebroadcast any of our txes that aren't in a block yet
820     printf("ResendWalletTransactions()\n");
821     CTxDB txdb("r");
822     {
823         LOCK(cs_wallet);
824         // Sort them in chronological order
825         multimap<unsigned int, CWalletTx*> mapSorted;
826         BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
827         {
828             CWalletTx& wtx = item.second;
829             // Don't rebroadcast until it's had plenty of time that
830             // it should have gotten in already by now.
831             if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
832                 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
833         }
834         BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
835         {
836             CWalletTx& wtx = *item.second;
837             wtx.RelayWalletTransaction(txdb);
838         }
839     }
840 }
841
842
843
844
845
846
847 //////////////////////////////////////////////////////////////////////////////
848 //
849 // Actions
850 //
851
852
853 int64 CWallet::GetBalance() const
854 {
855     int64 nTotal = 0;
856     {
857         LOCK(cs_wallet);
858         for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
859         {
860             const CWalletTx* pcoin = &(*it).second;
861             if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
862                 continue;
863             nTotal += pcoin->GetAvailableCredit();
864         }
865     }
866
867     return nTotal;
868 }
869
870 int64 CWallet::GetUnconfirmedBalance() const
871 {
872     int64 nTotal = 0;
873     {
874         LOCK(cs_wallet);
875         for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
876         {
877             const CWalletTx* pcoin = &(*it).second;
878             if (pcoin->IsFinal() && pcoin->IsConfirmed())
879                 continue;
880             nTotal += pcoin->GetAvailableCredit();
881         }
882     }
883     return nTotal;
884 }
885
886 // ppcoin: total coins staked (non-spendable until maturity)
887 int64 CWallet::GetStake() const
888 {
889     int64 nTotal = 0;
890     LOCK(cs_wallet);
891     for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
892     {
893         const CWalletTx* pcoin = &(*it).second;
894         if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
895             nTotal += CWallet::GetCredit(*pcoin);
896     }
897     return nTotal;
898 }
899
900 int64 CWallet::GetNewMint() const
901 {
902     int64 nTotal = 0;
903     LOCK(cs_wallet);
904     for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
905     {
906         const CWalletTx* pcoin = &(*it).second;
907         if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
908             nTotal += CWallet::GetCredit(*pcoin);
909     }
910     return nTotal;
911 }
912
913
914 bool CWallet::SelectCoinsMinConf(int64 nTargetValue, unsigned int nSpendTime, int nConfMine, int nConfTheirs, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
915 {
916     setCoinsRet.clear();
917     nValueRet = 0;
918
919     // List of values less than target
920     pair<int64, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
921     coinLowestLarger.first = std::numeric_limits<int64>::max();
922     coinLowestLarger.second.first = NULL;
923     vector<pair<int64, pair<const CWalletTx*,unsigned int> > > vValue;
924     int64 nTotalLower = 0;
925
926     {
927        LOCK(cs_wallet);
928        vector<const CWalletTx*> vCoins;
929        vCoins.reserve(mapWallet.size());
930        for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
931            vCoins.push_back(&(*it).second);
932        random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
933
934        BOOST_FOREACH(const CWalletTx* pcoin, vCoins)
935        {
936             if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
937                 continue;
938
939             if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0)
940                 continue;
941
942             int nDepth = pcoin->GetDepthInMainChain();
943             if (nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs))
944                 continue;
945
946             for (unsigned int i = 0; i < pcoin->vout.size(); i++)
947             {
948                 if (pcoin->IsSpent(i) || !IsMine(pcoin->vout[i]))
949                     continue;
950
951                 if (pcoin->nTime > nSpendTime)
952                     continue;  // ppcoin: timestamp must not exceed spend time
953
954                 int64 n = pcoin->vout[i].nValue;
955
956                 if (n <= 0)
957                     continue;
958
959                 pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin,i));
960
961                 if (n == nTargetValue)
962                 {
963                     setCoinsRet.insert(coin.second);
964                     nValueRet += coin.first;
965                     return true;
966                 }
967                 else if (n < nTargetValue + CENT)
968                 {
969                     vValue.push_back(coin);
970                     nTotalLower += n;
971                 }
972                 else if (n < coinLowestLarger.first)
973                 {
974                     coinLowestLarger = coin;
975                 }
976             }
977         }
978     }
979
980     if (nTotalLower == nTargetValue || nTotalLower == nTargetValue + CENT)
981     {
982         for (unsigned int i = 0; i < vValue.size(); ++i)
983         {
984             setCoinsRet.insert(vValue[i].second);
985             nValueRet += vValue[i].first;
986         }
987         return true;
988     }
989
990     if (nTotalLower < nTargetValue + (coinLowestLarger.second.first ? CENT : 0))
991     {
992         if (coinLowestLarger.second.first == NULL)
993             return false;
994         setCoinsRet.insert(coinLowestLarger.second);
995         nValueRet += coinLowestLarger.first;
996         return true;
997     }
998
999     if (nTotalLower >= nTargetValue + CENT)
1000         nTargetValue += CENT;
1001
1002     // Solve subset sum by stochastic approximation
1003     sort(vValue.rbegin(), vValue.rend());
1004     vector<char> vfIncluded;
1005     vector<char> vfBest(vValue.size(), true);
1006     int64 nBest = nTotalLower;
1007
1008     for (int nRep = 0; nRep < 1000 && nBest != nTargetValue; nRep++)
1009     {
1010         vfIncluded.assign(vValue.size(), false);
1011         int64 nTotal = 0;
1012         bool fReachedTarget = false;
1013         for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
1014         {
1015             for (unsigned int i = 0; i < vValue.size(); i++)
1016             {
1017                 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
1018                 {
1019                     nTotal += vValue[i].first;
1020                     vfIncluded[i] = true;
1021                     if (nTotal >= nTargetValue)
1022                     {
1023                         fReachedTarget = true;
1024                         if (nTotal < nBest)
1025                         {
1026                             nBest = nTotal;
1027                             vfBest = vfIncluded;
1028                         }
1029                         nTotal -= vValue[i].first;
1030                         vfIncluded[i] = false;
1031                     }
1032                 }
1033             }
1034         }
1035     }
1036
1037     // If the next larger is still closer, return it
1038     if (coinLowestLarger.second.first && coinLowestLarger.first - nTargetValue <= nBest - nTargetValue)
1039     {
1040         setCoinsRet.insert(coinLowestLarger.second);
1041         nValueRet += coinLowestLarger.first;
1042     }
1043     else {
1044         for (unsigned int i = 0; i < vValue.size(); i++)
1045             if (vfBest[i])
1046             {
1047                 setCoinsRet.insert(vValue[i].second);
1048                 nValueRet += vValue[i].first;
1049             }
1050
1051         //// debug print
1052         printf("SelectCoins() best subset: ");
1053         for (unsigned int i = 0; i < vValue.size(); i++)
1054             if (vfBest[i])
1055                 printf("%s ", FormatMoney(vValue[i].first).c_str());
1056         printf("total %s\n", FormatMoney(nBest).c_str());
1057     }
1058
1059     return true;
1060 }
1061
1062 bool CWallet::SelectCoins(int64 nTargetValue, unsigned int nSpendTime, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
1063 {
1064     return (SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 6, setCoinsRet, nValueRet) ||
1065             SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 1, setCoinsRet, nValueRet) ||
1066             SelectCoinsMinConf(nTargetValue, nSpendTime, 0, 1, setCoinsRet, nValueRet));
1067 }
1068
1069
1070
1071
1072 bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
1073 {
1074     int64 nValue = 0;
1075     BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1076     {
1077         if (nValue < 0)
1078             return false;
1079         nValue += s.second;
1080     }
1081     if (vecSend.empty() || nValue < 0)
1082         return false;
1083
1084     wtxNew.BindWallet(this);
1085
1086     {
1087         LOCK2(cs_main, cs_wallet);
1088         // txdb must be opened before the mapWallet lock
1089         CTxDB txdb("r");
1090         {
1091             nFeeRet = nTransactionFee;
1092             loop
1093             {
1094                 wtxNew.vin.clear();
1095                 wtxNew.vout.clear();
1096                 wtxNew.fFromMe = true;
1097
1098                 int64 nTotalValue = nValue + nFeeRet;
1099                 double dPriority = 0;
1100                 // vouts to the payees
1101                 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1102                     wtxNew.vout.push_back(CTxOut(s.second, s.first));
1103
1104                 // Choose coins to use
1105                 set<pair<const CWalletTx*,unsigned int> > setCoins;
1106                 int64 nValueIn = 0;
1107                 if (!SelectCoins(nTotalValue, wtxNew.nTime, setCoins, nValueIn))
1108                     return false;
1109                 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1110                 {
1111                     int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
1112                     dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
1113                 }
1114
1115                 int64 nChange = nValueIn - nValue - nFeeRet;
1116                 // if sub-cent change is required, the fee must be raised to at least MIN_TX_FEE
1117                 // or until nChange becomes zero
1118                 // NOTE: this depends on the exact behaviour of GetMinFee
1119                 if (nFeeRet < MIN_TX_FEE && nChange > 0 && nChange < CENT)
1120                 {
1121                     int64 nMoveToFee = min(nChange, MIN_TX_FEE - nFeeRet);
1122                     nChange -= nMoveToFee;
1123                     nFeeRet += nMoveToFee;
1124                 }
1125
1126                 if (nChange > 0)
1127                 {
1128                     // Note: We use a new key here to keep it from being obvious which side is the change.
1129                     //  The drawback is that by not reusing a previous key, the change may be lost if a
1130                     //  backup is restored, if the backup doesn't have the new private key for the change.
1131                     //  If we reused the old key, it would be possible to add code to look for and
1132                     //  rediscover unknown transactions that were written with keys of ours to recover
1133                     //  post-backup change.
1134
1135                     // Reserve a new key pair from key pool
1136                     vector<unsigned char> vchPubKey = reservekey.GetReservedKey();
1137                     // assert(mapKeys.count(vchPubKey));
1138
1139                     // Fill a vout to ourself
1140                     // TODO: pass in scriptChange instead of reservekey so
1141                     // change transaction isn't always pay-to-bitcoin-address
1142                     CScript scriptChange;
1143                     scriptChange.SetBitcoinAddress(vchPubKey);
1144
1145                     // Insert change txn at random position:
1146                     vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
1147                     wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
1148                 }
1149                 else
1150                     reservekey.ReturnKey();
1151
1152                 // Fill vin
1153                 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1154                     wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
1155
1156                 // Sign
1157                 int nIn = 0;
1158                 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1159                     if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
1160                         return false;
1161
1162                 // Limit size
1163                 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
1164                 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1165                     return false;
1166                 dPriority /= nBytes;
1167
1168                 // Check that enough fee is included
1169                 int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
1170                 int64 nMinFee = wtxNew.GetMinFee(1, false, GMF_SEND);
1171                 if (nFeeRet < max(nPayFee, nMinFee))
1172                 {
1173                     nFeeRet = max(nPayFee, nMinFee);
1174                     continue;
1175                 }
1176
1177                 // Fill vtxPrev by copying from previous transactions vtxPrev
1178                 wtxNew.AddSupportingTransactions(txdb);
1179                 wtxNew.fTimeReceivedIsTxTime = true;
1180
1181                 break;
1182             }
1183         }
1184     }
1185     return true;
1186 }
1187
1188 bool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
1189 {
1190     vector< pair<CScript, int64> > vecSend;
1191     vecSend.push_back(make_pair(scriptPubKey, nValue));
1192     return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet);
1193 }
1194
1195 // ppcoin: create coin stake transaction
1196 bool CWallet::CreateCoinStake(unsigned int nBits, CTransaction& txNew)
1197 {
1198     CBigNum bnTargetPerCoinDay;
1199     bnTargetPerCoinDay.SetCompact(nBits);
1200
1201     LOCK2(cs_main, cs_wallet);
1202     txNew.vin.clear();
1203     txNew.vout.clear();
1204     // Mark coin stake transaction
1205     CScript scriptEmpty;
1206     scriptEmpty.clear();
1207     txNew.vout.push_back(CTxOut(0, scriptEmpty));
1208     // Choose coins to use
1209     int64 nBalance = GetBalance();
1210     if (nBalance <= nBalanceReserve)
1211         return false;
1212     set<pair<const CWalletTx*,unsigned int> > setCoins;
1213     vector<const CWalletTx*> vwtxPrev;
1214     int64 nValueIn = 0;
1215     if (!SelectCoins(nBalance - nBalanceReserve, txNew.nTime, setCoins, nValueIn))
1216         return false;
1217     if (setCoins.empty())
1218         return false;
1219     int64 nCredit = 0;
1220     BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1221     {
1222         CTxDB txdb("r");
1223         CTxIndex txindex;
1224         if (!txdb.ReadTxIndex(pcoin.first->GetHash(), txindex))
1225             continue;
1226
1227         // Read block header
1228         CBlock block;
1229         if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
1230             continue;
1231         if (block.GetBlockTime() + STAKE_MIN_AGE > txNew.nTime)
1232             continue; // only count coins meeting min age requirement
1233
1234         int64 nValueIn = pcoin.first->vout[pcoin.second].nValue;
1235         CBigNum bnCoinDay = CBigNum(nValueIn) * (txNew.nTime-pcoin.first->nTime) / COIN / (24 * 60 * 60);
1236         // Calculate hash
1237         CDataStream ss(SER_GETHASH, 0);
1238         ss << nBits << block.nTime << (txindex.pos.nTxPos - txindex.pos.nBlockPos) << pcoin.first->nTime << pcoin.second << txNew.nTime;
1239         if (CBigNum(Hash(ss.begin(), ss.end())) <= bnCoinDay * bnTargetPerCoinDay)
1240         {
1241             txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1242             nCredit += pcoin.first->vout[pcoin.second].nValue;
1243             vwtxPrev.push_back(pcoin.first);
1244             // Set output scriptPubKey
1245             txNew.vout.push_back(CTxOut(0, pcoin.first->vout[pcoin.second].scriptPubKey));
1246             break;
1247         }
1248     }
1249     if (nCredit == 0 || nCredit > nBalance - nBalanceReserve)
1250         return false;
1251     BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1252     {
1253         if (pcoin.first->vout[pcoin.second].scriptPubKey == txNew.vout[1].scriptPubKey && pcoin.first->GetHash() != txNew.vin[0].prevout.hash)
1254         {
1255             if (nCredit + pcoin.first->vout[pcoin.second].nValue > nBalance - nBalanceReserve)
1256                 break;
1257             txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1258             nCredit += pcoin.first->vout[pcoin.second].nValue;
1259             vwtxPrev.push_back(pcoin.first);
1260         }
1261     }
1262     // Calculate coin age reward
1263     {
1264         uint64 nCoinAge;
1265         CTxDB txdb("r");
1266         if (!txNew.GetCoinAge(txdb, nCoinAge))
1267             return error("CreateCoinStake : failed to calculate coin age");
1268         nCredit += GetProofOfStakeReward(nCoinAge);
1269     }
1270     // Set output amount
1271     txNew.vout[1].nValue = nCredit;
1272
1273     // Sign
1274     int nIn = 0;
1275     BOOST_FOREACH(const CWalletTx* pcoin, vwtxPrev)
1276     {
1277         if (!SignSignature(*this, *pcoin, txNew, nIn++))
1278             return error("CreateCoinStake : failed to sign coinstake");
1279     }
1280     return true;
1281 }
1282
1283 // Call after CreateTransaction unless you want to abort
1284 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
1285 {
1286     {
1287         LOCK2(cs_main, cs_wallet);
1288         printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
1289         {
1290             // This is only to keep the database open to defeat the auto-flush for the
1291             // duration of this scope.  This is the only place where this optimization
1292             // maybe makes sense; please don't do it anywhere else.
1293             CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
1294
1295             // Take key pair from key pool so it won't be used again
1296             reservekey.KeepKey();
1297
1298             // Add tx to wallet, because if it has change it's also ours,
1299             // otherwise just for transaction history.
1300             AddToWallet(wtxNew);
1301
1302             // Mark old coins as spent
1303             set<CWalletTx*> setCoins;
1304             BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
1305             {
1306                 CWalletTx &coin = mapWallet[txin.prevout.hash];
1307                 coin.BindWallet(this);
1308                 coin.MarkSpent(txin.prevout.n);
1309                 coin.WriteToDisk();
1310                 vWalletUpdated.push_back(coin.GetHash());
1311             }
1312
1313             if (fFileBacked)
1314                 delete pwalletdb;
1315         }
1316
1317         // Track how many getdata requests our transaction gets
1318         mapRequestCount[wtxNew.GetHash()] = 0;
1319
1320         // Broadcast
1321         if (!wtxNew.AcceptToMemoryPool())
1322         {
1323             // This must not fail. The transaction has already been signed and recorded.
1324             printf("CommitTransaction() : Error: Transaction not valid");
1325             return false;
1326         }
1327         wtxNew.RelayWalletTransaction();
1328     }
1329     MainFrameRepaint();
1330     return true;
1331 }
1332
1333
1334
1335
1336 string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1337 {
1338     CReserveKey reservekey(this);
1339     int64 nFeeRequired;
1340
1341     if (IsLocked())
1342     {
1343         string strError = _("Error: Wallet locked, unable to create transaction  ");
1344         printf("SendMoney() : %s", strError.c_str());
1345         return strError;
1346     }
1347     if (fWalletUnlockStakeOnly)
1348     {
1349         string strError = _("Error: Wallet unlocked for coinstake only, unable to create transaction.");
1350         printf("SendMoney() : %s", strError.c_str());
1351         return strError;
1352     }
1353     if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
1354     {
1355         string strError;
1356         if (nValue + nFeeRequired > GetBalance())
1357             strError = strprintf(_("Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds  "), FormatMoney(nFeeRequired).c_str());
1358         else
1359             strError = _("Error: Transaction creation failed  ");
1360         printf("SendMoney() : %s", strError.c_str());
1361         return strError;
1362     }
1363
1364     if (fAskFee && !ThreadSafeAskFee(nFeeRequired, _("Sending...")))
1365         return "ABORTED";
1366
1367     if (!CommitTransaction(wtxNew, reservekey))
1368         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.");
1369
1370     MainFrameRepaint();
1371     return "";
1372 }
1373
1374
1375
1376 string CWallet::SendMoneyToBitcoinAddress(const CBitcoinAddress& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1377 {
1378     // Check amount
1379     if (nValue <= 0)
1380         return _("Invalid amount");
1381     if (nValue + nTransactionFee > GetBalance())
1382         return _("Insufficient funds");
1383
1384     // Parse bitcoin address
1385     CScript scriptPubKey;
1386     scriptPubKey.SetBitcoinAddress(address);
1387
1388     return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
1389 }
1390
1391
1392
1393
1394 int CWallet::LoadWallet(bool& fFirstRunRet)
1395 {
1396     if (!fFileBacked)
1397         return false;
1398     fFirstRunRet = false;
1399     int nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
1400     if (nLoadWalletRet == DB_NEED_REWRITE)
1401     {
1402         if (CDB::Rewrite(strWalletFile, "\x04pool"))
1403         {
1404             setKeyPool.clear();
1405             // Note: can't top-up keypool here, because wallet is locked.
1406             // User will be prompted to unlock wallet the next operation
1407             // the requires a new key.
1408         }
1409         nLoadWalletRet = DB_NEED_REWRITE;
1410     }
1411
1412     if (nLoadWalletRet != DB_LOAD_OK)
1413         return nLoadWalletRet;
1414     fFirstRunRet = vchDefaultKey.empty();
1415
1416     CreateThread(ThreadFlushWalletDB, &strWalletFile);
1417     return DB_LOAD_OK;
1418 }
1419
1420
1421 bool CWallet::SetAddressBookName(const CBitcoinAddress& address, const string& strName)
1422 {
1423     mapAddressBook[address] = strName;
1424     AddressBookRepaint();
1425     if (!fFileBacked)
1426         return false;
1427     return CWalletDB(strWalletFile).WriteName(address.ToString(), strName);
1428 }
1429
1430 bool CWallet::DelAddressBookName(const CBitcoinAddress& address)
1431 {
1432     mapAddressBook.erase(address);
1433     AddressBookRepaint();
1434     if (!fFileBacked)
1435         return false;
1436     return CWalletDB(strWalletFile).EraseName(address.ToString());
1437 }
1438
1439
1440 void CWallet::PrintWallet(const CBlock& block)
1441 {
1442     {
1443         LOCK(cs_wallet);
1444         if (block.IsProofOfWork() && mapWallet.count(block.vtx[0].GetHash()))
1445         {
1446             CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
1447             printf("    mine:  %d  %d  %s", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), FormatMoney(wtx.GetCredit()).c_str());
1448         }
1449         if (block.IsProofOfStake() && mapWallet.count(block.vtx[1].GetHash()))
1450         {
1451             CWalletTx& wtx = mapWallet[block.vtx[1].GetHash()];
1452             printf("    stake: %d  %d  %s", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), FormatMoney(wtx.GetCredit()).c_str());
1453         }
1454     }
1455     printf("\n");
1456 }
1457
1458 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
1459 {
1460     {
1461         LOCK(cs_wallet);
1462         map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
1463         if (mi != mapWallet.end())
1464         {
1465             wtx = (*mi).second;
1466             return true;
1467         }
1468     }
1469     return false;
1470 }
1471
1472 bool CWallet::SetDefaultKey(const std::vector<unsigned char> &vchPubKey)
1473 {
1474     if (fFileBacked)
1475     {
1476         if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
1477             return false;
1478     }
1479     vchDefaultKey = vchPubKey;
1480     return true;
1481 }
1482
1483 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
1484 {
1485     if (!pwallet->fFileBacked)
1486         return false;
1487     strWalletFileOut = pwallet->strWalletFile;
1488     return true;
1489 }
1490
1491 //
1492 // Mark old keypool keys as used,
1493 // and generate all new keys
1494 //
1495 bool CWallet::NewKeyPool()
1496 {
1497     {
1498         LOCK(cs_wallet);
1499         CWalletDB walletdb(strWalletFile);
1500         BOOST_FOREACH(int64 nIndex, setKeyPool)
1501             walletdb.ErasePool(nIndex);
1502         setKeyPool.clear();
1503
1504         if (IsLocked())
1505             return false;
1506
1507         int64 nKeys = max(GetArg("-keypool", 100), (int64)0);
1508         for (int i = 0; i < nKeys; i++)
1509         {
1510             int64 nIndex = i+1;
1511             walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
1512             setKeyPool.insert(nIndex);
1513         }
1514         printf("CWallet::NewKeyPool wrote %"PRI64d" new keys\n", nKeys);
1515     }
1516     return true;
1517 }
1518
1519 bool CWallet::TopUpKeyPool()
1520 {
1521     {
1522         LOCK(cs_wallet);
1523
1524         if (IsLocked())
1525             return false;
1526
1527         CWalletDB walletdb(strWalletFile);
1528
1529         // Top up key pool
1530         unsigned int nTargetSize = max(GetArg("-keypool", 100), 0LL);
1531         while (setKeyPool.size() < (nTargetSize + 1))
1532         {
1533             int64 nEnd = 1;
1534             if (!setKeyPool.empty())
1535                 nEnd = *(--setKeyPool.end()) + 1;
1536             if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
1537                 throw runtime_error("TopUpKeyPool() : writing generated key failed");
1538             setKeyPool.insert(nEnd);
1539             printf("keypool added key %"PRI64d", size=%d\n", nEnd, setKeyPool.size());
1540         }
1541     }
1542     return true;
1543 }
1544
1545 void CWallet::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool)
1546 {
1547     nIndex = -1;
1548     keypool.vchPubKey.clear();
1549     {
1550         LOCK(cs_wallet);
1551
1552         if (!IsLocked())
1553             TopUpKeyPool();
1554
1555         // Get the oldest key
1556         if(setKeyPool.empty())
1557             return;
1558
1559         CWalletDB walletdb(strWalletFile);
1560
1561         nIndex = *(setKeyPool.begin());
1562         setKeyPool.erase(setKeyPool.begin());
1563         if (!walletdb.ReadPool(nIndex, keypool))
1564             throw runtime_error("ReserveKeyFromKeyPool() : read failed");
1565         if (!HaveKey(Hash160(keypool.vchPubKey)))
1566             throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
1567         assert(!keypool.vchPubKey.empty());
1568         printf("keypool reserve %"PRI64d"\n", nIndex);
1569     }
1570 }
1571
1572 int64 CWallet::AddReserveKey(const CKeyPool& keypool)
1573 {
1574     {
1575         LOCK2(cs_main, cs_wallet);
1576         CWalletDB walletdb(strWalletFile);
1577
1578         int64 nIndex = 1 + *(--setKeyPool.end());
1579         if (!walletdb.WritePool(nIndex, keypool))
1580             throw runtime_error("AddReserveKey() : writing added key failed");
1581         setKeyPool.insert(nIndex);
1582         return nIndex;
1583     }
1584     return -1;
1585 }
1586
1587 void CWallet::KeepKey(int64 nIndex)
1588 {
1589     // Remove from key pool
1590     if (fFileBacked)
1591     {
1592         CWalletDB walletdb(strWalletFile);
1593         walletdb.ErasePool(nIndex);
1594     }
1595     printf("keypool keep %"PRI64d"\n", nIndex);
1596 }
1597
1598 void CWallet::ReturnKey(int64 nIndex)
1599 {
1600     // Return to key pool
1601     {
1602         LOCK(cs_wallet);
1603         setKeyPool.insert(nIndex);
1604     }
1605     printf("keypool return %"PRI64d"\n", nIndex);
1606 }
1607
1608 bool CWallet::GetKeyFromPool(vector<unsigned char>& result, bool fAllowReuse)
1609 {
1610     int64 nIndex = 0;
1611     CKeyPool keypool;
1612     {
1613         LOCK(cs_wallet);
1614         ReserveKeyFromKeyPool(nIndex, keypool);
1615         if (nIndex == -1)
1616         {
1617             if (fAllowReuse && !vchDefaultKey.empty())
1618             {
1619                 result = vchDefaultKey;
1620                 return true;
1621             }
1622             if (IsLocked()) return false;
1623             result = GenerateNewKey();
1624             return true;
1625         }
1626         KeepKey(nIndex);
1627         result = keypool.vchPubKey;
1628     }
1629     return true;
1630 }
1631
1632 int64 CWallet::GetOldestKeyPoolTime()
1633 {
1634     int64 nIndex = 0;
1635     CKeyPool keypool;
1636     ReserveKeyFromKeyPool(nIndex, keypool);
1637     if (nIndex == -1)
1638         return GetTime();
1639     ReturnKey(nIndex);
1640     return keypool.nTime;
1641 }
1642
1643 // ppcoin: check 'spent' consistency between wallet and txindex
1644 bool CWallet::CheckSpentCoins(int& nMismatchFound, int64& nBalanceInQuestion)
1645 {
1646     nMismatchFound = 0;
1647     nBalanceInQuestion = 0;
1648
1649     LOCK(cs_wallet);
1650     vector<const CWalletTx*> vCoins;
1651     vCoins.reserve(mapWallet.size());
1652     for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1653         vCoins.push_back(&(*it).second);
1654  
1655     CTxDB txdb("r");
1656     BOOST_FOREACH(const CWalletTx* pcoin, vCoins)
1657     {
1658         // Find the corresponding transaction index
1659         CTxIndex txindex;
1660         if (!txdb.ReadTxIndex(pcoin->GetHash(), txindex))
1661             continue;
1662         for (int n=0; n < pcoin->vout.size(); n++)
1663         {
1664             if (pcoin->IsSpent(n) && (txindex.vSpent.size() <= n || txindex.vSpent[n].IsNull()))
1665             {
1666                 printf("CheckSpentCoins found lost coin %sppc %s[%d]\n", FormatMoney(pcoin->GetCredit()).c_str(), pcoin->GetHash().ToString().c_str(), n);
1667                 nMismatchFound++;
1668                 nBalanceInQuestion += pcoin->vout[n].nValue;
1669             }
1670             else if (!pcoin->IsSpent(n) && (txindex.vSpent.size() > n && !txindex.vSpent[n].IsNull()))
1671             {
1672                 printf("CheckSpentCoins found spent coin %sppc %s[%d]\n", FormatMoney(pcoin->GetCredit()).c_str(), pcoin->GetHash().ToString().c_str(), n);
1673                 nMismatchFound++;
1674                 nBalanceInQuestion += pcoin->vout[n].nValue;
1675             }
1676         }
1677     }
1678     return (nMismatchFound == 0);
1679 }
1680
1681 // ppcoin: fix wallet spent state according to txindex
1682 void CWallet::FixSpentCoins(int& nMismatchFound, int64& nBalanceInQuestion)
1683 {
1684     nMismatchFound = 0;
1685     nBalanceInQuestion = 0;
1686
1687     LOCK(cs_wallet);
1688     vector<CWalletTx*> vCoins;
1689     vCoins.reserve(mapWallet.size());
1690     for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1691         vCoins.push_back(&(*it).second);
1692
1693     CTxDB txdb("r");
1694     BOOST_FOREACH(CWalletTx* pcoin, vCoins)
1695     {
1696         // Find the corresponding transaction index
1697         CTxIndex txindex;
1698         if (!txdb.ReadTxIndex(pcoin->GetHash(), txindex))
1699             continue;
1700         for (int n=0; n < pcoin->vout.size(); n++)
1701         {
1702             if (pcoin->IsSpent(n) && (txindex.vSpent.size() <= n || txindex.vSpent[n].IsNull()))
1703             {
1704                 printf("FixSpentCoins found lost coin %sppc %s[%d]\n", FormatMoney(pcoin->GetCredit()).c_str(), pcoin->GetHash().ToString().c_str(), n);
1705                 nMismatchFound++;
1706                 nBalanceInQuestion += pcoin->vout[n].nValue;
1707                 pcoin->MarkUnspent(n);
1708                 pcoin->WriteToDisk();
1709             }
1710             else if (!pcoin->IsSpent(n) && (txindex.vSpent.size() > n && !txindex.vSpent[n].IsNull()))
1711             {
1712                 printf("FixSpentCoins found spent coin %sppc %s[%d]\n", FormatMoney(pcoin->GetCredit()).c_str(), pcoin->GetHash().ToString().c_str(), n);
1713                 nMismatchFound++;
1714                 nBalanceInQuestion += pcoin->vout[n].nValue;
1715                 pcoin->MarkSpent(n);
1716                 pcoin->WriteToDisk();
1717             }
1718         }
1719     }
1720 }
1721
1722 // ppcoin: disable transaction (only for coinstake)
1723 void CWallet::DisableTransaction(const CTransaction &tx)
1724 {
1725     if (!tx.IsCoinStake() || !IsFromMe(tx))
1726         return; // only disconnecting coinstake requires marking input unspent
1727
1728     LOCK(cs_wallet);
1729     BOOST_FOREACH(const CTxIn& txin, tx.vin)
1730     {
1731         map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
1732         if (mi != mapWallet.end())
1733         {
1734             CWalletTx& prev = (*mi).second;
1735             if (txin.prevout.n < prev.vout.size() && IsMine(prev.vout[txin.prevout.n]))
1736             {
1737                 prev.MarkUnspent(txin.prevout.n);
1738                 prev.WriteToDisk();
1739             }
1740         }
1741     }
1742 }
1743
1744 vector<unsigned char> CReserveKey::GetReservedKey()
1745 {
1746     if (nIndex == -1)
1747     {
1748         CKeyPool keypool;
1749         pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
1750         if (nIndex != -1)
1751             vchPubKey = keypool.vchPubKey;
1752         else
1753         {
1754             printf("CReserveKey::GetReservedKey(): Warning: using default key instead of a new key, top up your keypool.");
1755             vchPubKey = pwallet->vchDefaultKey;
1756         }
1757     }
1758     assert(!vchPubKey.empty());
1759     return vchPubKey;
1760 }
1761
1762 void CReserveKey::KeepKey()
1763 {
1764     if (nIndex != -1)
1765         pwallet->KeepKey(nIndex);
1766     nIndex = -1;
1767     vchPubKey.clear();
1768 }
1769
1770 void CReserveKey::ReturnKey()
1771 {
1772     if (nIndex != -1)
1773         pwallet->ReturnKey(nIndex);
1774     nIndex = -1;
1775     vchPubKey.clear();
1776 }
1777
1778 void CWallet::GetAllReserveAddresses(set<CBitcoinAddress>& setAddress)
1779 {
1780     setAddress.clear();
1781
1782     CWalletDB walletdb(strWalletFile);
1783
1784     LOCK2(cs_main, cs_wallet);
1785     BOOST_FOREACH(const int64& id, setKeyPool)
1786     {
1787         CKeyPool keypool;
1788         if (!walletdb.ReadPool(id, keypool))
1789             throw runtime_error("GetAllReserveKeyHashes() : read failed");
1790         CBitcoinAddress address(keypool.vchPubKey);
1791         assert(!keypool.vchPubKey.empty());
1792         if (!HaveKey(address))
1793             throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
1794         setAddress.insert(address);
1795     }
1796 }