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