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