91b8aee49ab9284c87f7fed320de7e6d528b3c99
[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             if (fOnlyConfirmed && !pcoin->IsTrusted())
1029                 continue;
1030
1031             if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
1032                 continue;
1033
1034             if(pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0)
1035                 continue;
1036
1037             for (unsigned int i = 0; i < pcoin->vout.size(); i++)
1038                 if (!(pcoin->IsSpent(i)) && IsMine(pcoin->vout[i]) && pcoin->vout[i].nValue >= nMinimumInputValue &&
1039                 (!coinControl || !coinControl->HasSelected() || coinControl->IsSelected((*it).first, i)))
1040                     vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain()));
1041
1042         }
1043     }
1044 }
1045
1046 void CWallet::AvailableCoinsMinConf(vector<COutput>& vCoins, int nConf) const
1047 {
1048     vCoins.clear();
1049
1050     {
1051         LOCK(cs_wallet);
1052         for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1053         {
1054             const CWalletTx* pcoin = &(*it).second;
1055
1056             if (!pcoin->IsFinal())
1057                 continue;
1058
1059             if(pcoin->GetDepthInMainChain() < nConf)
1060                 continue;
1061
1062             for (unsigned int i = 0; i < pcoin->vout.size(); i++)
1063                 if (!(pcoin->IsSpent(i)) && IsMine(pcoin->vout[i]) && pcoin->vout[i].nValue >= nMinimumInputValue)
1064                     vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain()));
1065         }
1066     }
1067 }
1068
1069 static void ApproximateBestSubset(vector<pair<int64, pair<const CWalletTx*,unsigned int> > >vValue, int64 nTotalLower, int64 nTargetValue,
1070                                   vector<char>& vfBest, int64& nBest, int iterations = 1000)
1071 {
1072     vector<char> vfIncluded;
1073
1074     vfBest.assign(vValue.size(), true);
1075     nBest = nTotalLower;
1076
1077     for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
1078     {
1079         vfIncluded.assign(vValue.size(), false);
1080         int64 nTotal = 0;
1081         bool fReachedTarget = false;
1082         for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
1083         {
1084             for (unsigned int i = 0; i < vValue.size(); i++)
1085             {
1086                 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
1087                 {
1088                     nTotal += vValue[i].first;
1089                     vfIncluded[i] = true;
1090                     if (nTotal >= nTargetValue)
1091                     {
1092                         fReachedTarget = true;
1093                         if (nTotal < nBest)
1094                         {
1095                             nBest = nTotal;
1096                             vfBest = vfIncluded;
1097                         }
1098                         nTotal -= vValue[i].first;
1099                         vfIncluded[i] = false;
1100                     }
1101                 }
1102             }
1103         }
1104     }
1105 }
1106
1107 // ppcoin: total coins staked (non-spendable until maturity)
1108 int64 CWallet::GetStake() const
1109 {
1110     int64 nTotal = 0;
1111     LOCK(cs_wallet);
1112     for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1113     {
1114         const CWalletTx* pcoin = &(*it).second;
1115         if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1116             nTotal += CWallet::GetCredit(*pcoin);
1117     }
1118     return nTotal;
1119 }
1120
1121 int64 CWallet::GetNewMint() const
1122 {
1123     int64 nTotal = 0;
1124     LOCK(cs_wallet);
1125     for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1126     {
1127         const CWalletTx* pcoin = &(*it).second;
1128         if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1129             nTotal += CWallet::GetCredit(*pcoin);
1130     }
1131     return nTotal;
1132 }
1133
1134 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
1135 {
1136     setCoinsRet.clear();
1137     nValueRet = 0;
1138
1139     // List of values less than target
1140     pair<int64, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
1141     coinLowestLarger.first = std::numeric_limits<int64>::max();
1142     coinLowestLarger.second.first = NULL;
1143     vector<pair<int64, pair<const CWalletTx*,unsigned int> > > vValue;
1144     int64 nTotalLower = 0;
1145
1146     random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
1147
1148     BOOST_FOREACH(COutput output, vCoins)
1149     {
1150         const CWalletTx *pcoin = output.tx;
1151
1152         if (output.nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs))
1153             continue;
1154
1155         int i = output.i;
1156
1157         // Follow the timestamp rules
1158         if (pcoin->nTime > nSpendTime)
1159             continue;
1160
1161         int64 n = pcoin->vout[i].nValue;
1162
1163         pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1164
1165         if (n == nTargetValue)
1166         {
1167             setCoinsRet.insert(coin.second);
1168             nValueRet += coin.first;
1169             return true;
1170         }
1171         else if (n < nTargetValue + CENT)
1172         {
1173             vValue.push_back(coin);
1174             nTotalLower += n;
1175         }
1176         else if (n < coinLowestLarger.first)
1177         {
1178             coinLowestLarger = coin;
1179         }
1180     }
1181
1182     if (nTotalLower == nTargetValue)
1183     {
1184         for (unsigned int i = 0; i < vValue.size(); ++i)
1185         {
1186             setCoinsRet.insert(vValue[i].second);
1187             nValueRet += vValue[i].first;
1188         }
1189         return true;
1190     }
1191
1192     if (nTotalLower < nTargetValue)
1193     {
1194         if (coinLowestLarger.second.first == NULL)
1195             return false;
1196         setCoinsRet.insert(coinLowestLarger.second);
1197         nValueRet += coinLowestLarger.first;
1198         return true;
1199     }
1200
1201     // Solve subset sum by stochastic approximation
1202     sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
1203     vector<char> vfBest;
1204     int64 nBest;
1205
1206     ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);
1207     if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT)
1208         ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000);
1209
1210     // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
1211     //                                   or the next bigger coin is closer), return the bigger coin
1212     if (coinLowestLarger.second.first &&
1213         ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest))
1214     {
1215         setCoinsRet.insert(coinLowestLarger.second);
1216         nValueRet += coinLowestLarger.first;
1217     }
1218     else {
1219         for (unsigned int i = 0; i < vValue.size(); i++)
1220             if (vfBest[i])
1221             {
1222                 setCoinsRet.insert(vValue[i].second);
1223                 nValueRet += vValue[i].first;
1224             }
1225
1226         if (fDebug && GetBoolArg("-printpriority"))
1227         {
1228             //// debug print
1229             printf("SelectCoins() best subset: ");
1230             for (unsigned int i = 0; i < vValue.size(); i++)
1231                 if (vfBest[i])
1232                     printf("%s ", FormatMoney(vValue[i].first).c_str());
1233             printf("total %s\n", FormatMoney(nBest).c_str());
1234         }
1235     }
1236
1237     return true;
1238 }
1239
1240 bool CWallet::SelectCoins(int64 nTargetValue, unsigned int nSpendTime, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet, const CCoinControl* coinControl) const
1241 {
1242     vector<COutput> vCoins;
1243     AvailableCoins(vCoins, true, coinControl);
1244
1245     // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
1246     if (coinControl && coinControl->HasSelected())
1247     {
1248         BOOST_FOREACH(const COutput& out, vCoins)
1249         {
1250             nValueRet += out.tx->vout[out.i].nValue;
1251             setCoinsRet.insert(make_pair(out.tx, out.i));
1252         }
1253         return (nValueRet >= nTargetValue);
1254     }
1255
1256     return (SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 6, vCoins, setCoinsRet, nValueRet) ||
1257             SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 1, vCoins, setCoinsRet, nValueRet) ||
1258             SelectCoinsMinConf(nTargetValue, nSpendTime, 0, 1, vCoins, setCoinsRet, nValueRet));
1259 }
1260
1261 // Select some coins without random shuffle or best subset approximation
1262 bool CWallet::SelectCoinsSimple(int64 nTargetValue, unsigned int nSpendTime, int nMinConf, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
1263 {
1264     vector<COutput> vCoins;
1265     AvailableCoinsMinConf(vCoins, nMinConf);
1266
1267     setCoinsRet.clear();
1268     nValueRet = 0;
1269
1270     BOOST_FOREACH(COutput output, vCoins)
1271     {
1272         const CWalletTx *pcoin = output.tx;
1273         int i = output.i;
1274
1275         // Stop if we've chosen enough inputs
1276         if (nValueRet >= nTargetValue)
1277             break;
1278
1279         // Follow the timestamp rules
1280         if (pcoin->nTime > nSpendTime)
1281             continue;
1282
1283         int64 n = pcoin->vout[i].nValue;
1284
1285         pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1286
1287         if (n >= nTargetValue)
1288         {
1289             // If input value is greater or equal to target then simply insert
1290             //    it into the current subset and exit
1291             setCoinsRet.insert(coin.second);
1292             nValueRet += coin.first;
1293             break;
1294         }
1295         else if (n < nTargetValue + CENT)
1296         {
1297             setCoinsRet.insert(coin.second);
1298             nValueRet += coin.first;
1299         }
1300     }
1301
1302     return true;
1303 }
1304
1305 bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, const CCoinControl* coinControl)
1306 {
1307     int64 nValue = 0;
1308     BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1309     {
1310         if (nValue < 0)
1311             return false;
1312         nValue += s.second;
1313     }
1314     if (vecSend.empty() || nValue < 0)
1315         return false;
1316
1317     wtxNew.BindWallet(this);
1318
1319     {
1320         LOCK2(cs_main, cs_wallet);
1321         {
1322             nFeeRet = nTransactionFee;
1323             while (true)
1324             {
1325                 wtxNew.vin.clear();
1326                 wtxNew.vout.clear();
1327                 wtxNew.fFromMe = true;
1328
1329                 int64 nTotalValue = nValue + nFeeRet;
1330                 double dPriority = 0;
1331                 // vouts to the payees
1332                 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1333                     wtxNew.vout.push_back(CTxOut(s.second, s.first));
1334
1335                 // Choose coins to use
1336                 set<pair<const CWalletTx*,unsigned int> > setCoins;
1337                 int64 nValueIn = 0;
1338                 if (!SelectCoins(nTotalValue, wtxNew.nTime, setCoins, nValueIn, coinControl))
1339                     return false;
1340                 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1341                 {
1342                     int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
1343                     dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
1344                 }
1345
1346                 int64 nChange = nValueIn - nValue - nFeeRet;
1347                 // if sub-cent change is required, the fee must be raised to at least MIN_TX_FEE
1348                 // or until nChange becomes zero
1349                 // NOTE: this depends on the exact behaviour of GetMinFee
1350                 if (nFeeRet < MIN_TX_FEE && nChange > 0 && nChange < CENT)
1351                 {
1352                     int64 nMoveToFee = min(nChange, MIN_TX_FEE - nFeeRet);
1353                     nChange -= nMoveToFee;
1354                     nFeeRet += nMoveToFee;
1355                 }
1356
1357                 // sub-cent change is moved to fee
1358                 if (nChange > 0 && nChange < MIN_TXOUT_AMOUNT)
1359                 {
1360                     nFeeRet += nChange;
1361                     nChange = 0;
1362                 }
1363
1364                 if (nChange > 0)
1365                 {
1366                     // Fill a vout to ourself
1367                     // TODO: pass in scriptChange instead of reservekey so
1368                     // change transaction isn't always pay-to-bitcoin-address
1369                     CScript scriptChange;
1370
1371                     // coin control: send change to custom address
1372                     if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange))
1373                         scriptChange.SetDestination(coinControl->destChange);
1374
1375                     // no coin control: send change to newly generated address
1376                     else
1377                     {
1378                         // Note: We use a new key here to keep it from being obvious which side is the change.
1379                         //  The drawback is that by not reusing a previous key, the change may be lost if a
1380                         //  backup is restored, if the backup doesn't have the new private key for the change.
1381                         //  If we reused the old key, it would be possible to add code to look for and
1382                         //  rediscover unknown transactions that were written with keys of ours to recover
1383                         //  post-backup change.
1384
1385                         // Reserve a new key pair from key pool
1386                         CPubKey vchPubKey = reservekey.GetReservedKey();
1387
1388                         scriptChange.SetDestination(vchPubKey.GetID());
1389                     }
1390
1391                     // Insert change txn at random position:
1392                     vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
1393                     wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
1394                 }
1395                 else
1396                     reservekey.ReturnKey();
1397
1398                 // Fill vin
1399                 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1400                     wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
1401
1402                 // Sign
1403                 int nIn = 0;
1404                 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1405                     if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
1406                         return false;
1407
1408                 // Limit size
1409                 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
1410                 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1411                     return false;
1412                 dPriority /= nBytes;
1413
1414                 // Check that enough fee is included
1415                 int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
1416                 int64 nMinFee = wtxNew.GetMinFee(1, false, GMF_SEND, nBytes);
1417                 if (nFeeRet < max(nPayFee, nMinFee))
1418                 {
1419                     nFeeRet = max(nPayFee, nMinFee);
1420                     continue;
1421                 }
1422
1423                 // Fill vtxPrev by copying from previous transactions vtxPrev
1424                 wtxNew.AddSupportingTransactions();
1425                 wtxNew.fTimeReceivedIsTxTime = true;
1426
1427                 break;
1428             }
1429         }
1430     }
1431     return true;
1432 }
1433
1434 bool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, const CCoinControl* coinControl)
1435 {
1436     vector< pair<CScript, int64> > vecSend;
1437     vecSend.push_back(make_pair(scriptPubKey, nValue));
1438     return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, coinControl);
1439 }
1440
1441 // NovaCoin: get current stake weight
1442 bool CWallet::GetStakeWeight(const CKeyStore& keystore, uint64& nMinWeight, uint64& nMaxWeight, uint64& nWeight)
1443 {
1444     // Choose coins to use
1445     int64 nBalance = GetBalance();
1446     int64 nReserveBalance = 0;
1447
1448     if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
1449     {
1450         error("GetStakeWeight : invalid reserve balance amount");
1451         return false;
1452     }
1453
1454     if (nBalance <= nReserveBalance)
1455         return false;
1456
1457     vector<const CWalletTx*> vwtxPrev;
1458     set<pair<const CWalletTx*,unsigned int> > setCoins;
1459     int64 nValueIn = 0;
1460
1461     if (!SelectCoinsSimple(nBalance - nReserveBalance, GetTime(), nCoinbaseMaturity * 10, setCoins, nValueIn))
1462         return false;
1463
1464     if (setCoins.empty())
1465         return false;
1466
1467     CCoinsViewCache &view = *pcoinsTip;
1468     BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1469     {
1470         CCoins coins;
1471         {
1472             LOCK2(cs_main, cs_wallet);
1473             if (!view.GetCoinsReadOnly(pcoin.first->GetHash(), coins))
1474                 continue;
1475         }
1476
1477         int64 nTimeWeight = GetWeight((int64)pcoin.first->nTime, (int64)GetTime());
1478         CBigNum bnCoinDayWeight = CBigNum(pcoin.first->vout[pcoin.second].nValue) * nTimeWeight / COIN / (24 * 60 * 60);
1479
1480         // Weight is greater than zero
1481         if (nTimeWeight > 0)
1482         {
1483             nWeight += bnCoinDayWeight.getuint64();
1484         }
1485
1486         // Weight is greater than zero, but the maximum value isn't reached yet
1487         if (nTimeWeight > 0 && nTimeWeight < nStakeMaxAge)
1488         {
1489             nMinWeight += bnCoinDayWeight.getuint64();
1490         }
1491
1492         // Maximum weight was reached
1493         if (nTimeWeight == nStakeMaxAge)
1494         {
1495             nMaxWeight += bnCoinDayWeight.getuint64();
1496         }
1497     }
1498
1499     return true;
1500 }
1501
1502 bool CWallet::CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int64 nSearchInterval, CTransaction& txNew, CKey& key)
1503 {
1504     // The following combine threshold is important to security
1505     // Should not be adjusted if you don't understand the consequences
1506     int64 nCombineThreshold = GetProofOfWorkReward(GetLastBlockIndex(pindexBest, false)->nBits) / 3;
1507     CBlockIndex* pindexPrev = pindexBest;
1508     CBigNum bnTargetPerCoinDay;
1509     bnTargetPerCoinDay.SetCompact(nBits);
1510
1511     txNew.vin.clear();
1512     txNew.vout.clear();
1513
1514     // Mark coin stake transaction
1515     CScript scriptEmpty;
1516     scriptEmpty.clear();
1517     txNew.vout.push_back(CTxOut(0, scriptEmpty));
1518
1519     // Choose coins to use
1520     int64 nBalance = GetBalance();
1521     int64 nReserveBalance = 0;
1522
1523     if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
1524         return error("CreateCoinStake : invalid reserve balance amount");
1525
1526     if (nBalance <= nReserveBalance)
1527         return false;
1528
1529     vector<const CWalletTx*> vwtxPrev;
1530     set<pair<const CWalletTx*,unsigned int> > setCoins;
1531     int64 nValueIn = 0;
1532
1533     // Select coins with suitable depth
1534     if (!SelectCoinsSimple(nBalance - nReserveBalance, txNew.nTime, nCoinbaseMaturity * 10, setCoins, nValueIn))
1535         return false;
1536
1537     if (setCoins.empty())
1538         return false;
1539
1540     int64 nCredit = 0;
1541     CScript scriptPubKeyKernel;
1542
1543     CCoinsViewCache &view = *pcoinsTip;
1544     BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1545     {
1546         CCoins coins;
1547         {
1548             LOCK2(cs_main, cs_wallet);
1549             if (!view.GetCoinsReadOnly(pcoin.first->GetHash(), coins))
1550                 continue;
1551         }
1552
1553         static int nMaxStakeSearchInterval = 60;
1554         if (coins.nBlockTime + nStakeMinAge > txNew.nTime - nMaxStakeSearchInterval)
1555             continue; // only count coins meeting min age requirement
1556
1557         // Read block header
1558         CBlock block;
1559         unsigned int nTxPos = 0;
1560         {
1561             LOCK2(cs_main, cs_wallet);
1562             CBlockIndex *pindex = FindBlockByHeight(coins.nHeight);
1563
1564             if (!block.ReadFromDisk(pindex))
1565                 continue;
1566
1567             BOOST_FOREACH(const CTransaction &tx, block.vtx) {
1568                 if (tx.GetHash() == pcoin.first->GetHash()) {
1569                     break;
1570                 }
1571                 nTxPos += tx.GetSerializeSize(SER_DISK, CLIENT_VERSION);
1572             }
1573             nTxPos += GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - (2 * GetSizeOfCompactSize(0)) + GetSizeOfCompactSize(block.vtx.size());
1574         }
1575
1576
1577         bool fFatal = false;
1578         bool fKernelFound = false;
1579         for (unsigned int n=0; n<min(nSearchInterval,(int64)nMaxStakeSearchInterval) && !fKernelFound && !fShutdown && pindexPrev == pindexBest; n++)
1580         {
1581             // Search backward in time from the given txNew timestamp 
1582             // Search nSearchInterval seconds back up to nMaxStakeSearchInterval
1583             uint256 hashProofOfStake = 0, targetProofOfStake = 0;
1584             COutPoint prevoutStake = COutPoint(pcoin.first->GetHash(), pcoin.second);
1585             if (CheckStakeKernelHash(nBits, block, nTxPos, *pcoin.first, prevoutStake, txNew.nTime - n, hashProofOfStake, targetProofOfStake, fFatal, true))
1586             {
1587                 // Found a kernel
1588                 if (fDebug && GetBoolArg("-printcoinstake"))
1589                     printf("CreateCoinStake : kernel found\n");
1590                 vector<valtype> vSolutions;
1591                 txnouttype whichType;
1592                 CScript scriptPubKeyOut;
1593                 scriptPubKeyKernel = pcoin.first->vout[pcoin.second].scriptPubKey;
1594                 if (!Solver(scriptPubKeyKernel, whichType, vSolutions))
1595                 {
1596                     if (fDebug && GetBoolArg("-printcoinstake"))
1597                         printf("CreateCoinStake : failed to parse kernel\n");
1598                     break;
1599                 }
1600                 if (fDebug && GetBoolArg("-printcoinstake"))
1601                     printf("CreateCoinStake : parsed kernel type=%d\n", whichType);
1602                 if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH)
1603                 {
1604                     if (fDebug && GetBoolArg("-printcoinstake"))
1605                         printf("CreateCoinStake : no support for kernel type=%d\n", whichType);
1606                     break;  // only support pay to public key and pay to address
1607                 }
1608                 if (whichType == TX_PUBKEYHASH) // pay to address type
1609                 {
1610                     // convert to pay to public key type
1611                     if (!keystore.GetKey(uint160(vSolutions[0]), key))
1612                     {
1613                         if (fDebug && GetBoolArg("-printcoinstake"))
1614                             printf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1615                         break;  // unable to find corresponding public key
1616                     }
1617                     scriptPubKeyOut << key.GetPubKey() << OP_CHECKSIG;
1618                 }
1619                 if (whichType == TX_PUBKEY)
1620                 {
1621                     valtype& vchPubKey = vSolutions[0];
1622                     if (!keystore.GetKey(Hash160(vchPubKey), key))
1623                     {
1624                         if (fDebug && GetBoolArg("-printcoinstake"))
1625                             printf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1626                         break;  // unable to find corresponding public key
1627                     }
1628
1629                 if (key.GetPubKey() != vchPubKey)
1630                 {
1631                     if (fDebug && GetBoolArg("-printcoinstake"))
1632                         printf("CreateCoinStake : invalid key for kernel type=%d\n", whichType);
1633                         break; // keys mismatch
1634                     }
1635
1636                     scriptPubKeyOut = scriptPubKeyKernel;
1637                 }
1638
1639                 txNew.nTime -= n;
1640                 txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1641                 nCredit += pcoin.first->vout[pcoin.second].nValue;
1642                 vwtxPrev.push_back(pcoin.first);
1643                 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
1644
1645                 if (GetWeight(block.GetBlockTime(), (int64)txNew.nTime) < nStakeMaxAge)
1646                     txNew.vout.push_back(CTxOut(0, scriptPubKeyOut)); //split stake
1647                 if (fDebug && GetBoolArg("-printcoinstake"))
1648                     printf("CreateCoinStake : added kernel type=%d\n", whichType);
1649                 fKernelFound = true;
1650                 break;
1651             }
1652         }
1653
1654         if (fKernelFound || fShutdown)
1655             break; // if kernel is found stop searching
1656     }
1657
1658     if (nCredit == 0 || nCredit > nBalance - nReserveBalance)
1659         return false;
1660
1661     BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1662     {
1663         // Attempt to add more inputs
1664         // Only add coins of the same key/address as kernel
1665         if (txNew.vout.size() == 2 && ((pcoin.first->vout[pcoin.second].scriptPubKey == scriptPubKeyKernel || pcoin.first->vout[pcoin.second].scriptPubKey == txNew.vout[1].scriptPubKey))
1666             && pcoin.first->GetHash() != txNew.vin[0].prevout.hash)
1667         {
1668             int64 nTimeWeight = GetWeight((int64)pcoin.first->nTime, (int64)txNew.nTime);
1669
1670             // Stop adding more inputs if already too many inputs
1671             if (txNew.vin.size() >= 100)
1672                 break;
1673             // Stop adding more inputs if value is already pretty significant
1674             if (nCredit > nCombineThreshold)
1675                 break;
1676             // Stop adding inputs if reached reserve limit
1677             if (nCredit + pcoin.first->vout[pcoin.second].nValue > nBalance - nReserveBalance)
1678                 break;
1679             // Do not add additional significant input
1680             if (pcoin.first->vout[pcoin.second].nValue > nCombineThreshold)
1681                 continue;
1682             // Do not add input that is still too young
1683             if (nTimeWeight < nStakeMaxAge)
1684                 continue;
1685
1686             txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1687             nCredit += pcoin.first->vout[pcoin.second].nValue;
1688             vwtxPrev.push_back(pcoin.first);
1689         }
1690     }
1691
1692     // Calculate coin age reward
1693     {
1694         uint64 nCoinAge;
1695
1696         if (!txNew.GetCoinAge(nCoinAge))
1697             return error("CreateCoinStake : failed to calculate coin age");
1698         nCredit += GetProofOfStakeReward(nCoinAge, nBits, txNew.nTime);
1699     }
1700
1701     int64 nMinFee = 0;
1702     while (true)
1703     {
1704         // Set output amount
1705         if (txNew.vout.size() == 3)
1706         {
1707             txNew.vout[1].nValue = ((nCredit - nMinFee) / 2 / CENT) * CENT;
1708             txNew.vout[2].nValue = nCredit - nMinFee - txNew.vout[1].nValue;
1709         }
1710         else
1711             txNew.vout[1].nValue = nCredit - nMinFee;
1712
1713         // Sign
1714         int nIn = 0;
1715         BOOST_FOREACH(const CWalletTx* pcoin, vwtxPrev)
1716         {
1717             if (!SignSignature(*this, *pcoin, txNew, nIn++))
1718                 return error("CreateCoinStake : failed to sign coinstake");
1719         }
1720
1721         // Limit size
1722         unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION);
1723         if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1724             return error("CreateCoinStake : exceeded coinstake size limit");
1725
1726         // Check enough fee is paid
1727         if (nMinFee < txNew.GetMinFee() - MIN_TX_FEE)
1728         {
1729             nMinFee = txNew.GetMinFee() - MIN_TX_FEE;
1730             continue; // try signing again
1731         }
1732         else
1733         {
1734             if (fDebug && GetBoolArg("-printfee"))
1735                 printf("CreateCoinStake : fee for coinstake %s\n", FormatMoney(nMinFee).c_str());
1736             break;
1737         }
1738     }
1739
1740     // Successfully generated coinstake
1741     return true;
1742 }
1743
1744
1745 // Call after CreateTransaction unless you want to abort
1746 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
1747 {
1748     {
1749         LOCK2(cs_main, cs_wallet);
1750         printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
1751         {
1752             // This is only to keep the database open to defeat the auto-flush for the
1753             // duration of this scope.  This is the only place where this optimization
1754             // maybe makes sense; please don't do it anywhere else.
1755             CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
1756
1757             // Take key pair from key pool so it won't be used again
1758             reservekey.KeepKey();
1759
1760             // Add tx to wallet, because if it has change it's also ours,
1761             // otherwise just for transaction history.
1762             AddToWallet(wtxNew);
1763
1764             // Mark old coins as spent
1765             set<CWalletTx*> setCoins;
1766             BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
1767             {
1768                 CWalletTx &coin = mapWallet[txin.prevout.hash];
1769                 coin.BindWallet(this);
1770                 coin.MarkSpent(txin.prevout.n);
1771                 coin.WriteToDisk();
1772                 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
1773             }
1774
1775             if (fFileBacked)
1776                 delete pwalletdb;
1777         }
1778
1779         // Track how many getdata requests our transaction gets
1780         mapRequestCount[wtxNew.GetHash()] = 0;
1781
1782         // Broadcast
1783         if (!wtxNew.AcceptToMemoryPool())
1784         {
1785             // This must not fail. The transaction has already been signed and recorded.
1786             printf("CommitTransaction() : Error: Transaction not valid");
1787             return false;
1788         }
1789         wtxNew.RelayWalletTransaction();
1790     }
1791     return true;
1792 }
1793
1794
1795
1796
1797 string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1798 {
1799     CReserveKey reservekey(this);
1800     int64 nFeeRequired;
1801
1802     if (IsLocked())
1803     {
1804         string strError = _("Error: Wallet locked, unable to create transaction  ");
1805         printf("SendMoney() : %s", strError.c_str());
1806         return strError;
1807     }
1808     if (fWalletUnlockMintOnly)
1809     {
1810         string strError = _("Error: Wallet unlocked for block minting only, unable to create transaction.");
1811         printf("SendMoney() : %s", strError.c_str());
1812         return strError;
1813     }
1814     if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
1815     {
1816         string strError;
1817         if (nValue + nFeeRequired > GetBalance())
1818             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());
1819         else
1820             strError = _("Error: Transaction creation failed  ");
1821         printf("SendMoney() : %s", strError.c_str());
1822         return strError;
1823     }
1824
1825     if (fAskFee && !uiInterface.ThreadSafeAskFee(nFeeRequired, _("Sending...")))
1826         return "ABORTED";
1827
1828     if (!CommitTransaction(wtxNew, reservekey))
1829         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.");
1830
1831     return "";
1832 }
1833
1834
1835
1836 string CWallet::SendMoneyToDestination(const CTxDestination& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1837 {
1838     // Check amount
1839     if (nValue <= 0)
1840         return _("Invalid amount");
1841     if (nValue + nTransactionFee > GetBalance())
1842         return _("Insufficient funds");
1843
1844     // Parse Bitcoin address
1845     CScript scriptPubKey;
1846     scriptPubKey.SetDestination(address);
1847
1848     return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
1849 }
1850
1851
1852
1853
1854 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
1855 {
1856     if (!fFileBacked)
1857         return DB_LOAD_OK;
1858     fFirstRunRet = false;
1859     DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
1860     if (nLoadWalletRet == DB_NEED_REWRITE)
1861     {
1862         if (CDB::Rewrite(strWalletFile, "\x04pool"))
1863         {
1864             setKeyPool.clear();
1865             // Note: can't top-up keypool here, because wallet is locked.
1866             // User will be prompted to unlock wallet the next operation
1867             // the requires a new key.
1868         }
1869     }
1870
1871     if (nLoadWalletRet != DB_LOAD_OK)
1872         return nLoadWalletRet;
1873     fFirstRunRet = !vchDefaultKey.IsValid();
1874
1875     NewThread(ThreadFlushWalletDB, &strWalletFile);
1876     return DB_LOAD_OK;
1877 }
1878
1879
1880 bool CWallet::SetAddressBookName(const CTxDestination& address, const string& strName)
1881 {
1882     std::map<CTxDestination, std::string>::iterator mi = mapAddressBook.find(address);
1883     mapAddressBook[address] = strName;
1884     NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address), (mi == mapAddressBook.end()) ? CT_NEW : CT_UPDATED);
1885     if (!fFileBacked)
1886         return false;
1887     return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName);
1888 }
1889
1890 bool CWallet::DelAddressBookName(const CTxDestination& address)
1891 {
1892     mapAddressBook.erase(address);
1893     NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address), CT_DELETED);
1894     if (!fFileBacked)
1895         return false;
1896     return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString());
1897 }
1898
1899
1900 void CWallet::PrintWallet(const CBlock& block)
1901 {
1902     {
1903         LOCK(cs_wallet);
1904         if (block.IsProofOfWork() && mapWallet.count(block.vtx[0].GetHash()))
1905         {
1906             CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
1907             printf("    mine:  %d  %d  %"PRI64d"", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
1908         }
1909         if (block.IsProofOfStake() && mapWallet.count(block.vtx[1].GetHash()))
1910         {
1911             CWalletTx& wtx = mapWallet[block.vtx[1].GetHash()];
1912             printf("    stake: %d  %d  %"PRI64d"", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
1913          }
1914
1915     }
1916     printf("\n");
1917 }
1918
1919 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
1920 {
1921     {
1922         LOCK(cs_wallet);
1923         map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
1924         if (mi != mapWallet.end())
1925         {
1926             wtx = (*mi).second;
1927             return true;
1928         }
1929     }
1930     return false;
1931 }
1932
1933 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
1934 {
1935     if (fFileBacked)
1936     {
1937         if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
1938             return false;
1939     }
1940     vchDefaultKey = vchPubKey;
1941     return true;
1942 }
1943
1944 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
1945 {
1946     if (!pwallet->fFileBacked)
1947         return false;
1948     strWalletFileOut = pwallet->strWalletFile;
1949     return true;
1950 }
1951
1952 //
1953 // Mark old keypool keys as used,
1954 // and generate all new keys
1955 //
1956 bool CWallet::NewKeyPool()
1957 {
1958     {
1959         LOCK(cs_wallet);
1960         CWalletDB walletdb(strWalletFile);
1961         BOOST_FOREACH(int64 nIndex, setKeyPool)
1962             walletdb.ErasePool(nIndex);
1963         setKeyPool.clear();
1964
1965         if (IsLocked())
1966             return false;
1967
1968         int64 nKeys = max(GetArg("-keypool", 100), (int64)0);
1969         for (int i = 0; i < nKeys; i++)
1970         {
1971             int64 nIndex = i+1;
1972             walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
1973             setKeyPool.insert(nIndex);
1974         }
1975         printf("CWallet::NewKeyPool wrote %"PRI64d" new keys\n", nKeys);
1976     }
1977     return true;
1978 }
1979
1980 bool CWallet::TopUpKeyPool(unsigned int nSize)
1981 {
1982     {
1983         LOCK(cs_wallet);
1984
1985         if (IsLocked())
1986             return false;
1987
1988         CWalletDB walletdb(strWalletFile);
1989
1990         // Top up key pool
1991         unsigned int nTargetSize;
1992         if (nSize > 0)
1993             nTargetSize = nSize;
1994         else
1995             nTargetSize = max(GetArg("-keypool", 100), 0LL);
1996
1997         while (setKeyPool.size() < (nTargetSize + 1))
1998         {
1999             int64 nEnd = 1;
2000             if (!setKeyPool.empty())
2001                 nEnd = *(--setKeyPool.end()) + 1;
2002             if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
2003                 throw runtime_error("TopUpKeyPool() : writing generated key failed");
2004             setKeyPool.insert(nEnd);
2005             printf("keypool added key %"PRI64d", size=%"PRIszu"\n", nEnd, setKeyPool.size());
2006         }
2007     }
2008     return true;
2009 }
2010
2011 void CWallet::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool)
2012 {
2013     nIndex = -1;
2014     keypool.vchPubKey = CPubKey();
2015     {
2016         LOCK(cs_wallet);
2017
2018         if (!IsLocked())
2019             TopUpKeyPool();
2020
2021         // Get the oldest key
2022         if(setKeyPool.empty())
2023             return;
2024
2025         CWalletDB walletdb(strWalletFile);
2026
2027         nIndex = *(setKeyPool.begin());
2028         setKeyPool.erase(setKeyPool.begin());
2029         if (!walletdb.ReadPool(nIndex, keypool))
2030             throw runtime_error("ReserveKeyFromKeyPool() : read failed");
2031         if (!HaveKey(keypool.vchPubKey.GetID()))
2032             throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
2033         assert(keypool.vchPubKey.IsValid());
2034         if (fDebug && GetBoolArg("-printkeypool"))
2035             printf("keypool reserve %"PRI64d"\n", nIndex);
2036     }
2037 }
2038
2039 int64 CWallet::AddReserveKey(const CKeyPool& keypool)
2040 {
2041     {
2042         LOCK2(cs_main, cs_wallet);
2043         CWalletDB walletdb(strWalletFile);
2044
2045         int64 nIndex = 1 + *(--setKeyPool.end());
2046         if (!walletdb.WritePool(nIndex, keypool))
2047             throw runtime_error("AddReserveKey() : writing added key failed");
2048         setKeyPool.insert(nIndex);
2049         return nIndex;
2050     }
2051     return -1;
2052 }
2053
2054 void CWallet::KeepKey(int64 nIndex)
2055 {
2056     // Remove from key pool
2057     if (fFileBacked)
2058     {
2059         CWalletDB walletdb(strWalletFile);
2060         walletdb.ErasePool(nIndex);
2061     }
2062     if(fDebug)
2063         printf("keypool keep %"PRI64d"\n", nIndex);
2064 }
2065
2066 void CWallet::ReturnKey(int64 nIndex)
2067 {
2068     // Return to key pool
2069     {
2070         LOCK(cs_wallet);
2071         setKeyPool.insert(nIndex);
2072     }
2073     if(fDebug)
2074         printf("keypool return %"PRI64d"\n", nIndex);
2075 }
2076
2077 bool CWallet::GetKeyFromPool(CPubKey& result, bool fAllowReuse)
2078 {
2079     int64 nIndex = 0;
2080     CKeyPool keypool;
2081     {
2082         LOCK(cs_wallet);
2083         ReserveKeyFromKeyPool(nIndex, keypool);
2084         if (nIndex == -1)
2085         {
2086             if (fAllowReuse && vchDefaultKey.IsValid())
2087             {
2088                 result = vchDefaultKey;
2089                 return true;
2090             }
2091             if (IsLocked()) return false;
2092             result = GenerateNewKey();
2093             return true;
2094         }
2095         KeepKey(nIndex);
2096         result = keypool.vchPubKey;
2097     }
2098     return true;
2099 }
2100
2101 int64 CWallet::GetOldestKeyPoolTime()
2102 {
2103     int64 nIndex = 0;
2104     CKeyPool keypool;
2105     ReserveKeyFromKeyPool(nIndex, keypool);
2106     if (nIndex == -1)
2107         return GetTime();
2108     ReturnKey(nIndex);
2109     return keypool.nTime;
2110 }
2111
2112 std::map<CTxDestination, int64> CWallet::GetAddressBalances()
2113 {
2114     map<CTxDestination, int64> balances;
2115
2116     {
2117         LOCK(cs_wallet);
2118         BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2119         {
2120             CWalletTx *pcoin = &walletEntry.second;
2121
2122             if (!pcoin->IsFinal() || !pcoin->IsTrusted())
2123                 continue;
2124
2125             if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0)
2126                 continue;
2127
2128             int nDepth = pcoin->GetDepthInMainChain();
2129             if (nDepth < (pcoin->IsFromMe() ? 0 : 1))
2130                 continue;
2131
2132             for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2133             {
2134                 CTxDestination addr;
2135                 if (!IsMine(pcoin->vout[i]))
2136                     continue;
2137                 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr))
2138                     continue;
2139
2140                 int64 n = pcoin->IsSpent(i) ? 0 : pcoin->vout[i].nValue;
2141
2142                 if (!balances.count(addr))
2143                     balances[addr] = 0;
2144                 balances[addr] += n;
2145             }
2146         }
2147     }
2148
2149     return balances;
2150 }
2151
2152 set< set<CTxDestination> > CWallet::GetAddressGroupings()
2153 {
2154     set< set<CTxDestination> > groupings;
2155     set<CTxDestination> grouping;
2156
2157     BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2158     {
2159         CWalletTx *pcoin = &walletEntry.second;
2160
2161         if (pcoin->vin.size() > 0 && IsMine(pcoin->vin[0]))
2162         {
2163             // group all input addresses with each other
2164             BOOST_FOREACH(CTxIn txin, pcoin->vin)
2165             {
2166                 CTxDestination address;
2167                 if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
2168                     continue;
2169                 grouping.insert(address);
2170             }
2171
2172             // group change with input addresses
2173             BOOST_FOREACH(CTxOut txout, pcoin->vout)
2174                 if (IsChange(txout))
2175                 {
2176                     CWalletTx tx = mapWallet[pcoin->vin[0].prevout.hash];
2177                     CTxDestination txoutAddr;
2178                     if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
2179                         continue;
2180                     grouping.insert(txoutAddr);
2181                 }
2182             groupings.insert(grouping);
2183             grouping.clear();
2184         }
2185
2186         // group lone addrs by themselves
2187         for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2188             if (IsMine(pcoin->vout[i]))
2189             {
2190                 CTxDestination address;
2191                 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address))
2192                     continue;
2193                 grouping.insert(address);
2194                 groupings.insert(grouping);
2195                 grouping.clear();
2196             }
2197     }
2198
2199     set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
2200     map< CTxDestination, set<CTxDestination>* > setmap;  // map addresses to the unique group containing it
2201     BOOST_FOREACH(set<CTxDestination> grouping, groupings)
2202     {
2203         // make a set of all the groups hit by this new group
2204         set< set<CTxDestination>* > hits;
2205         map< CTxDestination, set<CTxDestination>* >::iterator it;
2206         BOOST_FOREACH(CTxDestination address, grouping)
2207             if ((it = setmap.find(address)) != setmap.end())
2208                 hits.insert((*it).second);
2209
2210         // merge all hit groups into a new single group and delete old groups
2211         set<CTxDestination>* merged = new set<CTxDestination>(grouping);
2212         BOOST_FOREACH(set<CTxDestination>* hit, hits)
2213         {
2214             merged->insert(hit->begin(), hit->end());
2215             uniqueGroupings.erase(hit);
2216             delete hit;
2217         }
2218         uniqueGroupings.insert(merged);
2219
2220         // update setmap
2221         BOOST_FOREACH(CTxDestination element, *merged)
2222             setmap[element] = merged;
2223     }
2224
2225     set< set<CTxDestination> > ret;
2226     BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings)
2227     {
2228         ret.insert(*uniqueGrouping);
2229         delete uniqueGrouping;
2230     }
2231
2232     return ret;
2233 }
2234
2235 // 1. check 'spent' consistency between wallet and coins database
2236 // 2. fix wallet spent state according to coins database
2237 // 3. remove orphaned coinstakes and coinbases from wallet
2238 void CWallet::FixSpentCoins(int& nMismatchFound, int64& nBalanceInQuestion, bool fCheckOnly)
2239 {
2240     nMismatchFound = 0;
2241     nBalanceInQuestion = 0;
2242
2243     LOCK(cs_wallet);
2244     vector<CWalletTx*> vCoins;
2245     vCoins.reserve(mapWallet.size());
2246     for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2247         vCoins.push_back(&(*it).second);
2248
2249     CCoinsViewCache &view = *pcoinsTip;
2250     BOOST_FOREACH(CWalletTx* pcoin, vCoins)
2251     {
2252         uint256 hash = pcoin->GetHash();
2253         if(!view.HaveCoins(hash))
2254             continue;
2255
2256         // Find the corresponding transaction index
2257         CCoins &coins = view.GetCoins(hash);
2258
2259         for (unsigned int n=0; n < pcoin->vout.size(); n++)
2260         {
2261             bool fUpdated = false;
2262             if (IsMine(pcoin->vout[n]))
2263             {
2264                 if (pcoin->IsSpent(n) && coins.IsAvailable(n))
2265                 {
2266                     printf("FixSpentCoins found lost coin %snvc %s[%d], %s\n",
2267                         FormatMoney(pcoin->vout[n].nValue).c_str(), hash.ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2268                     nMismatchFound++;
2269                     nBalanceInQuestion += pcoin->vout[n].nValue;
2270                     if (!fCheckOnly)
2271                     {
2272                         fUpdated = true;
2273                         pcoin->MarkUnspent(n);
2274                         pcoin->WriteToDisk();
2275                     }
2276                 }
2277                 else if (!pcoin->IsSpent(n) && !coins.IsAvailable(n))
2278                 {
2279                     printf("FixSpentCoins found spent coin %snvc %s[%d], %s\n",
2280                         FormatMoney(pcoin->vout[n].nValue).c_str(), hash.ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2281                     nMismatchFound++;
2282                     nBalanceInQuestion += pcoin->vout[n].nValue;
2283                     if (!fCheckOnly)
2284                     {
2285                         fUpdated = true;
2286                         pcoin->MarkSpent(n);
2287                         pcoin->WriteToDisk();
2288                     }
2289                 }
2290
2291                 if (fUpdated)
2292                     NotifyTransactionChanged(this, hash, CT_UPDATED);
2293             }
2294         }
2295
2296         if((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetDepthInMainChain() == 0)
2297         {
2298             if (!fCheckOnly)
2299             {
2300                 EraseFromWallet(hash);
2301                 NotifyTransactionChanged(this, hash, CT_DELETED);
2302             }
2303
2304             printf("FixSpentCoins %s orphaned generation tx %s\n", fCheckOnly ? "found" : "removed", hash.ToString().c_str());
2305         }
2306     }
2307 }
2308
2309 // ppcoin: disable transaction (only for coinstake)
2310 void CWallet::DisableTransaction(const CTransaction &tx)
2311 {
2312     if (!tx.IsCoinStake() || !IsFromMe(tx))
2313         return; // only disconnecting coinstake requires marking input unspent
2314
2315     LOCK(cs_wallet);
2316     BOOST_FOREACH(const CTxIn& txin, tx.vin)
2317     {
2318         map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
2319         if (mi != mapWallet.end())
2320         {
2321             CWalletTx& prev = (*mi).second;
2322             if (txin.prevout.n < prev.vout.size() && IsMine(prev.vout[txin.prevout.n]))
2323             {
2324                 prev.MarkUnspent(txin.prevout.n);
2325                 prev.WriteToDisk();
2326             }
2327         }
2328     }
2329 }
2330
2331 CPubKey CReserveKey::GetReservedKey()
2332 {
2333     if (nIndex == -1)
2334     {
2335         CKeyPool keypool;
2336         pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
2337         if (nIndex != -1)
2338             vchPubKey = keypool.vchPubKey;
2339         else
2340         {
2341             printf("CReserveKey::GetReservedKey(): Warning: Using default key instead of a new key, top up your keypool!");
2342             vchPubKey = pwallet->vchDefaultKey;
2343         }
2344     }
2345     assert(vchPubKey.IsValid());
2346     return vchPubKey;
2347 }
2348
2349 void CReserveKey::KeepKey()
2350 {
2351     if (nIndex != -1)
2352         pwallet->KeepKey(nIndex);
2353     nIndex = -1;
2354     vchPubKey = CPubKey();
2355 }
2356
2357 void CReserveKey::ReturnKey()
2358 {
2359     if (nIndex != -1)
2360         pwallet->ReturnKey(nIndex);
2361     nIndex = -1;
2362     vchPubKey = CPubKey();
2363 }
2364
2365 void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
2366 {
2367     setAddress.clear();
2368
2369     CWalletDB walletdb(strWalletFile);
2370
2371     LOCK2(cs_main, cs_wallet);
2372     BOOST_FOREACH(const int64& id, setKeyPool)
2373     {
2374         CKeyPool keypool;
2375         if (!walletdb.ReadPool(id, keypool))
2376             throw runtime_error("GetAllReserveKeyHashes() : read failed");
2377         assert(keypool.vchPubKey.IsValid());
2378         CKeyID keyID = keypool.vchPubKey.GetID();
2379         if (!HaveKey(keyID))
2380             throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
2381         setAddress.insert(keyID);
2382     }
2383 }
2384
2385 void CWallet::UpdatedTransaction(const uint256 &hashTx)
2386 {
2387     {
2388         LOCK(cs_wallet);
2389         // Only notify UI if this transaction is in this wallet
2390         map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
2391         if (mi != mapWallet.end())
2392             NotifyTransactionChanged(this, hashTx, CT_UPDATED);
2393     }
2394 }
2395
2396 void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64> &mapKeyBirth) const {
2397     mapKeyBirth.clear();
2398
2399     // get birth times for keys with metadata
2400     for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++)
2401         if (it->second.nCreateTime)
2402             mapKeyBirth[it->first] = it->second.nCreateTime;
2403
2404     // map in which we'll infer heights of other keys
2405     CBlockIndex *pindexMax = FindBlockByHeight(std::max(0, nBestHeight - 144)); // the tip can be reorganised; use a 144-block safety margin
2406     std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
2407     std::set<CKeyID> setKeys;
2408     GetKeys(setKeys);
2409     BOOST_FOREACH(const CKeyID &keyid, setKeys) {
2410         if (mapKeyBirth.count(keyid) == 0)
2411             mapKeyFirstBlock[keyid] = pindexMax;
2412     }
2413     setKeys.clear();
2414
2415     // if there are no such keys, we're done
2416     if (mapKeyFirstBlock.empty())
2417         return;
2418
2419     // find first block that affects those keys, if there are any left
2420     std::vector<CKeyID> vAffected;
2421     for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
2422         // iterate over all wallet transactions...
2423         const CWalletTx &wtx = (*it).second;
2424         std::map<uint256, CBlockIndex*>::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
2425         if (blit != mapBlockIndex.end() && blit->second->IsInMainChain()) {
2426             // ... which are already in a block
2427             int nHeight = blit->second->nHeight;
2428             BOOST_FOREACH(const CTxOut &txout, wtx.vout) {
2429                 // iterate over all their outputs
2430                 ::ExtractAffectedKeys(*this, txout.scriptPubKey, vAffected);
2431                 BOOST_FOREACH(const CKeyID &keyid, vAffected) {
2432                     // ... and all their affected keys
2433                     std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
2434                     if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
2435                         rit->second = blit->second;
2436                 }
2437                 vAffected.clear();
2438             }
2439         }
2440     }
2441
2442     // Extract block timestamps for those keys
2443     for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
2444         mapKeyBirth[it->first] = it->second->nTime - 7200; // block times can be 2h off
2445 }