fix warnings: suggest explicit braces to avoid ambiguous 'else' [-Wparentheses]
[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                 {
648                     BOOST_FOREACH(const CTxIn& txin, tx.vin)
649                         vWorkQueue.push_back(txin.prevout.hash);
650                 }
651             }
652         }
653     }
654
655     reverse(vtxPrev.begin(), vtxPrev.end());
656 }
657
658 bool CWalletTx::WriteToDisk()
659 {
660     return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
661 }
662
663 // Scan the block chain (starting in pindexStart) for transactions
664 // from or to us. If fUpdate is true, found transactions that already
665 // exist in the wallet will be updated.
666 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
667 {
668     int ret = 0;
669
670     CBlockIndex* pindex = pindexStart;
671     CRITICAL_BLOCK(cs_wallet)
672     {
673         while (pindex)
674         {
675             CBlock block;
676             block.ReadFromDisk(pindex, true);
677             BOOST_FOREACH(CTransaction& tx, block.vtx)
678             {
679                 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
680                     ret++;
681             }
682             pindex = pindex->pnext;
683         }
684     }
685     return ret;
686 }
687
688 int CWallet::ScanForWalletTransaction(const uint256& hashTx)
689 {
690     CTransaction tx;
691     tx.ReadFromDisk(COutPoint(hashTx, 0));
692     if (AddToWalletIfInvolvingMe(tx, NULL, true, true))
693         return 1;
694     return 0;
695 }
696
697 void CWallet::ReacceptWalletTransactions()
698 {
699     CTxDB txdb("r");
700     bool fRepeat = true;
701     while (fRepeat) CRITICAL_BLOCK(cs_wallet)
702     {
703         fRepeat = false;
704         vector<CDiskTxPos> vMissingTx;
705         BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
706         {
707             CWalletTx& wtx = item.second;
708             if (wtx.IsCoinBase() && wtx.IsSpent(0))
709                 continue;
710
711             CTxIndex txindex;
712             bool fUpdated = false;
713             if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
714             {
715                 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
716                 if (txindex.vSpent.size() != wtx.vout.size())
717                 {
718                     printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %d != wtx.vout.size() %d\n", txindex.vSpent.size(), wtx.vout.size());
719                     continue;
720                 }
721                 for (int i = 0; i < txindex.vSpent.size(); i++)
722                 {
723                     if (wtx.IsSpent(i))
724                         continue;
725                     if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i]))
726                     {
727                         wtx.MarkSpent(i);
728                         fUpdated = true;
729                         vMissingTx.push_back(txindex.vSpent[i]);
730                     }
731                 }
732                 if (fUpdated)
733                 {
734                     printf("ReacceptWalletTransactions found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
735                     wtx.MarkDirty();
736                     wtx.WriteToDisk();
737                 }
738             }
739             else
740             {
741                 // Reaccept any txes of ours that aren't already in a block
742                 if (!wtx.IsCoinBase())
743                     wtx.AcceptWalletTransaction(txdb, false);
744             }
745         }
746         if (!vMissingTx.empty())
747         {
748             // TODO: optimize this to scan just part of the block chain?
749             if (ScanForWalletTransactions(pindexGenesisBlock))
750                 fRepeat = true;  // Found missing transactions: re-do Reaccept.
751         }
752     }
753 }
754
755 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
756 {
757     BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
758     {
759         if (!tx.IsCoinBase())
760         {
761             uint256 hash = tx.GetHash();
762             if (!txdb.ContainsTx(hash))
763                 RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx);
764         }
765     }
766     if (!IsCoinBase())
767     {
768         uint256 hash = GetHash();
769         if (!txdb.ContainsTx(hash))
770         {
771             printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
772             RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this);
773         }
774     }
775 }
776
777 void CWalletTx::RelayWalletTransaction()
778 {
779    CTxDB txdb("r");
780    RelayWalletTransaction(txdb);
781 }
782
783 void CWallet::ResendWalletTransactions()
784 {
785     // Do this infrequently and randomly to avoid giving away
786     // that these are our transactions.
787     static int64 nNextTime;
788     if (GetTime() < nNextTime)
789         return;
790     bool fFirst = (nNextTime == 0);
791     nNextTime = GetTime() + GetRand(30 * 60);
792     if (fFirst)
793         return;
794
795     // Only do it if there's been a new block since last time
796     static int64 nLastTime;
797     if (nTimeBestReceived < nLastTime)
798         return;
799     nLastTime = GetTime();
800
801     // Rebroadcast any of our txes that aren't in a block yet
802     printf("ResendWalletTransactions()\n");
803     CTxDB txdb("r");
804     CRITICAL_BLOCK(cs_wallet)
805     {
806         // Sort them in chronological order
807         multimap<unsigned int, CWalletTx*> mapSorted;
808         BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
809         {
810             CWalletTx& wtx = item.second;
811             // Don't rebroadcast until it's had plenty of time that
812             // it should have gotten in already by now.
813             if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
814                 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
815         }
816         BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
817         {
818             CWalletTx& wtx = *item.second;
819             wtx.RelayWalletTransaction(txdb);
820         }
821     }
822 }
823
824
825
826
827
828
829 //////////////////////////////////////////////////////////////////////////////
830 //
831 // Actions
832 //
833
834
835 int64 CWallet::GetBalance() const
836 {
837     int64 nTotal = 0;
838     CRITICAL_BLOCK(cs_wallet)
839     {
840         for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
841         {
842             const CWalletTx* pcoin = &(*it).second;
843             if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
844                 continue;
845             nTotal += pcoin->GetAvailableCredit();
846         }
847     }
848
849     return nTotal;
850 }
851
852 int64 CWallet::GetUnconfirmedBalance() const
853 {
854     int64 nTotal = 0;
855     CRITICAL_BLOCK(cs_wallet)
856     {
857         for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
858         {
859             const CWalletTx* pcoin = &(*it).second;
860             if (pcoin->IsFinal() && pcoin->IsConfirmed())
861                 continue;
862             nTotal += pcoin->GetAvailableCredit();
863         }
864     }
865     return nTotal;
866 }
867
868 bool CWallet::SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
869 {
870     setCoinsRet.clear();
871     nValueRet = 0;
872
873     // List of values less than target
874     pair<int64, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
875     coinLowestLarger.first = std::numeric_limits<int64>::max();
876     coinLowestLarger.second.first = NULL;
877     vector<pair<int64, pair<const CWalletTx*,unsigned int> > > vValue;
878     int64 nTotalLower = 0;
879
880     CRITICAL_BLOCK(cs_wallet)
881     {
882        vector<const CWalletTx*> vCoins;
883        vCoins.reserve(mapWallet.size());
884        for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
885            vCoins.push_back(&(*it).second);
886        random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
887
888        BOOST_FOREACH(const CWalletTx* pcoin, vCoins)
889        {
890             if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
891                 continue;
892
893             if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
894                 continue;
895
896             int nDepth = pcoin->GetDepthInMainChain();
897             if (nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs))
898                 continue;
899
900             for (int i = 0; i < pcoin->vout.size(); i++)
901             {
902                 if (pcoin->IsSpent(i) || !IsMine(pcoin->vout[i]))
903                     continue;
904
905                 int64 n = pcoin->vout[i].nValue;
906
907                 if (n <= 0)
908                     continue;
909
910                 pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin,i));
911
912                 if (n == nTargetValue)
913                 {
914                     setCoinsRet.insert(coin.second);
915                     nValueRet += coin.first;
916                     return true;
917                 }
918                 else if (n < nTargetValue + CENT)
919                 {
920                     vValue.push_back(coin);
921                     nTotalLower += n;
922                 }
923                 else if (n < coinLowestLarger.first)
924                 {
925                     coinLowestLarger = coin;
926                 }
927             }
928         }
929     }
930
931     if (nTotalLower == nTargetValue || nTotalLower == nTargetValue + CENT)
932     {
933         for (int i = 0; i < vValue.size(); ++i)
934         {
935             setCoinsRet.insert(vValue[i].second);
936             nValueRet += vValue[i].first;
937         }
938         return true;
939     }
940
941     if (nTotalLower < nTargetValue + (coinLowestLarger.second.first ? CENT : 0))
942     {
943         if (coinLowestLarger.second.first == NULL)
944             return false;
945         setCoinsRet.insert(coinLowestLarger.second);
946         nValueRet += coinLowestLarger.first;
947         return true;
948     }
949
950     if (nTotalLower >= nTargetValue + CENT)
951         nTargetValue += CENT;
952
953     // Solve subset sum by stochastic approximation
954     sort(vValue.rbegin(), vValue.rend());
955     vector<char> vfIncluded;
956     vector<char> vfBest(vValue.size(), true);
957     int64 nBest = nTotalLower;
958
959     for (int nRep = 0; nRep < 1000 && nBest != nTargetValue; nRep++)
960     {
961         vfIncluded.assign(vValue.size(), false);
962         int64 nTotal = 0;
963         bool fReachedTarget = false;
964         for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
965         {
966             for (int i = 0; i < vValue.size(); i++)
967             {
968                 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
969                 {
970                     nTotal += vValue[i].first;
971                     vfIncluded[i] = true;
972                     if (nTotal >= nTargetValue)
973                     {
974                         fReachedTarget = true;
975                         if (nTotal < nBest)
976                         {
977                             nBest = nTotal;
978                             vfBest = vfIncluded;
979                         }
980                         nTotal -= vValue[i].first;
981                         vfIncluded[i] = false;
982                     }
983                 }
984             }
985         }
986     }
987
988     // If the next larger is still closer, return it
989     if (coinLowestLarger.second.first && coinLowestLarger.first - nTargetValue <= nBest - nTargetValue)
990     {
991         setCoinsRet.insert(coinLowestLarger.second);
992         nValueRet += coinLowestLarger.first;
993     }
994     else {
995         for (int i = 0; i < vValue.size(); i++)
996             if (vfBest[i])
997             {
998                 setCoinsRet.insert(vValue[i].second);
999                 nValueRet += vValue[i].first;
1000             }
1001
1002         //// debug print
1003         printf("SelectCoins() best subset: ");
1004         for (int i = 0; i < vValue.size(); i++)
1005             if (vfBest[i])
1006                 printf("%s ", FormatMoney(vValue[i].first).c_str());
1007         printf("total %s\n", FormatMoney(nBest).c_str());
1008     }
1009
1010     return true;
1011 }
1012
1013 bool CWallet::SelectCoins(int64 nTargetValue, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
1014 {
1015     return (SelectCoinsMinConf(nTargetValue, 1, 6, setCoinsRet, nValueRet) ||
1016             SelectCoinsMinConf(nTargetValue, 1, 1, setCoinsRet, nValueRet) ||
1017             SelectCoinsMinConf(nTargetValue, 0, 1, setCoinsRet, nValueRet));
1018 }
1019
1020
1021
1022
1023 bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
1024 {
1025     int64 nValue = 0;
1026     BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1027     {
1028         if (nValue < 0)
1029             return false;
1030         nValue += s.second;
1031     }
1032     if (vecSend.empty() || nValue < 0)
1033         return false;
1034
1035     wtxNew.BindWallet(this);
1036
1037     CRITICAL_BLOCK(cs_main)
1038     CRITICAL_BLOCK(cs_wallet)
1039     {
1040         // txdb must be opened before the mapWallet lock
1041         CTxDB txdb("r");
1042         {
1043             nFeeRet = nTransactionFee;
1044             loop
1045             {
1046                 wtxNew.vin.clear();
1047                 wtxNew.vout.clear();
1048                 wtxNew.fFromMe = true;
1049
1050                 int64 nTotalValue = nValue + nFeeRet;
1051                 double dPriority = 0;
1052                 // vouts to the payees
1053                 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1054                     wtxNew.vout.push_back(CTxOut(s.second, s.first));
1055
1056                 // Choose coins to use
1057                 set<pair<const CWalletTx*,unsigned int> > setCoins;
1058                 int64 nValueIn = 0;
1059                 if (!SelectCoins(nTotalValue, setCoins, nValueIn))
1060                     return false;
1061                 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1062                 {
1063                     int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
1064                     dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
1065                 }
1066
1067                 int64 nChange = nValueIn - nValue - nFeeRet;
1068                 // if sub-cent change is required, the fee must be raised to at least MIN_TX_FEE
1069                 // or until nChange becomes zero
1070                 // NOTE: this depends on the exact behaviour of GetMinFee
1071                 if (nFeeRet < MIN_TX_FEE && nChange > 0 && nChange < CENT)
1072                 {
1073                     int64 nMoveToFee = min(nChange, MIN_TX_FEE - nFeeRet);
1074                     nChange -= nMoveToFee;
1075                     nFeeRet += nMoveToFee;
1076                 }
1077
1078                 if (nChange > 0)
1079                 {
1080                     // Note: We use a new key here to keep it from being obvious which side is the change.
1081                     //  The drawback is that by not reusing a previous key, the change may be lost if a
1082                     //  backup is restored, if the backup doesn't have the new private key for the change.
1083                     //  If we reused the old key, it would be possible to add code to look for and
1084                     //  rediscover unknown transactions that were written with keys of ours to recover
1085                     //  post-backup change.
1086
1087                     // Reserve a new key pair from key pool
1088                     vector<unsigned char> vchPubKey = reservekey.GetReservedKey();
1089                     // assert(mapKeys.count(vchPubKey));
1090
1091                     // Fill a vout to ourself
1092                     // TODO: pass in scriptChange instead of reservekey so
1093                     // change transaction isn't always pay-to-bitcoin-address
1094                     CScript scriptChange;
1095                     scriptChange.SetBitcoinAddress(vchPubKey);
1096
1097                     // Insert change txn at random position:
1098                     vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
1099                     wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
1100                 }
1101                 else
1102                     reservekey.ReturnKey();
1103
1104                 // Fill vin
1105                 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1106                     wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
1107
1108                 // Sign
1109                 int nIn = 0;
1110                 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1111                     if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
1112                         return false;
1113
1114                 // Limit size
1115                 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK);
1116                 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1117                     return false;
1118                 dPriority /= nBytes;
1119
1120                 // Check that enough fee is included
1121                 int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
1122                 bool fAllowFree = CTransaction::AllowFree(dPriority);
1123                 int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND);
1124                 if (nFeeRet < max(nPayFee, nMinFee))
1125                 {
1126                     nFeeRet = max(nPayFee, nMinFee);
1127                     continue;
1128                 }
1129
1130                 // Fill vtxPrev by copying from previous transactions vtxPrev
1131                 wtxNew.AddSupportingTransactions(txdb);
1132                 wtxNew.fTimeReceivedIsTxTime = true;
1133
1134                 break;
1135             }
1136         }
1137     }
1138     return true;
1139 }
1140
1141 bool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
1142 {
1143     vector< pair<CScript, int64> > vecSend;
1144     vecSend.push_back(make_pair(scriptPubKey, nValue));
1145     return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet);
1146 }
1147
1148 // Call after CreateTransaction unless you want to abort
1149 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
1150 {
1151     CRITICAL_BLOCK(cs_main)
1152     CRITICAL_BLOCK(cs_wallet)
1153     {
1154         printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
1155         {
1156             // This is only to keep the database open to defeat the auto-flush for the
1157             // duration of this scope.  This is the only place where this optimization
1158             // maybe makes sense; please don't do it anywhere else.
1159             CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
1160
1161             // Take key pair from key pool so it won't be used again
1162             reservekey.KeepKey();
1163
1164             // Add tx to wallet, because if it has change it's also ours,
1165             // otherwise just for transaction history.
1166             AddToWallet(wtxNew);
1167
1168             // Mark old coins as spent
1169             set<CWalletTx*> setCoins;
1170             BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
1171             {
1172                 CWalletTx &coin = mapWallet[txin.prevout.hash];
1173                 coin.BindWallet(this);
1174                 coin.MarkSpent(txin.prevout.n);
1175                 coin.WriteToDisk();
1176                 vWalletUpdated.push_back(coin.GetHash());
1177             }
1178
1179             if (fFileBacked)
1180                 delete pwalletdb;
1181         }
1182
1183         // Track how many getdata requests our transaction gets
1184         mapRequestCount[wtxNew.GetHash()] = 0;
1185
1186         // Broadcast
1187         if (!wtxNew.AcceptToMemoryPool())
1188         {
1189             // This must not fail. The transaction has already been signed and recorded.
1190             printf("CommitTransaction() : Error: Transaction not valid");
1191             return false;
1192         }
1193         wtxNew.RelayWalletTransaction();
1194     }
1195     MainFrameRepaint();
1196     return true;
1197 }
1198
1199
1200
1201
1202 string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1203 {
1204     CReserveKey reservekey(this);
1205     int64 nFeeRequired;
1206
1207     if (IsLocked())
1208     {
1209         string strError = _("Error: Wallet locked, unable to create transaction  ");
1210         printf("SendMoney() : %s", strError.c_str());
1211         return strError;
1212     }
1213     if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
1214     {
1215         string strError;
1216         if (nValue + nFeeRequired > GetBalance())
1217             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());
1218         else
1219             strError = _("Error: Transaction creation failed  ");
1220         printf("SendMoney() : %s", strError.c_str());
1221         return strError;
1222     }
1223
1224     if (fAskFee && !ThreadSafeAskFee(nFeeRequired, _("Sending..."), NULL))
1225         return "ABORTED";
1226
1227     if (!CommitTransaction(wtxNew, reservekey))
1228         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.");
1229
1230     MainFrameRepaint();
1231     return "";
1232 }
1233
1234
1235
1236 string CWallet::SendMoneyToBitcoinAddress(const CBitcoinAddress& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1237 {
1238     // Check amount
1239     if (nValue <= 0)
1240         return _("Invalid amount");
1241     if (nValue + nTransactionFee > GetBalance())
1242         return _("Insufficient funds");
1243
1244     // Parse bitcoin address
1245     CScript scriptPubKey;
1246     scriptPubKey.SetBitcoinAddress(address);
1247
1248     return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
1249 }
1250
1251
1252
1253
1254 int CWallet::LoadWallet(bool& fFirstRunRet)
1255 {
1256     if (!fFileBacked)
1257         return false;
1258     fFirstRunRet = false;
1259     int nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
1260     if (nLoadWalletRet == DB_NEED_REWRITE)
1261     {
1262         if (CDB::Rewrite(strWalletFile, "\x04pool"))
1263         {
1264             setKeyPool.clear();
1265             // Note: can't top-up keypool here, because wallet is locked.
1266             // User will be prompted to unlock wallet the next operation
1267             // the requires a new key.
1268         }
1269         nLoadWalletRet = DB_NEED_REWRITE;
1270     }
1271
1272     if (nLoadWalletRet != DB_LOAD_OK)
1273         return nLoadWalletRet;
1274     fFirstRunRet = vchDefaultKey.empty();
1275
1276     CreateThread(ThreadFlushWalletDB, &strWalletFile);
1277     return DB_LOAD_OK;
1278 }
1279
1280
1281 bool CWallet::SetAddressBookName(const CBitcoinAddress& address, const string& strName)
1282 {
1283     mapAddressBook[address] = strName;
1284     if (!fFileBacked)
1285         return false;
1286     return CWalletDB(strWalletFile).WriteName(address.ToString(), strName);
1287 }
1288
1289 bool CWallet::DelAddressBookName(const CBitcoinAddress& address)
1290 {
1291     mapAddressBook.erase(address);
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 }