PPCoin: Change date display format and clean up a merge issue
[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         if (fDebug && GetBoolArg("-printselectcoin"))
1053         {
1054             printf("SelectCoins() best subset: ");
1055             for (unsigned int i = 0; i < vValue.size(); i++)
1056                 if (vfBest[i])
1057                     printf("%s ", FormatMoney(vValue[i].first).c_str());
1058             printf("total %s\n", FormatMoney(nBest).c_str());
1059         }
1060     }
1061
1062     return true;
1063 }
1064
1065 bool CWallet::SelectCoins(int64 nTargetValue, unsigned int nSpendTime, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
1066 {
1067     return (SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 6, setCoinsRet, nValueRet) ||
1068             SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 1, setCoinsRet, nValueRet) ||
1069             SelectCoinsMinConf(nTargetValue, nSpendTime, 0, 1, setCoinsRet, nValueRet));
1070 }
1071
1072
1073
1074
1075 bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
1076 {
1077     int64 nValue = 0;
1078     BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1079     {
1080         if (nValue < 0)
1081             return false;
1082         nValue += s.second;
1083     }
1084     if (vecSend.empty() || nValue < 0)
1085         return false;
1086
1087     wtxNew.BindWallet(this);
1088
1089     {
1090         LOCK2(cs_main, cs_wallet);
1091         // txdb must be opened before the mapWallet lock
1092         CTxDB txdb("r");
1093         {
1094             nFeeRet = nTransactionFee;
1095             loop
1096             {
1097                 wtxNew.vin.clear();
1098                 wtxNew.vout.clear();
1099                 wtxNew.fFromMe = true;
1100
1101                 int64 nTotalValue = nValue + nFeeRet;
1102                 double dPriority = 0;
1103                 // vouts to the payees
1104                 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1105                     wtxNew.vout.push_back(CTxOut(s.second, s.first));
1106
1107                 // Choose coins to use
1108                 set<pair<const CWalletTx*,unsigned int> > setCoins;
1109                 int64 nValueIn = 0;
1110                 if (!SelectCoins(nTotalValue, wtxNew.nTime, setCoins, nValueIn))
1111                     return false;
1112                 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1113                 {
1114                     int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
1115                     dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
1116                 }
1117
1118                 int64 nChange = nValueIn - nValue - nFeeRet;
1119                 // if sub-cent change is required, the fee must be raised to at least MIN_TX_FEE
1120                 // or until nChange becomes zero
1121                 // NOTE: this depends on the exact behaviour of GetMinFee
1122                 if (nFeeRet < MIN_TX_FEE && nChange > 0 && nChange < CENT)
1123                 {
1124                     int64 nMoveToFee = min(nChange, MIN_TX_FEE - nFeeRet);
1125                     nChange -= nMoveToFee;
1126                     nFeeRet += nMoveToFee;
1127                 }
1128
1129                 if (nChange > 0)
1130                 {
1131                     // Note: We use a new key here to keep it from being obvious which side is the change.
1132                     //  The drawback is that by not reusing a previous key, the change may be lost if a
1133                     //  backup is restored, if the backup doesn't have the new private key for the change.
1134                     //  If we reused the old key, it would be possible to add code to look for and
1135                     //  rediscover unknown transactions that were written with keys of ours to recover
1136                     //  post-backup change.
1137
1138                     // Reserve a new key pair from key pool
1139                     vector<unsigned char> vchPubKey = reservekey.GetReservedKey();
1140                     // assert(mapKeys.count(vchPubKey));
1141
1142                     // Fill a vout to ourself
1143                     // TODO: pass in scriptChange instead of reservekey so
1144                     // change transaction isn't always pay-to-bitcoin-address
1145                     CScript scriptChange;
1146                     scriptChange.SetBitcoinAddress(vchPubKey);
1147
1148                     // Insert change txn at random position:
1149                     vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
1150                     wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
1151                 }
1152                 else
1153                     reservekey.ReturnKey();
1154
1155                 // Fill vin
1156                 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1157                     wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
1158
1159                 // Sign
1160                 int nIn = 0;
1161                 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1162                     if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
1163                         return false;
1164
1165                 // Limit size
1166                 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
1167                 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1168                     return false;
1169                 dPriority /= nBytes;
1170
1171                 // Check that enough fee is included
1172                 int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
1173                 int64 nMinFee = wtxNew.GetMinFee(1, false, GMF_SEND);
1174                 if (nFeeRet < max(nPayFee, nMinFee))
1175                 {
1176                     nFeeRet = max(nPayFee, nMinFee);
1177                     continue;
1178                 }
1179
1180                 // Fill vtxPrev by copying from previous transactions vtxPrev
1181                 wtxNew.AddSupportingTransactions(txdb);
1182                 wtxNew.fTimeReceivedIsTxTime = true;
1183
1184                 break;
1185             }
1186         }
1187     }
1188     return true;
1189 }
1190
1191 bool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
1192 {
1193     vector< pair<CScript, int64> > vecSend;
1194     vecSend.push_back(make_pair(scriptPubKey, nValue));
1195     return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet);
1196 }
1197
1198 // ppcoin: create coin stake transaction
1199 bool CWallet::CreateCoinStake(unsigned int nBits, CTransaction& txNew)
1200 {
1201     CBigNum bnTargetPerCoinDay;
1202     bnTargetPerCoinDay.SetCompact(nBits);
1203
1204     LOCK2(cs_main, cs_wallet);
1205     txNew.vin.clear();
1206     txNew.vout.clear();
1207     // Mark coin stake transaction
1208     CScript scriptEmpty;
1209     scriptEmpty.clear();
1210     txNew.vout.push_back(CTxOut(0, scriptEmpty));
1211     // Choose coins to use
1212     int64 nBalance = GetBalance();
1213     int64 nReserveBalance = 0;
1214     if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
1215         return error("CreateCoinStake : invalid reserve balance amount");
1216     if (nBalance <= nReserveBalance)
1217         return false;
1218     set<pair<const CWalletTx*,unsigned int> > setCoins;
1219     vector<const CWalletTx*> vwtxPrev;
1220     int64 nValueIn = 0;
1221     if (!SelectCoins(nBalance - nReserveBalance, txNew.nTime, setCoins, nValueIn))
1222         return false;
1223     if (setCoins.empty())
1224         return false;
1225     int64 nCredit = 0;
1226     BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1227     {
1228         CTxDB txdb("r");
1229         CTxIndex txindex;
1230         if (!txdb.ReadTxIndex(pcoin.first->GetHash(), txindex))
1231             continue;
1232
1233         // Read block header
1234         CBlock block;
1235         if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
1236             continue;
1237         if (block.GetBlockTime() + STAKE_MIN_AGE > txNew.nTime)
1238             continue; // only count coins meeting min age requirement
1239
1240         int64 nValueIn = pcoin.first->vout[pcoin.second].nValue;
1241         CBigNum bnCoinDay = CBigNum(nValueIn) * (txNew.nTime-pcoin.first->nTime) / COIN / (24 * 60 * 60);
1242         // Calculate hash
1243         CDataStream ss(SER_GETHASH, 0);
1244         ss << nBits << block.nTime << (txindex.pos.nTxPos - txindex.pos.nBlockPos) << pcoin.first->nTime << pcoin.second << txNew.nTime;
1245         if (CBigNum(Hash(ss.begin(), ss.end())) <= bnCoinDay * bnTargetPerCoinDay)
1246         {
1247             txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1248             nCredit += pcoin.first->vout[pcoin.second].nValue;
1249             vwtxPrev.push_back(pcoin.first);
1250             // Set output scriptPubKey
1251             txNew.vout.push_back(CTxOut(0, pcoin.first->vout[pcoin.second].scriptPubKey));
1252             break;
1253         }
1254     }
1255     if (nCredit == 0 || nCredit > nBalance - nReserveBalance)
1256         return false;
1257     BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1258     {
1259         if (pcoin.first->vout[pcoin.second].scriptPubKey == txNew.vout[1].scriptPubKey && pcoin.first->GetHash() != txNew.vin[0].prevout.hash)
1260         {
1261             if (nCredit + pcoin.first->vout[pcoin.second].nValue > nBalance - nReserveBalance)
1262                 break;
1263             txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1264             nCredit += pcoin.first->vout[pcoin.second].nValue;
1265             vwtxPrev.push_back(pcoin.first);
1266         }
1267     }
1268     // Calculate coin age reward
1269     {
1270         uint64 nCoinAge;
1271         CTxDB txdb("r");
1272         if (!txNew.GetCoinAge(txdb, nCoinAge))
1273             return error("CreateCoinStake : failed to calculate coin age");
1274         nCredit += GetProofOfStakeReward(nCoinAge);
1275     }
1276     // Set output amount
1277     txNew.vout[1].nValue = nCredit;
1278
1279     // Sign
1280     int nIn = 0;
1281     BOOST_FOREACH(const CWalletTx* pcoin, vwtxPrev)
1282     {
1283         if (!SignSignature(*this, *pcoin, txNew, nIn++))
1284             return error("CreateCoinStake : failed to sign coinstake");
1285     }
1286     return true;
1287 }
1288
1289 // Call after CreateTransaction unless you want to abort
1290 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
1291 {
1292     {
1293         LOCK2(cs_main, cs_wallet);
1294         printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
1295         {
1296             // This is only to keep the database open to defeat the auto-flush for the
1297             // duration of this scope.  This is the only place where this optimization
1298             // maybe makes sense; please don't do it anywhere else.
1299             CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
1300
1301             // Take key pair from key pool so it won't be used again
1302             reservekey.KeepKey();
1303
1304             // Add tx to wallet, because if it has change it's also ours,
1305             // otherwise just for transaction history.
1306             AddToWallet(wtxNew);
1307
1308             // Mark old coins as spent
1309             set<CWalletTx*> setCoins;
1310             BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
1311             {
1312                 CWalletTx &coin = mapWallet[txin.prevout.hash];
1313                 coin.BindWallet(this);
1314                 coin.MarkSpent(txin.prevout.n);
1315                 coin.WriteToDisk();
1316                 vWalletUpdated.push_back(coin.GetHash());
1317             }
1318
1319             if (fFileBacked)
1320                 delete pwalletdb;
1321         }
1322
1323         // Track how many getdata requests our transaction gets
1324         mapRequestCount[wtxNew.GetHash()] = 0;
1325
1326         // Broadcast
1327         if (!wtxNew.AcceptToMemoryPool())
1328         {
1329             // This must not fail. The transaction has already been signed and recorded.
1330             printf("CommitTransaction() : Error: Transaction not valid");
1331             return false;
1332         }
1333         wtxNew.RelayWalletTransaction();
1334     }
1335     MainFrameRepaint();
1336     return true;
1337 }
1338
1339
1340
1341
1342 string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1343 {
1344     CReserveKey reservekey(this);
1345     int64 nFeeRequired;
1346
1347     if (IsLocked())
1348     {
1349         string strError = _("Error: Wallet locked, unable to create transaction  ");
1350         printf("SendMoney() : %s", strError.c_str());
1351         return strError;
1352     }
1353     if (fWalletUnlockStakeOnly)
1354     {
1355         string strError = _("Error: Wallet unlocked for coinstake only, unable to create transaction.");
1356         printf("SendMoney() : %s", strError.c_str());
1357         return strError;
1358     }
1359     if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
1360     {
1361         string strError;
1362         if (nValue + nFeeRequired > GetBalance())
1363             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());
1364         else
1365             strError = _("Error: Transaction creation failed  ");
1366         printf("SendMoney() : %s", strError.c_str());
1367         return strError;
1368     }
1369
1370     if (fAskFee && !ThreadSafeAskFee(nFeeRequired, _("Sending...")))
1371         return "ABORTED";
1372
1373     if (!CommitTransaction(wtxNew, reservekey))
1374         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.");
1375
1376     MainFrameRepaint();
1377     return "";
1378 }
1379
1380
1381
1382 string CWallet::SendMoneyToBitcoinAddress(const CBitcoinAddress& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1383 {
1384     // Check amount
1385     if (nValue <= 0)
1386         return _("Invalid amount");
1387     if (nValue + nTransactionFee > GetBalance())
1388         return _("Insufficient funds");
1389
1390     // Parse bitcoin address
1391     CScript scriptPubKey;
1392     scriptPubKey.SetBitcoinAddress(address);
1393
1394     return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
1395 }
1396
1397
1398
1399
1400 int CWallet::LoadWallet(bool& fFirstRunRet)
1401 {
1402     if (!fFileBacked)
1403         return false;
1404     fFirstRunRet = false;
1405     int nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
1406     if (nLoadWalletRet == DB_NEED_REWRITE)
1407     {
1408         if (CDB::Rewrite(strWalletFile, "\x04pool"))
1409         {
1410             setKeyPool.clear();
1411             // Note: can't top-up keypool here, because wallet is locked.
1412             // User will be prompted to unlock wallet the next operation
1413             // the requires a new key.
1414         }
1415         nLoadWalletRet = DB_NEED_REWRITE;
1416     }
1417
1418     if (nLoadWalletRet != DB_LOAD_OK)
1419         return nLoadWalletRet;
1420     fFirstRunRet = vchDefaultKey.empty();
1421
1422     CreateThread(ThreadFlushWalletDB, &strWalletFile);
1423     return DB_LOAD_OK;
1424 }
1425
1426
1427 bool CWallet::SetAddressBookName(const CBitcoinAddress& address, const string& strName)
1428 {
1429     mapAddressBook[address] = strName;
1430     AddressBookRepaint();
1431     if (!fFileBacked)
1432         return false;
1433     return CWalletDB(strWalletFile).WriteName(address.ToString(), strName);
1434 }
1435
1436 bool CWallet::DelAddressBookName(const CBitcoinAddress& address)
1437 {
1438     mapAddressBook.erase(address);
1439     AddressBookRepaint();
1440     if (!fFileBacked)
1441         return false;
1442     return CWalletDB(strWalletFile).EraseName(address.ToString());
1443 }
1444
1445
1446 void CWallet::PrintWallet(const CBlock& block)
1447 {
1448     {
1449         LOCK(cs_wallet);
1450         if (block.IsProofOfWork() && mapWallet.count(block.vtx[0].GetHash()))
1451         {
1452             CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
1453             printf("    mine:  %d  %d  %s", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), FormatMoney(wtx.GetCredit()).c_str());
1454         }
1455         if (block.IsProofOfStake() && mapWallet.count(block.vtx[1].GetHash()))
1456         {
1457             CWalletTx& wtx = mapWallet[block.vtx[1].GetHash()];
1458             printf("    stake: %d  %d  %s", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), FormatMoney(wtx.GetCredit()).c_str());
1459         }
1460     }
1461     printf("\n");
1462 }
1463
1464 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
1465 {
1466     {
1467         LOCK(cs_wallet);
1468         map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
1469         if (mi != mapWallet.end())
1470         {
1471             wtx = (*mi).second;
1472             return true;
1473         }
1474     }
1475     return false;
1476 }
1477
1478 bool CWallet::SetDefaultKey(const std::vector<unsigned char> &vchPubKey)
1479 {
1480     if (fFileBacked)
1481     {
1482         if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
1483             return false;
1484     }
1485     vchDefaultKey = vchPubKey;
1486     return true;
1487 }
1488
1489 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
1490 {
1491     if (!pwallet->fFileBacked)
1492         return false;
1493     strWalletFileOut = pwallet->strWalletFile;
1494     return true;
1495 }
1496
1497 //
1498 // Mark old keypool keys as used,
1499 // and generate all new keys
1500 //
1501 bool CWallet::NewKeyPool()
1502 {
1503     {
1504         LOCK(cs_wallet);
1505         CWalletDB walletdb(strWalletFile);
1506         BOOST_FOREACH(int64 nIndex, setKeyPool)
1507             walletdb.ErasePool(nIndex);
1508         setKeyPool.clear();
1509
1510         if (IsLocked())
1511             return false;
1512
1513         int64 nKeys = max(GetArg("-keypool", 100), (int64)0);
1514         for (int i = 0; i < nKeys; i++)
1515         {
1516             int64 nIndex = i+1;
1517             walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
1518             setKeyPool.insert(nIndex);
1519         }
1520         printf("CWallet::NewKeyPool wrote %"PRI64d" new keys\n", nKeys);
1521     }
1522     return true;
1523 }
1524
1525 bool CWallet::TopUpKeyPool()
1526 {
1527     {
1528         LOCK(cs_wallet);
1529
1530         if (IsLocked())
1531             return false;
1532
1533         CWalletDB walletdb(strWalletFile);
1534
1535         // Top up key pool
1536         unsigned int nTargetSize = max(GetArg("-keypool", 100), 0LL);
1537         while (setKeyPool.size() < (nTargetSize + 1))
1538         {
1539             int64 nEnd = 1;
1540             if (!setKeyPool.empty())
1541                 nEnd = *(--setKeyPool.end()) + 1;
1542             if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
1543                 throw runtime_error("TopUpKeyPool() : writing generated key failed");
1544             setKeyPool.insert(nEnd);
1545             printf("keypool added key %"PRI64d", size=%d\n", nEnd, setKeyPool.size());
1546         }
1547     }
1548     return true;
1549 }
1550
1551 void CWallet::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool)
1552 {
1553     nIndex = -1;
1554     keypool.vchPubKey.clear();
1555     {
1556         LOCK(cs_wallet);
1557
1558         if (!IsLocked())
1559             TopUpKeyPool();
1560
1561         // Get the oldest key
1562         if(setKeyPool.empty())
1563             return;
1564
1565         CWalletDB walletdb(strWalletFile);
1566
1567         nIndex = *(setKeyPool.begin());
1568         setKeyPool.erase(setKeyPool.begin());
1569         if (!walletdb.ReadPool(nIndex, keypool))
1570             throw runtime_error("ReserveKeyFromKeyPool() : read failed");
1571         if (!HaveKey(Hash160(keypool.vchPubKey)))
1572             throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
1573         assert(!keypool.vchPubKey.empty());
1574         printf("keypool reserve %"PRI64d"\n", nIndex);
1575     }
1576 }
1577
1578 int64 CWallet::AddReserveKey(const CKeyPool& keypool)
1579 {
1580     {
1581         LOCK2(cs_main, cs_wallet);
1582         CWalletDB walletdb(strWalletFile);
1583
1584         int64 nIndex = 1 + *(--setKeyPool.end());
1585         if (!walletdb.WritePool(nIndex, keypool))
1586             throw runtime_error("AddReserveKey() : writing added key failed");
1587         setKeyPool.insert(nIndex);
1588         return nIndex;
1589     }
1590     return -1;
1591 }
1592
1593 void CWallet::KeepKey(int64 nIndex)
1594 {
1595     // Remove from key pool
1596     if (fFileBacked)
1597     {
1598         CWalletDB walletdb(strWalletFile);
1599         walletdb.ErasePool(nIndex);
1600     }
1601     printf("keypool keep %"PRI64d"\n", nIndex);
1602 }
1603
1604 void CWallet::ReturnKey(int64 nIndex)
1605 {
1606     // Return to key pool
1607     {
1608         LOCK(cs_wallet);
1609         setKeyPool.insert(nIndex);
1610     }
1611     printf("keypool return %"PRI64d"\n", nIndex);
1612 }
1613
1614 bool CWallet::GetKeyFromPool(vector<unsigned char>& result, bool fAllowReuse)
1615 {
1616     int64 nIndex = 0;
1617     CKeyPool keypool;
1618     {
1619         LOCK(cs_wallet);
1620         ReserveKeyFromKeyPool(nIndex, keypool);
1621         if (nIndex == -1)
1622         {
1623             if (fAllowReuse && !vchDefaultKey.empty())
1624             {
1625                 result = vchDefaultKey;
1626                 return true;
1627             }
1628             if (IsLocked()) return false;
1629             result = GenerateNewKey();
1630             return true;
1631         }
1632         KeepKey(nIndex);
1633         result = keypool.vchPubKey;
1634     }
1635     return true;
1636 }
1637
1638 int64 CWallet::GetOldestKeyPoolTime()
1639 {
1640     int64 nIndex = 0;
1641     CKeyPool keypool;
1642     ReserveKeyFromKeyPool(nIndex, keypool);
1643     if (nIndex == -1)
1644         return GetTime();
1645     ReturnKey(nIndex);
1646     return keypool.nTime;
1647 }
1648
1649 // ppcoin: check 'spent' consistency between wallet and txindex
1650 bool CWallet::CheckSpentCoins(int& nMismatchFound, int64& nBalanceInQuestion)
1651 {
1652     nMismatchFound = 0;
1653     nBalanceInQuestion = 0;
1654
1655     LOCK(cs_wallet);
1656     vector<const CWalletTx*> vCoins;
1657     vCoins.reserve(mapWallet.size());
1658     for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1659         vCoins.push_back(&(*it).second);
1660  
1661     CTxDB txdb("r");
1662     BOOST_FOREACH(const CWalletTx* pcoin, vCoins)
1663     {
1664         // Find the corresponding transaction index
1665         CTxIndex txindex;
1666         if (!txdb.ReadTxIndex(pcoin->GetHash(), txindex))
1667             continue;
1668         for (int n=0; n < pcoin->vout.size(); n++)
1669         {
1670             if (pcoin->IsSpent(n) && (txindex.vSpent.size() <= n || txindex.vSpent[n].IsNull()))
1671             {
1672                 printf("CheckSpentCoins found lost 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             else if (!pcoin->IsSpent(n) && (txindex.vSpent.size() > n && !txindex.vSpent[n].IsNull()))
1677             {
1678                 printf("CheckSpentCoins found spent coin %sppc %s[%d]\n", FormatMoney(pcoin->GetCredit()).c_str(), pcoin->GetHash().ToString().c_str(), n);
1679                 nMismatchFound++;
1680                 nBalanceInQuestion += pcoin->vout[n].nValue;
1681             }
1682         }
1683     }
1684     return (nMismatchFound == 0);
1685 }
1686
1687 // ppcoin: fix wallet spent state according to txindex
1688 void CWallet::FixSpentCoins(int& nMismatchFound, int64& nBalanceInQuestion)
1689 {
1690     nMismatchFound = 0;
1691     nBalanceInQuestion = 0;
1692
1693     LOCK(cs_wallet);
1694     vector<CWalletTx*> vCoins;
1695     vCoins.reserve(mapWallet.size());
1696     for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1697         vCoins.push_back(&(*it).second);
1698
1699     CTxDB txdb("r");
1700     BOOST_FOREACH(CWalletTx* pcoin, vCoins)
1701     {
1702         // Find the corresponding transaction index
1703         CTxIndex txindex;
1704         if (!txdb.ReadTxIndex(pcoin->GetHash(), txindex))
1705             continue;
1706         for (int n=0; n < pcoin->vout.size(); n++)
1707         {
1708             if (pcoin->IsSpent(n) && (txindex.vSpent.size() <= n || txindex.vSpent[n].IsNull()))
1709             {
1710                 printf("FixSpentCoins found lost coin %sppc %s[%d]\n", FormatMoney(pcoin->GetCredit()).c_str(), pcoin->GetHash().ToString().c_str(), n);
1711                 nMismatchFound++;
1712                 nBalanceInQuestion += pcoin->vout[n].nValue;
1713                 pcoin->MarkUnspent(n);
1714                 pcoin->WriteToDisk();
1715             }
1716             else if (!pcoin->IsSpent(n) && (txindex.vSpent.size() > n && !txindex.vSpent[n].IsNull()))
1717             {
1718                 printf("FixSpentCoins found spent coin %sppc %s[%d]\n", FormatMoney(pcoin->GetCredit()).c_str(), pcoin->GetHash().ToString().c_str(), n);
1719                 nMismatchFound++;
1720                 nBalanceInQuestion += pcoin->vout[n].nValue;
1721                 pcoin->MarkSpent(n);
1722                 pcoin->WriteToDisk();
1723             }
1724         }
1725     }
1726 }
1727
1728 // ppcoin: disable transaction (only for coinstake)
1729 void CWallet::DisableTransaction(const CTransaction &tx)
1730 {
1731     if (!tx.IsCoinStake() || !IsFromMe(tx))
1732         return; // only disconnecting coinstake requires marking input unspent
1733
1734     LOCK(cs_wallet);
1735     BOOST_FOREACH(const CTxIn& txin, tx.vin)
1736     {
1737         map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
1738         if (mi != mapWallet.end())
1739         {
1740             CWalletTx& prev = (*mi).second;
1741             if (txin.prevout.n < prev.vout.size() && IsMine(prev.vout[txin.prevout.n]))
1742             {
1743                 prev.MarkUnspent(txin.prevout.n);
1744                 prev.WriteToDisk();
1745             }
1746         }
1747     }
1748 }
1749
1750 vector<unsigned char> CReserveKey::GetReservedKey()
1751 {
1752     if (nIndex == -1)
1753     {
1754         CKeyPool keypool;
1755         pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
1756         if (nIndex != -1)
1757             vchPubKey = keypool.vchPubKey;
1758         else
1759         {
1760             printf("CReserveKey::GetReservedKey(): Warning: using default key instead of a new key, top up your keypool.");
1761             vchPubKey = pwallet->vchDefaultKey;
1762         }
1763     }
1764     assert(!vchPubKey.empty());
1765     return vchPubKey;
1766 }
1767
1768 void CReserveKey::KeepKey()
1769 {
1770     if (nIndex != -1)
1771         pwallet->KeepKey(nIndex);
1772     nIndex = -1;
1773     vchPubKey.clear();
1774 }
1775
1776 void CReserveKey::ReturnKey()
1777 {
1778     if (nIndex != -1)
1779         pwallet->ReturnKey(nIndex);
1780     nIndex = -1;
1781     vchPubKey.clear();
1782 }
1783
1784 void CWallet::GetAllReserveAddresses(set<CBitcoinAddress>& setAddress)
1785 {
1786     setAddress.clear();
1787
1788     CWalletDB walletdb(strWalletFile);
1789
1790     LOCK2(cs_main, cs_wallet);
1791     BOOST_FOREACH(const int64& id, setKeyPool)
1792     {
1793         CKeyPool keypool;
1794         if (!walletdb.ReadPool(id, keypool))
1795             throw runtime_error("GetAllReserveKeyHashes() : read failed");
1796         CBitcoinAddress address(keypool.vchPubKey);
1797         assert(!keypool.vchPubKey.empty());
1798         if (!HaveKey(address))
1799             throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
1800         setAddress.insert(address);
1801     }
1802 }