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