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