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