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