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