]> Git Repo - VerusCoin.git/blame - src/wallet.cpp
Merge pull request #5632
[VerusCoin.git] / src / wallet.cpp
CommitLineData
b2120e22 1// Copyright (c) 2009-2010 Satoshi Nakamoto
f914f1a7 2// Copyright (c) 2009-2014 The Bitcoin Core developers
5b40d886 3// Distributed under the MIT software license, see the accompanying
3a25a2b9 4// file COPYING or http://www.opensource.org/licenses/mit-license.php.
e8ef3da7 5
9eace6b1 6#include "wallet.h"
51ed9ec9 7
10254401 8#include "base58.h"
3e1cf9b6 9#include "checkpoints.h"
6a86c24d 10#include "coincontrol.h"
0689f46c 11#include "net.h"
e088d65a 12#include "script/script.h"
13#include "script/sign.h"
14f888ca 14#include "timedata.h"
ad49c256
WL
15#include "util.h"
16#include "utilmoneystr.h"
51ed9ec9 17
d0c4197e
PK
18#include <assert.h>
19
cae686d3 20#include <boost/algorithm/string/replace.hpp>
ad49c256 21#include <boost/thread.hpp>
e8ef3da7
WL
22
23using namespace std;
24
5b40d886
MF
25/**
26 * Settings
27 */
c6cb21d1 28CFeeRate payTxFee(DEFAULT_TRANSACTION_FEE);
aa279d61 29CAmount maxTxFee = DEFAULT_TRANSACTION_MAXFEE;
b33d1f5e 30unsigned int nTxConfirmTarget = 1;
1bbca249 31bool bSpendZeroConfChange = true;
c1c9d5b4 32bool fSendFreeTransactions = false;
ed3e5e46 33bool fPayAtLeastCustomFee = true;
e8ef3da7 34
5b40d886
MF
35/**
36 * Fees smaller than this (in satoshi) are considered zero fee (for transaction creation)
37 * Override with -mintxfee
38 */
9b1627d1 39CFeeRate CWallet::minTxFee = CFeeRate(1000);
13fc83c7 40
5b40d886
MF
41/** @defgroup mapWallet
42 *
43 * @{
44 */
e8ef3da7 45
d650f96d
CM
46struct CompareValueOnly
47{
a372168e
MF
48 bool operator()(const pair<CAmount, pair<const CWalletTx*, unsigned int> >& t1,
49 const pair<CAmount, pair<const CWalletTx*, unsigned int> >& t2) const
d650f96d
CM
50 {
51 return t1.first < t2.first;
52 }
53};
54
ad49c256
WL
55std::string COutput::ToString() const
56{
2c2cc5da 57 return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString(), i, nDepth, FormatMoney(tx->vout[i].nValue));
ad49c256
WL
58}
59
93a18a36
GA
60const CWalletTx* CWallet::GetWalletTx(const uint256& hash) const
61{
62 LOCK(cs_wallet);
63 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(hash);
64 if (it == mapWallet.end())
65 return NULL;
66 return &(it->second);
67}
68
fd61d6f5 69CPubKey CWallet::GenerateNewKey()
9976cf07 70{
95691680 71 AssertLockHeld(cs_wallet); // mapKeyMetadata
439e1497 72 bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
38067c18 73
dfa23b94
PW
74 CKey secret;
75 secret.MakeNewKey(fCompressed);
38067c18
PW
76
77 // Compressed public keys were introduced in version 0.6.0
78 if (fCompressed)
439e1497 79 SetMinVersion(FEATURE_COMPRPUBKEY);
38067c18 80
dfa23b94 81 CPubKey pubkey = secret.GetPubKey();
d0c41a73 82 assert(secret.VerifyPubKey(pubkey));
4addb2c0
PW
83
84 // Create new metadata
51ed9ec9 85 int64_t nCreationTime = GetTime();
4addb2c0
PW
86 mapKeyMetadata[pubkey.GetID()] = CKeyMetadata(nCreationTime);
87 if (!nTimeFirstKey || nCreationTime < nTimeFirstKey)
88 nTimeFirstKey = nCreationTime;
89
dfa23b94 90 if (!AddKeyPubKey(secret, pubkey))
9976cf07 91 throw std::runtime_error("CWallet::GenerateNewKey() : AddKey failed");
dfa23b94 92 return pubkey;
9976cf07 93}
e8ef3da7 94
4addb2c0 95bool CWallet::AddKeyPubKey(const CKey& secret, const CPubKey &pubkey)
e8ef3da7 96{
95691680 97 AssertLockHeld(cs_wallet); // mapKeyMetadata
dfa23b94 98 if (!CCryptoKeyStore::AddKeyPubKey(secret, pubkey))
acd65016 99 return false;
ccca27a7
CL
100
101 // check if we need to remove from watch-only
102 CScript script;
103 script = GetScriptForDestination(pubkey.GetID());
104 if (HaveWatchOnly(script))
105 RemoveWatchOnly(script);
106
e8ef3da7
WL
107 if (!fFileBacked)
108 return true;
dfa23b94 109 if (!IsCrypted()) {
3869fb89
JG
110 return CWalletDB(strWalletFile).WriteKey(pubkey,
111 secret.GetPrivKey(),
4addb2c0 112 mapKeyMetadata[pubkey.GetID()]);
dfa23b94 113 }
84c3c2eb 114 return true;
4e87d341
MC
115}
116
3869fb89 117bool CWallet::AddCryptedKey(const CPubKey &vchPubKey,
4addb2c0 118 const vector<unsigned char> &vchCryptedSecret)
4e87d341
MC
119{
120 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
121 return false;
122 if (!fFileBacked)
123 return true;
96f34cd5 124 {
f8dcd5ca 125 LOCK(cs_wallet);
96f34cd5 126 if (pwalletdbEncryption)
3869fb89
JG
127 return pwalletdbEncryption->WriteCryptedKey(vchPubKey,
128 vchCryptedSecret,
4addb2c0 129 mapKeyMetadata[vchPubKey.GetID()]);
96f34cd5 130 else
3869fb89
JG
131 return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey,
132 vchCryptedSecret,
4addb2c0 133 mapKeyMetadata[vchPubKey.GetID()]);
96f34cd5 134 }
0767e691 135 return false;
4e87d341
MC
136}
137
4addb2c0
PW
138bool CWallet::LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &meta)
139{
95691680 140 AssertLockHeld(cs_wallet); // mapKeyMetadata
4addb2c0
PW
141 if (meta.nCreateTime && (!nTimeFirstKey || meta.nCreateTime < nTimeFirstKey))
142 nTimeFirstKey = meta.nCreateTime;
143
144 mapKeyMetadata[pubkey.GetID()] = meta;
145 return true;
146}
147
2f15e86a
GA
148bool CWallet::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
149{
150 return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret);
151}
152
922e8e29 153bool CWallet::AddCScript(const CScript& redeemScript)
e679ec96 154{
922e8e29 155 if (!CCryptoKeyStore::AddCScript(redeemScript))
e679ec96
GA
156 return false;
157 if (!fFileBacked)
158 return true;
922e8e29 159 return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript);
e679ec96
GA
160}
161
18116b06
WL
162bool CWallet::LoadCScript(const CScript& redeemScript)
163{
164 /* A sanity check was added in pull #3843 to avoid adding redeemScripts
165 * that never can be redeemed. However, old wallets may still contain
166 * these. Do not add them to the wallet and warn. */
167 if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
168 {
066e2a14 169 std::string strAddr = CBitcoinAddress(CScriptID(redeemScript)).ToString();
18116b06
WL
170 LogPrintf("%s: Warning: This wallet contains a redeemScript of size %i which exceeds maximum size %i thus can never be redeemed. Do not use address %s.\n",
171 __func__, redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr);
172 return true;
173 }
174
175 return CCryptoKeyStore::AddCScript(redeemScript);
176}
177
d5087d1b 178bool CWallet::AddWatchOnly(const CScript &dest)
c8988460
PW
179{
180 if (!CCryptoKeyStore::AddWatchOnly(dest))
181 return false;
182 nTimeFirstKey = 1; // No birthday information for watch-only keys.
939ed973 183 NotifyWatchonlyChanged(true);
c8988460
PW
184 if (!fFileBacked)
185 return true;
186 return CWalletDB(strWalletFile).WriteWatchOnly(dest);
187}
188
ccca27a7
CL
189bool CWallet::RemoveWatchOnly(const CScript &dest)
190{
191 AssertLockHeld(cs_wallet);
192 if (!CCryptoKeyStore::RemoveWatchOnly(dest))
193 return false;
194 if (!HaveWatchOnly())
195 NotifyWatchonlyChanged(false);
196 if (fFileBacked)
197 if (!CWalletDB(strWalletFile).EraseWatchOnly(dest))
198 return false;
199
200 return true;
201}
202
d5087d1b 203bool CWallet::LoadWatchOnly(const CScript &dest)
c8988460 204{
c8988460
PW
205 return CCryptoKeyStore::AddWatchOnly(dest);
206}
207
94f778bd 208bool CWallet::Unlock(const SecureString& strWalletPassphrase)
4e87d341 209{
6cc4a62c
GA
210 CCrypter crypter;
211 CKeyingMaterial vMasterKey;
4e87d341 212
f8dcd5ca
PW
213 {
214 LOCK(cs_wallet);
4e87d341
MC
215 BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
216 {
217 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
218 return false;
219 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
92f2c1fe 220 continue; // try another master key
4e87d341
MC
221 if (CCryptoKeyStore::Unlock(vMasterKey))
222 return true;
223 }
f8dcd5ca 224 }
4e87d341
MC
225 return false;
226}
227
94f778bd 228bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
4e87d341 229{
6cc4a62c 230 bool fWasLocked = IsLocked();
4e87d341 231
6cc4a62c 232 {
f8dcd5ca 233 LOCK(cs_wallet);
4e87d341
MC
234 Lock();
235
236 CCrypter crypter;
237 CKeyingMaterial vMasterKey;
238 BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
239 {
240 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
241 return false;
6cc4a62c 242 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
4e87d341
MC
243 return false;
244 if (CCryptoKeyStore::Unlock(vMasterKey))
245 {
51ed9ec9 246 int64_t nStartTime = GetTimeMillis();
ddebdd9a
MC
247 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
248 pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
249
250 nStartTime = GetTimeMillis();
251 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
252 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
253
254 if (pMasterKey.second.nDeriveIterations < 25000)
255 pMasterKey.second.nDeriveIterations = 25000;
256
881a85a2 257 LogPrintf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
ddebdd9a 258
4e87d341
MC
259 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
260 return false;
261 if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
262 return false;
263 CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
264 if (fWasLocked)
265 Lock();
266 return true;
267 }
268 }
269 }
6cc4a62c 270
4e87d341
MC
271 return false;
272}
273
ed6d0b5f
PW
274void CWallet::SetBestChain(const CBlockLocator& loc)
275{
276 CWalletDB walletdb(strWalletFile);
277 walletdb.WriteBestBlock(loc);
278}
7414733b 279
439e1497 280bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
0b807a41 281{
ca4cf5cf 282 LOCK(cs_wallet); // nWalletVersion
0b807a41
PW
283 if (nWalletVersion >= nVersion)
284 return true;
285
439e1497
PW
286 // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
287 if (fExplicit && nVersion > nWalletMaxVersion)
288 nVersion = FEATURE_LATEST;
289
0b807a41
PW
290 nWalletVersion = nVersion;
291
439e1497
PW
292 if (nVersion > nWalletMaxVersion)
293 nWalletMaxVersion = nVersion;
294
0b807a41
PW
295 if (fFileBacked)
296 {
297 CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile);
0b807a41
PW
298 if (nWalletVersion > 40000)
299 pwalletdb->WriteMinVersion(nWalletVersion);
300 if (!pwalletdbIn)
301 delete pwalletdb;
302 }
303
304 return true;
305}
306
439e1497
PW
307bool CWallet::SetMaxVersion(int nVersion)
308{
ca4cf5cf 309 LOCK(cs_wallet); // nWalletVersion, nWalletMaxVersion
439e1497
PW
310 // cannot downgrade below current version
311 if (nWalletVersion > nVersion)
312 return false;
313
314 nWalletMaxVersion = nVersion;
315
316 return true;
317}
318
3015e0bc 319set<uint256> CWallet::GetConflicts(const uint256& txid) const
731b89b8
GA
320{
321 set<uint256> result;
322 AssertLockHeld(cs_wallet);
323
324 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(txid);
325 if (it == mapWallet.end())
326 return result;
327 const CWalletTx& wtx = it->second;
328
93a18a36 329 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
731b89b8
GA
330
331 BOOST_FOREACH(const CTxIn& txin, wtx.vin)
332 {
93a18a36
GA
333 if (mapTxSpends.count(txin.prevout) <= 1)
334 continue; // No conflict if zero or one spends
335 range = mapTxSpends.equal_range(txin.prevout);
336 for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
3015e0bc 337 result.insert(it->second);
731b89b8
GA
338 }
339 return result;
340}
341
93a18a36 342void CWallet::SyncMetaData(pair<TxSpends::iterator, TxSpends::iterator> range)
731b89b8
GA
343{
344 // We want all the wallet transactions in range to have the same metadata as
345 // the oldest (smallest nOrderPos).
346 // So: find smallest nOrderPos:
347
348 int nMinOrderPos = std::numeric_limits<int>::max();
349 const CWalletTx* copyFrom = NULL;
93a18a36 350 for (TxSpends::iterator it = range.first; it != range.second; ++it)
731b89b8
GA
351 {
352 const uint256& hash = it->second;
353 int n = mapWallet[hash].nOrderPos;
354 if (n < nMinOrderPos)
355 {
356 nMinOrderPos = n;
357 copyFrom = &mapWallet[hash];
358 }
359 }
360 // Now copy data from copyFrom to rest:
93a18a36 361 for (TxSpends::iterator it = range.first; it != range.second; ++it)
731b89b8
GA
362 {
363 const uint256& hash = it->second;
364 CWalletTx* copyTo = &mapWallet[hash];
365 if (copyFrom == copyTo) continue;
366 copyTo->mapValue = copyFrom->mapValue;
367 copyTo->vOrderForm = copyFrom->vOrderForm;
368 // fTimeReceivedIsTxTime not copied on purpose
369 // nTimeReceived not copied on purpose
370 copyTo->nTimeSmart = copyFrom->nTimeSmart;
371 copyTo->fFromMe = copyFrom->fFromMe;
372 copyTo->strFromAccount = copyFrom->strFromAccount;
731b89b8
GA
373 // nOrderPos not copied on purpose
374 // cached members not copied on purpose
375 }
376}
377
5b40d886
MF
378/**
379 * Outpoint is spent if any non-conflicted transaction
380 * spends it:
381 */
93a18a36 382bool CWallet::IsSpent(const uint256& hash, unsigned int n) const
731b89b8 383{
93a18a36
GA
384 const COutPoint outpoint(hash, n);
385 pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
386 range = mapTxSpends.equal_range(outpoint);
731b89b8 387
93a18a36 388 for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
731b89b8 389 {
93a18a36
GA
390 const uint256& wtxid = it->second;
391 std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
392 if (mit != mapWallet.end() && mit->second.GetDepthInMainChain() >= 0)
393 return true; // Spent
731b89b8 394 }
93a18a36
GA
395 return false;
396}
397
398void CWallet::AddToSpends(const COutPoint& outpoint, const uint256& wtxid)
399{
400 mapTxSpends.insert(make_pair(outpoint, wtxid));
401
402 pair<TxSpends::iterator, TxSpends::iterator> range;
403 range = mapTxSpends.equal_range(outpoint);
404 SyncMetaData(range);
405}
406
407
408void CWallet::AddToSpends(const uint256& wtxid)
409{
410 assert(mapWallet.count(wtxid));
411 CWalletTx& thisTx = mapWallet[wtxid];
412 if (thisTx.IsCoinBase()) // Coinbases don't spend anything!
413 return;
414
415 BOOST_FOREACH(const CTxIn& txin, thisTx.vin)
416 AddToSpends(txin.prevout, wtxid);
731b89b8
GA
417}
418
94f778bd 419bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
4e87d341 420{
6cc4a62c
GA
421 if (IsCrypted())
422 return false;
4e87d341 423
6cc4a62c
GA
424 CKeyingMaterial vMasterKey;
425 RandAddSeedPerfmon();
4e87d341 426
6cc4a62c 427 vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
65e3a1e7 428 GetRandBytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
4e87d341 429
6cc4a62c 430 CMasterKey kMasterKey;
6cc4a62c 431 RandAddSeedPerfmon();
001a53d7 432
6cc4a62c 433 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
65e3a1e7 434 GetRandBytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
4e87d341 435
6cc4a62c 436 CCrypter crypter;
51ed9ec9 437 int64_t nStartTime = GetTimeMillis();
6cc4a62c
GA
438 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
439 kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
ddebdd9a 440
6cc4a62c
GA
441 nStartTime = GetTimeMillis();
442 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
443 kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
ddebdd9a 444
6cc4a62c
GA
445 if (kMasterKey.nDeriveIterations < 25000)
446 kMasterKey.nDeriveIterations = 25000;
ddebdd9a 447
881a85a2 448 LogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
ddebdd9a 449
6cc4a62c
GA
450 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
451 return false;
452 if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
453 return false;
4e87d341 454
6cc4a62c 455 {
f8dcd5ca 456 LOCK(cs_wallet);
4e87d341
MC
457 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
458 if (fFileBacked)
459 {
870da77d 460 assert(!pwalletdbEncryption);
96f34cd5 461 pwalletdbEncryption = new CWalletDB(strWalletFile);
870da77d
PK
462 if (!pwalletdbEncryption->TxnBegin()) {
463 delete pwalletdbEncryption;
464 pwalletdbEncryption = NULL;
0fb78eae 465 return false;
870da77d 466 }
96f34cd5 467 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
4e87d341
MC
468 }
469
470 if (!EncryptKeys(vMasterKey))
96f34cd5 471 {
870da77d 472 if (fFileBacked) {
96f34cd5 473 pwalletdbEncryption->TxnAbort();
870da77d
PK
474 delete pwalletdbEncryption;
475 }
476 // We now probably have half of our keys encrypted in memory, and half not...
477 // die and let the user reload their unencrypted wallet.
d0c4197e 478 assert(false);
96f34cd5
MC
479 }
480
0b807a41 481 // Encryption was introduced in version 0.4.0
439e1497 482 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
0b807a41 483
96f34cd5
MC
484 if (fFileBacked)
485 {
870da77d
PK
486 if (!pwalletdbEncryption->TxnCommit()) {
487 delete pwalletdbEncryption;
5b40d886 488 // We now have keys encrypted in memory, but not on disk...
870da77d 489 // die to avoid confusion and let the user reload their unencrypted wallet.
d0c4197e 490 assert(false);
870da77d 491 }
96f34cd5 492
fcfd7ff8 493 delete pwalletdbEncryption;
96f34cd5
MC
494 pwalletdbEncryption = NULL;
495 }
4e87d341 496
37971fcc
GA
497 Lock();
498 Unlock(strWalletPassphrase);
499 NewKeyPool();
4e87d341 500 Lock();
6cc4a62c 501
d764d916
GA
502 // Need to completely rewrite the wallet file; if we don't, bdb might keep
503 // bits of the unencrypted private key in slack space in the database file.
b2d3b2d6 504 CDB::Rewrite(strWalletFile);
fe4a6550 505
d764d916 506 }
ab1b288f 507 NotifyStatusChanged(this);
9e9869d0 508
4e87d341 509 return true;
e8ef3da7
WL
510}
511
51ed9ec9 512int64_t CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
da7b8c12 513{
95691680 514 AssertLockHeld(cs_wallet); // nOrderPosNext
51ed9ec9 515 int64_t nRet = nOrderPosNext++;
4291e8fe
PW
516 if (pwalletdb) {
517 pwalletdb->WriteOrderPosNext(nOrderPosNext);
518 } else {
519 CWalletDB(strWalletFile).WriteOrderPosNext(nOrderPosNext);
520 }
da7b8c12
LD
521 return nRet;
522}
523
ddb709e9 524CWallet::TxItems CWallet::OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount)
c3f95ef1 525{
95691680 526 AssertLockHeld(cs_wallet); // mapWallet
c3f95ef1
LD
527 CWalletDB walletdb(strWalletFile);
528
529 // First: get all CWalletTx and CAccountingEntry into a sorted-by-order multimap.
530 TxItems txOrdered;
531
532 // Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry
533 // would make this much faster for applications that do this a lot.
534 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
535 {
536 CWalletTx* wtx = &((*it).second);
537 txOrdered.insert(make_pair(wtx->nOrderPos, TxPair(wtx, (CAccountingEntry*)0)));
538 }
ddb709e9 539 acentries.clear();
c3f95ef1
LD
540 walletdb.ListAccountCreditDebit(strAccount, acentries);
541 BOOST_FOREACH(CAccountingEntry& entry, acentries)
542 {
543 txOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
544 }
545
546 return txOrdered;
547}
548
95d888a6
PW
549void CWallet::MarkDirty()
550{
95d888a6 551 {
f8dcd5ca 552 LOCK(cs_wallet);
95d888a6
PW
553 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
554 item.second.MarkDirty();
555 }
556}
557
731b89b8 558bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFromLoadWallet)
e8ef3da7
WL
559{
560 uint256 hash = wtxIn.GetHash();
731b89b8
GA
561
562 if (fFromLoadWallet)
563 {
564 mapWallet[hash] = wtxIn;
09ec3af1 565 mapWallet[hash].BindWallet(this);
93a18a36 566 AddToSpends(hash);
731b89b8
GA
567 }
568 else
e8ef3da7 569 {
f8dcd5ca 570 LOCK(cs_wallet);
e8ef3da7
WL
571 // Inserts only if not already there, returns tx inserted or tx found
572 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
573 CWalletTx& wtx = (*ret.first).second;
4c6e2295 574 wtx.BindWallet(this);
e8ef3da7
WL
575 bool fInsertedNew = ret.second;
576 if (fInsertedNew)
9c7722b7 577 {
e8ef3da7 578 wtx.nTimeReceived = GetAdjustedTime();
da7b8c12 579 wtx.nOrderPos = IncOrderPosNext();
c3f95ef1
LD
580
581 wtx.nTimeSmart = wtx.nTimeReceived;
4f152496 582 if (!wtxIn.hashBlock.IsNull())
c3f95ef1
LD
583 {
584 if (mapBlockIndex.count(wtxIn.hashBlock))
585 {
209377a7 586 int64_t latestNow = wtx.nTimeReceived;
587 int64_t latestEntry = 0;
c3f95ef1
LD
588 {
589 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
51ed9ec9 590 int64_t latestTolerated = latestNow + 300;
ddb709e9
LD
591 std::list<CAccountingEntry> acentries;
592 TxItems txOrdered = OrderedTxItems(acentries);
c3f95ef1
LD
593 for (TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
594 {
595 CWalletTx *const pwtx = (*it).second.first;
596 if (pwtx == &wtx)
597 continue;
598 CAccountingEntry *const pacentry = (*it).second.second;
51ed9ec9 599 int64_t nSmartTime;
c3f95ef1
LD
600 if (pwtx)
601 {
602 nSmartTime = pwtx->nTimeSmart;
603 if (!nSmartTime)
604 nSmartTime = pwtx->nTimeReceived;
605 }
606 else
607 nSmartTime = pacentry->nTime;
608 if (nSmartTime <= latestTolerated)
609 {
610 latestEntry = nSmartTime;
611 if (nSmartTime > latestNow)
612 latestNow = nSmartTime;
613 break;
614 }
615 }
616 }
617
209377a7 618 int64_t blocktime = mapBlockIndex[wtxIn.hashBlock]->GetBlockTime();
c3f95ef1
LD
619 wtx.nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
620 }
621 else
881a85a2 622 LogPrintf("AddToWallet() : found %s in block %s not in index\n",
7d9d134b
WL
623 wtxIn.GetHash().ToString(),
624 wtxIn.hashBlock.ToString());
c3f95ef1 625 }
93a18a36 626 AddToSpends(hash);
9c7722b7 627 }
e8ef3da7
WL
628
629 bool fUpdated = false;
630 if (!fInsertedNew)
631 {
632 // Merge
4f152496 633 if (!wtxIn.hashBlock.IsNull() && wtxIn.hashBlock != wtx.hashBlock)
e8ef3da7
WL
634 {
635 wtx.hashBlock = wtxIn.hashBlock;
636 fUpdated = true;
637 }
638 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
639 {
640 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
641 wtx.nIndex = wtxIn.nIndex;
642 fUpdated = true;
643 }
644 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
645 {
646 wtx.fFromMe = wtxIn.fFromMe;
647 fUpdated = true;
648 }
e8ef3da7
WL
649 }
650
651 //// debug print
7d9d134b 652 LogPrintf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
e8ef3da7
WL
653
654 // Write to disk
655 if (fInsertedNew || fUpdated)
656 if (!wtx.WriteToDisk())
657 return false;
ee4b170c 658
93a18a36
GA
659 // Break debit/credit balance caches:
660 wtx.MarkDirty();
e8ef3da7 661
fe4a6550
WL
662 // Notify UI of new or updated transaction
663 NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
cae686d3 664
665 // notify an external script when a wallet transaction comes in or is updated
666 std::string strCmd = GetArg("-walletnotify", "");
667
668 if ( !strCmd.empty())
669 {
670 boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
671 boost::thread t(runCommand, strCmd); // thread runs free
672 }
673
fe4a6550 674 }
e8ef3da7
WL
675 return true;
676}
677
5b40d886
MF
678/**
679 * Add a transaction to the wallet, or update it.
680 * pblock is optional, but should be provided if the transaction is known to be in a block.
681 * If fUpdate is true, existing transactions will be updated.
682 */
d38da59b 683bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate)
e8ef3da7 684{
e8ef3da7 685 {
53d56881 686 AssertLockHeld(cs_wallet);
8d657a65 687 bool fExisted = mapWallet.count(tx.GetHash()) != 0;
6cc4a62c 688 if (fExisted && !fUpdate) return false;
3015e0bc 689 if (fExisted || IsMine(tx) || IsFromMe(tx))
6cc4a62c
GA
690 {
691 CWalletTx wtx(this,tx);
692 // Get merkle branch if transaction was found in a block
693 if (pblock)
4b0deb3b 694 wtx.SetMerkleBranch(*pblock);
6cc4a62c
GA
695 return AddToWallet(wtx);
696 }
e8ef3da7 697 }
e8ef3da7
WL
698 return false;
699}
700
d38da59b 701void CWallet::SyncTransaction(const CTransaction& tx, const CBlock* pblock)
93a18a36 702{
55a1db4f 703 LOCK2(cs_main, cs_wallet);
d38da59b 704 if (!AddToWalletIfInvolvingMe(tx, pblock, true))
93a18a36
GA
705 return; // Not one of ours
706
707 // If a transaction changes 'conflicted' state, that changes the balance
708 // available of the outputs it spends. So force those to be
709 // recomputed, also:
710 BOOST_FOREACH(const CTxIn& txin, tx.vin)
711 {
712 if (mapWallet.count(txin.prevout.hash))
713 mapWallet[txin.prevout.hash].MarkDirty();
714 }
00588c3f
PW
715}
716
717void CWallet::EraseFromWallet(const uint256 &hash)
e8ef3da7
WL
718{
719 if (!fFileBacked)
00588c3f 720 return;
e8ef3da7 721 {
f8dcd5ca 722 LOCK(cs_wallet);
e8ef3da7
WL
723 if (mapWallet.erase(hash))
724 CWalletDB(strWalletFile).EraseTx(hash);
725 }
00588c3f 726 return;
e8ef3da7
WL
727}
728
729
c8988460 730isminetype CWallet::IsMine(const CTxIn &txin) const
e8ef3da7 731{
e8ef3da7 732 {
f8dcd5ca 733 LOCK(cs_wallet);
e8ef3da7
WL
734 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
735 if (mi != mapWallet.end())
736 {
737 const CWalletTx& prev = (*mi).second;
738 if (txin.prevout.n < prev.vout.size())
c8988460 739 return IsMine(prev.vout[txin.prevout.n]);
e8ef3da7
WL
740 }
741 }
a3e192a3 742 return ISMINE_NO;
e8ef3da7
WL
743}
744
a372168e 745CAmount CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
e8ef3da7 746{
e8ef3da7 747 {
f8dcd5ca 748 LOCK(cs_wallet);
e8ef3da7
WL
749 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
750 if (mi != mapWallet.end())
751 {
752 const CWalletTx& prev = (*mi).second;
753 if (txin.prevout.n < prev.vout.size())
d4640d7d 754 if (IsMine(prev.vout[txin.prevout.n]) & filter)
e8ef3da7
WL
755 return prev.vout[txin.prevout.n].nValue;
756 }
757 }
758 return 0;
759}
760
e679ec96
GA
761bool CWallet::IsChange(const CTxOut& txout) const
762{
2a45a494 763 // TODO: fix handling of 'change' outputs. The assumption is that any
d5087d1b 764 // payment to a script that is ours, but is not in the address book
2a45a494
GA
765 // is change. That assumption is likely to break when we implement multisignature
766 // wallets that return change back into a multi-signature-protected address;
767 // a better way of identifying which outputs are 'the send' and which are
768 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
769 // which output, if any, was change).
d5087d1b 770 if (::IsMine(*this, txout.scriptPubKey))
f8dcd5ca 771 {
d5087d1b
PW
772 CTxDestination address;
773 if (!ExtractDestination(txout.scriptPubKey, address))
774 return true;
775
f8dcd5ca
PW
776 LOCK(cs_wallet);
777 if (!mapAddressBook.count(address))
778 return true;
779 }
e679ec96
GA
780 return false;
781}
782
51ed9ec9 783int64_t CWalletTx::GetTxTime() const
e8ef3da7 784{
51ed9ec9 785 int64_t n = nTimeSmart;
c3f95ef1 786 return n ? n : nTimeReceived;
e8ef3da7
WL
787}
788
789int CWalletTx::GetRequestCount() const
790{
791 // Returns -1 if it wasn't being tracked
792 int nRequests = -1;
e8ef3da7 793 {
f8dcd5ca 794 LOCK(pwallet->cs_wallet);
e8ef3da7
WL
795 if (IsCoinBase())
796 {
797 // Generated block
4f152496 798 if (!hashBlock.IsNull())
e8ef3da7
WL
799 {
800 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
801 if (mi != pwallet->mapRequestCount.end())
802 nRequests = (*mi).second;
803 }
804 }
805 else
806 {
807 // Did anyone request this transaction?
808 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
809 if (mi != pwallet->mapRequestCount.end())
810 {
811 nRequests = (*mi).second;
812
813 // How about the block it's in?
4f152496 814 if (nRequests == 0 && !hashBlock.IsNull())
e8ef3da7
WL
815 {
816 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
817 if (mi != pwallet->mapRequestCount.end())
818 nRequests = (*mi).second;
819 else
820 nRequests = 1; // If it's in someone else's block it must have got out
821 }
822 }
823 }
824 }
825 return nRequests;
826}
827
1b4568cb 828void CWalletTx::GetAmounts(list<COutputEntry>& listReceived,
a372168e 829 list<COutputEntry>& listSent, CAmount& nFee, string& strSentAccount, const isminefilter& filter) const
e8ef3da7 830{
e07c8e91 831 nFee = 0;
e8ef3da7
WL
832 listReceived.clear();
833 listSent.clear();
834 strSentAccount = strFromAccount;
835
e8ef3da7 836 // Compute fee:
a372168e 837 CAmount nDebit = GetDebit(filter);
e8ef3da7
WL
838 if (nDebit > 0) // debit>0 means we signed/sent this transaction
839 {
a372168e 840 CAmount nValueOut = GetValueOut();
e8ef3da7
WL
841 nFee = nDebit - nValueOut;
842 }
843
e679ec96 844 // Sent/received.
5bb76550 845 for (unsigned int i = 0; i < vout.size(); ++i)
e8ef3da7 846 {
1b4568cb 847 const CTxOut& txout = vout[i];
a5c6c5d6 848 isminetype fIsMine = pwallet->IsMine(txout);
96ed6821
LD
849 // Only need to handle txouts if AT LEAST one of these is true:
850 // 1) they debit from us (sent)
851 // 2) the output is to us (received)
852 if (nDebit > 0)
853 {
854 // Don't report 'change' txouts
855 if (pwallet->IsChange(txout))
856 continue;
96ed6821 857 }
a5c6c5d6 858 else if (!(fIsMine & filter))
96ed6821
LD
859 continue;
860
861 // In either case, we need to get the destination address
10254401 862 CTxDestination address;
10254401 863 if (!ExtractDestination(txout.scriptPubKey, address))
e8ef3da7 864 {
881a85a2 865 LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
7d9d134b 866 this->GetHash().ToString());
96ed6821 867 address = CNoDestination();
e8ef3da7
WL
868 }
869
5bb76550 870 COutputEntry output = {address, txout.nValue, (int)i};
1b4568cb 871
96ed6821 872 // If we are debited by the transaction, add the output as a "sent" entry
e8ef3da7 873 if (nDebit > 0)
1b4568cb 874 listSent.push_back(output);
e8ef3da7 875
96ed6821 876 // If we are receiving the output, add it as a "received" entry
d512534c 877 if (fIsMine & filter)
1b4568cb 878 listReceived.push_back(output);
e8ef3da7
WL
879 }
880
881}
882
a372168e
MF
883void CWalletTx::GetAccountAmounts(const string& strAccount, CAmount& nReceived,
884 CAmount& nSent, CAmount& nFee, const isminefilter& filter) const
e8ef3da7 885{
e07c8e91 886 nReceived = nSent = nFee = 0;
e8ef3da7 887
a372168e 888 CAmount allFee;
e8ef3da7 889 string strSentAccount;
1b4568cb
CL
890 list<COutputEntry> listReceived;
891 list<COutputEntry> listSent;
d4640d7d 892 GetAmounts(listReceived, listSent, allFee, strSentAccount, filter);
e8ef3da7 893
e8ef3da7
WL
894 if (strAccount == strSentAccount)
895 {
1b4568cb
CL
896 BOOST_FOREACH(const COutputEntry& s, listSent)
897 nSent += s.amount;
e8ef3da7
WL
898 nFee = allFee;
899 }
e8ef3da7 900 {
f8dcd5ca 901 LOCK(pwallet->cs_wallet);
1b4568cb 902 BOOST_FOREACH(const COutputEntry& r, listReceived)
e8ef3da7 903 {
1b4568cb 904 if (pwallet->mapAddressBook.count(r.destination))
e8ef3da7 905 {
1b4568cb 906 map<CTxDestination, CAddressBookData>::const_iterator mi = pwallet->mapAddressBook.find(r.destination);
61885513 907 if (mi != pwallet->mapAddressBook.end() && (*mi).second.name == strAccount)
1b4568cb 908 nReceived += r.amount;
e8ef3da7
WL
909 }
910 else if (strAccount.empty())
911 {
1b4568cb 912 nReceived += r.amount;
e8ef3da7
WL
913 }
914 }
915 }
916}
917
722fa283 918
e8ef3da7
WL
919bool CWalletTx::WriteToDisk()
920{
921 return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
922}
923
5b40d886
MF
924/**
925 * Scan the block chain (starting in pindexStart) for transactions
926 * from or to us. If fUpdate is true, found transactions that already
927 * exist in the wallet will be updated.
928 */
e8ef3da7
WL
929int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
930{
931 int ret = 0;
75b8953a 932 int64_t nNow = GetTime();
e8ef3da7
WL
933
934 CBlockIndex* pindex = pindexStart;
e8ef3da7 935 {
55a1db4f 936 LOCK2(cs_main, cs_wallet);
39278369
CL
937
938 // no need to read and scan block, if block was created before
939 // our wallet birthday (as adjusted for block time variability)
209377a7 940 while (pindex && nTimeFirstKey && (pindex->GetBlockTime() < (nTimeFirstKey - 7200)))
39278369
CL
941 pindex = chainActive.Next(pindex);
942
943 ShowProgress(_("Rescanning..."), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup
944 double dProgressStart = Checkpoints::GuessVerificationProgress(pindex, false);
945 double dProgressTip = Checkpoints::GuessVerificationProgress(chainActive.Tip(), false);
e8ef3da7
WL
946 while (pindex)
947 {
39278369
CL
948 if (pindex->nHeight % 100 == 0 && dProgressTip - dProgressStart > 0.0)
949 ShowProgress(_("Rescanning..."), std::max(1, std::min(99, (int)((Checkpoints::GuessVerificationProgress(pindex, false) - dProgressStart) / (dProgressTip - dProgressStart) * 100))));
8da9dd07 950
e8ef3da7 951 CBlock block;
7db120d5 952 ReadBlockFromDisk(block, pindex);
e8ef3da7
WL
953 BOOST_FOREACH(CTransaction& tx, block.vtx)
954 {
d38da59b 955 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
e8ef3da7
WL
956 ret++;
957 }
4c6d41b8 958 pindex = chainActive.Next(pindex);
75b8953a
B
959 if (GetTime() >= nNow + 60) {
960 nNow = GetTime();
961 LogPrintf("Still rescanning. At block %d. Progress=%f\n", pindex->nHeight, Checkpoints::GuessVerificationProgress(pindex));
962 }
e8ef3da7 963 }
39278369 964 ShowProgress(_("Rescanning..."), 100); // hide progress dialog in GUI
e8ef3da7
WL
965 }
966 return ret;
967}
968
969void CWallet::ReacceptWalletTransactions()
970{
55a1db4f 971 LOCK2(cs_main, cs_wallet);
93a18a36 972 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
e8ef3da7 973 {
93a18a36
GA
974 const uint256& wtxid = item.first;
975 CWalletTx& wtx = item.second;
976 assert(wtx.GetHash() == wtxid);
e8ef3da7 977
93a18a36
GA
978 int nDepth = wtx.GetDepthInMainChain();
979
3015e0bc 980 if (!wtx.IsCoinBase() && nDepth < 0)
e8ef3da7 981 {
93a18a36
GA
982 // Try to add to memory pool
983 LOCK(mempool.cs);
984 wtx.AcceptToMemoryPool(false);
e8ef3da7
WL
985 }
986 }
987}
988
ae8bfd12 989void CWalletTx::RelayWalletTransaction()
e8ef3da7 990{
e8ef3da7
WL
991 if (!IsCoinBase())
992 {
5eaf91a4 993 if (GetDepthInMainChain() == 0) {
d38da59b
PW
994 LogPrintf("Relaying wtx %s\n", GetHash().ToString());
995 RelayTransaction((CTransaction)*this);
e8ef3da7
WL
996 }
997 }
998}
999
3015e0bc 1000set<uint256> CWalletTx::GetConflicts() const
731b89b8
GA
1001{
1002 set<uint256> result;
1003 if (pwallet != NULL)
1004 {
1005 uint256 myHash = GetHash();
3015e0bc 1006 result = pwallet->GetConflicts(myHash);
731b89b8
GA
1007 result.erase(myHash);
1008 }
1009 return result;
1010}
1011
e8ef3da7
WL
1012void CWallet::ResendWalletTransactions()
1013{
1014 // Do this infrequently and randomly to avoid giving away
1015 // that these are our transactions.
203d1ae6 1016 if (GetTime() < nNextResend)
e8ef3da7 1017 return;
203d1ae6
LD
1018 bool fFirst = (nNextResend == 0);
1019 nNextResend = GetTime() + GetRand(30 * 60);
e8ef3da7
WL
1020 if (fFirst)
1021 return;
1022
1023 // Only do it if there's been a new block since last time
203d1ae6 1024 if (nTimeBestReceived < nLastResend)
e8ef3da7 1025 return;
203d1ae6 1026 nLastResend = GetTime();
e8ef3da7
WL
1027
1028 // Rebroadcast any of our txes that aren't in a block yet
881a85a2 1029 LogPrintf("ResendWalletTransactions()\n");
e8ef3da7 1030 {
f8dcd5ca 1031 LOCK(cs_wallet);
e8ef3da7
WL
1032 // Sort them in chronological order
1033 multimap<unsigned int, CWalletTx*> mapSorted;
1034 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1035 {
1036 CWalletTx& wtx = item.second;
1037 // Don't rebroadcast until it's had plenty of time that
1038 // it should have gotten in already by now.
51ed9ec9 1039 if (nTimeBestReceived - (int64_t)wtx.nTimeReceived > 5 * 60)
e8ef3da7
WL
1040 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
1041 }
1042 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
1043 {
1044 CWalletTx& wtx = *item.second;
ae8bfd12 1045 wtx.RelayWalletTransaction();
e8ef3da7
WL
1046 }
1047 }
1048}
1049
5b40d886 1050/** @} */ // end of mapWallet
e8ef3da7
WL
1051
1052
1053
1054
5b40d886
MF
1055/** @defgroup Actions
1056 *
1057 * @{
1058 */
e8ef3da7
WL
1059
1060
a372168e 1061CAmount CWallet::GetBalance() const
e8ef3da7 1062{
a372168e 1063 CAmount nTotal = 0;
e8ef3da7 1064 {
55a1db4f 1065 LOCK2(cs_main, cs_wallet);
e8ef3da7
WL
1066 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1067 {
1068 const CWalletTx* pcoin = &(*it).second;
0542619d 1069 if (pcoin->IsTrusted())
8fdb7e10 1070 nTotal += pcoin->GetAvailableCredit();
e8ef3da7
WL
1071 }
1072 }
1073
e8ef3da7
WL
1074 return nTotal;
1075}
1076
a372168e 1077CAmount CWallet::GetUnconfirmedBalance() const
df5ccbd2 1078{
a372168e 1079 CAmount nTotal = 0;
df5ccbd2 1080 {
55a1db4f 1081 LOCK2(cs_main, cs_wallet);
df5ccbd2
WL
1082 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1083 {
1084 const CWalletTx* pcoin = &(*it).second;
731b89b8 1085 if (!IsFinalTx(*pcoin) || (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0))
8fdb7e10 1086 nTotal += pcoin->GetAvailableCredit();
1087 }
1088 }
1089 return nTotal;
1090}
1091
a372168e 1092CAmount CWallet::GetImmatureBalance() const
8fdb7e10 1093{
a372168e 1094 CAmount nTotal = 0;
8fdb7e10 1095 {
55a1db4f 1096 LOCK2(cs_main, cs_wallet);
8fdb7e10 1097 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1098 {
966a0e8c
PK
1099 const CWalletTx* pcoin = &(*it).second;
1100 nTotal += pcoin->GetImmatureCredit();
df5ccbd2
WL
1101 }
1102 }
1103 return nTotal;
1104}
e8ef3da7 1105
a372168e 1106CAmount CWallet::GetWatchOnlyBalance() const
ffd40da3 1107{
a372168e 1108 CAmount nTotal = 0;
ffd40da3 1109 {
39cc4922 1110 LOCK2(cs_main, cs_wallet);
ffd40da3
J
1111 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1112 {
1113 const CWalletTx* pcoin = &(*it).second;
1114 if (pcoin->IsTrusted())
1115 nTotal += pcoin->GetAvailableWatchOnlyCredit();
1116 }
1117 }
870da77d 1118
ffd40da3
J
1119 return nTotal;
1120}
1121
a372168e 1122CAmount CWallet::GetUnconfirmedWatchOnlyBalance() const
ffd40da3 1123{
a372168e 1124 CAmount nTotal = 0;
ffd40da3 1125 {
39cc4922 1126 LOCK2(cs_main, cs_wallet);
ffd40da3
J
1127 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1128 {
1129 const CWalletTx* pcoin = &(*it).second;
1130 if (!IsFinalTx(*pcoin) || (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0))
1131 nTotal += pcoin->GetAvailableWatchOnlyCredit();
1132 }
1133 }
1134 return nTotal;
1135}
1136
a372168e 1137CAmount CWallet::GetImmatureWatchOnlyBalance() const
ffd40da3 1138{
a372168e 1139 CAmount nTotal = 0;
ffd40da3 1140 {
39cc4922 1141 LOCK2(cs_main, cs_wallet);
ffd40da3
J
1142 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1143 {
1144 const CWalletTx* pcoin = &(*it).second;
1145 nTotal += pcoin->GetImmatureWatchOnlyCredit();
1146 }
1147 }
1148 return nTotal;
1149}
1150
5b40d886
MF
1151/**
1152 * populate vCoins with vector of available COutputs.
1153 */
6a86c24d 1154void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl) const
9b0369c7
CM
1155{
1156 vCoins.clear();
1157
1158 {
ea3acaf3 1159 LOCK2(cs_main, cs_wallet);
9b0369c7
CM
1160 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1161 {
93a18a36 1162 const uint256& wtxid = it->first;
9b0369c7
CM
1163 const CWalletTx* pcoin = &(*it).second;
1164
05df3fc6 1165 if (!IsFinalTx(*pcoin))
a2709fad
GA
1166 continue;
1167
0542619d 1168 if (fOnlyConfirmed && !pcoin->IsTrusted())
9b0369c7
CM
1169 continue;
1170
1171 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
1172 continue;
1173
2b72d46f
GA
1174 int nDepth = pcoin->GetDepthInMainChain();
1175 if (nDepth < 0)
1176 continue;
1177
fdbb537d 1178 for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
c8988460 1179 isminetype mine = IsMine(pcoin->vout[i]);
a3e192a3 1180 if (!(IsSpent(wtxid, i)) && mine != ISMINE_NO &&
6a86c24d
CL
1181 !IsLockedCoin((*it).first, i) && pcoin->vout[i].nValue > 0 &&
1182 (!coinControl || !coinControl->HasSelected() || coinControl->IsSelected((*it).first, i)))
8d657a65 1183 vCoins.push_back(COutput(pcoin, i, nDepth, (mine & ISMINE_SPENDABLE) != ISMINE_NO));
fdbb537d 1184 }
9b0369c7
CM
1185 }
1186 }
1187}
1188
a372168e
MF
1189static void ApproximateBestSubset(vector<pair<CAmount, pair<const CWalletTx*,unsigned int> > >vValue, const CAmount& nTotalLower, const CAmount& nTargetValue,
1190 vector<char>& vfBest, CAmount& nBest, int iterations = 1000)
831f59ce
CM
1191{
1192 vector<char> vfIncluded;
1193
1194 vfBest.assign(vValue.size(), true);
1195 nBest = nTotalLower;
1196
907a2aa4
GM
1197 seed_insecure_rand();
1198
831f59ce
CM
1199 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
1200 {
1201 vfIncluded.assign(vValue.size(), false);
a372168e 1202 CAmount nTotal = 0;
831f59ce
CM
1203 bool fReachedTarget = false;
1204 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
1205 {
1206 for (unsigned int i = 0; i < vValue.size(); i++)
1207 {
907a2aa4
GM
1208 //The solver here uses a randomized algorithm,
1209 //the randomness serves no real security purpose but is just
1210 //needed to prevent degenerate behavior and it is important
5b40d886 1211 //that the rng is fast. We do not use a constant random sequence,
907a2aa4
GM
1212 //because there may be some privacy improvement by making
1213 //the selection random.
1214 if (nPass == 0 ? insecure_rand()&1 : !vfIncluded[i])
831f59ce
CM
1215 {
1216 nTotal += vValue[i].first;
1217 vfIncluded[i] = true;
1218 if (nTotal >= nTargetValue)
1219 {
1220 fReachedTarget = true;
1221 if (nTotal < nBest)
1222 {
1223 nBest = nTotal;
1224 vfBest = vfIncluded;
1225 }
1226 nTotal -= vValue[i].first;
1227 vfIncluded[i] = false;
1228 }
1229 }
1230 }
1231 }
1232 }
1233}
1234
a372168e
MF
1235bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, int nConfMine, int nConfTheirs, vector<COutput> vCoins,
1236 set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet) const
e8ef3da7
WL
1237{
1238 setCoinsRet.clear();
1239 nValueRet = 0;
1240
1241 // List of values less than target
a372168e
MF
1242 pair<CAmount, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
1243 coinLowestLarger.first = std::numeric_limits<CAmount>::max();
e8ef3da7 1244 coinLowestLarger.second.first = NULL;
a372168e
MF
1245 vector<pair<CAmount, pair<const CWalletTx*,unsigned int> > > vValue;
1246 CAmount nTotalLower = 0;
e8ef3da7 1247
e333ab56
CM
1248 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
1249
c8988460 1250 BOOST_FOREACH(const COutput &output, vCoins)
e8ef3da7 1251 {
c8988460
PW
1252 if (!output.fSpendable)
1253 continue;
1254
9b0369c7 1255 const CWalletTx *pcoin = output.tx;
e8ef3da7 1256
a3e192a3 1257 if (output.nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? nConfMine : nConfTheirs))
9b0369c7 1258 continue;
e8ef3da7 1259
9b0369c7 1260 int i = output.i;
a372168e 1261 CAmount n = pcoin->vout[i].nValue;
e8ef3da7 1262
a372168e 1263 pair<CAmount,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
e8ef3da7 1264
9b0369c7
CM
1265 if (n == nTargetValue)
1266 {
1267 setCoinsRet.insert(coin.second);
1268 nValueRet += coin.first;
1269 return true;
1270 }
1271 else if (n < nTargetValue + CENT)
1272 {
1273 vValue.push_back(coin);
1274 nTotalLower += n;
1275 }
1276 else if (n < coinLowestLarger.first)
1277 {
1278 coinLowestLarger = coin;
e8ef3da7
WL
1279 }
1280 }
1281
831f59ce 1282 if (nTotalLower == nTargetValue)
e8ef3da7 1283 {
c376ac35 1284 for (unsigned int i = 0; i < vValue.size(); ++i)
e8ef3da7
WL
1285 {
1286 setCoinsRet.insert(vValue[i].second);
1287 nValueRet += vValue[i].first;
1288 }
1289 return true;
1290 }
1291
831f59ce 1292 if (nTotalLower < nTargetValue)
e8ef3da7
WL
1293 {
1294 if (coinLowestLarger.second.first == NULL)
1295 return false;
1296 setCoinsRet.insert(coinLowestLarger.second);
1297 nValueRet += coinLowestLarger.first;
1298 return true;
1299 }
1300
e8ef3da7 1301 // Solve subset sum by stochastic approximation
d650f96d 1302 sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
831f59ce 1303 vector<char> vfBest;
a372168e 1304 CAmount nBest;
e8ef3da7 1305
831f59ce
CM
1306 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);
1307 if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT)
1308 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000);
e8ef3da7 1309
831f59ce
CM
1310 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
1311 // or the next bigger coin is closer), return the bigger coin
1312 if (coinLowestLarger.second.first &&
1313 ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest))
e8ef3da7
WL
1314 {
1315 setCoinsRet.insert(coinLowestLarger.second);
1316 nValueRet += coinLowestLarger.first;
1317 }
1318 else {
c376ac35 1319 for (unsigned int i = 0; i < vValue.size(); i++)
e8ef3da7
WL
1320 if (vfBest[i])
1321 {
1322 setCoinsRet.insert(vValue[i].second);
1323 nValueRet += vValue[i].first;
1324 }
1325
faaeae1e 1326 LogPrint("selectcoins", "SelectCoins() best subset: ");
c376ac35 1327 for (unsigned int i = 0; i < vValue.size(); i++)
e8ef3da7 1328 if (vfBest[i])
7d9d134b
WL
1329 LogPrint("selectcoins", "%s ", FormatMoney(vValue[i].first));
1330 LogPrint("selectcoins", "total %s\n", FormatMoney(nBest));
e8ef3da7
WL
1331 }
1332
1333 return true;
1334}
1335
a372168e 1336bool CWallet::SelectCoins(const CAmount& nTargetValue, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet, const CCoinControl* coinControl) const
e8ef3da7 1337{
9b0369c7 1338 vector<COutput> vCoins;
6a86c24d
CL
1339 AvailableCoins(vCoins, true, coinControl);
1340
1341 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
1342 if (coinControl && coinControl->HasSelected())
1343 {
1344 BOOST_FOREACH(const COutput& out, vCoins)
1345 {
2935b211
WL
1346 if(!out.fSpendable)
1347 continue;
6a86c24d
CL
1348 nValueRet += out.tx->vout[out.i].nValue;
1349 setCoinsRet.insert(make_pair(out.tx, out.i));
1350 }
1351 return (nValueRet >= nTargetValue);
1352 }
9b0369c7
CM
1353
1354 return (SelectCoinsMinConf(nTargetValue, 1, 6, vCoins, setCoinsRet, nValueRet) ||
1355 SelectCoinsMinConf(nTargetValue, 1, 1, vCoins, setCoinsRet, nValueRet) ||
1bbca249 1356 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue, 0, 1, vCoins, setCoinsRet, nValueRet)));
e8ef3da7
WL
1357}
1358
1359
1360
1361
a372168e
MF
1362bool CWallet::CreateTransaction(const vector<pair<CScript, CAmount> >& vecSend,
1363 CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, std::string& strFailReason, const CCoinControl* coinControl)
e8ef3da7 1364{
a372168e
MF
1365 CAmount nValue = 0;
1366 BOOST_FOREACH (const PAIRTYPE(CScript, CAmount)& s, vecSend)
e8ef3da7
WL
1367 {
1368 if (nValue < 0)
1f00f4e9
GA
1369 {
1370 strFailReason = _("Transaction amounts must be positive");
e8ef3da7 1371 return false;
1f00f4e9 1372 }
e8ef3da7
WL
1373 nValue += s.second;
1374 }
1375 if (vecSend.empty() || nValue < 0)
1f00f4e9
GA
1376 {
1377 strFailReason = _("Transaction amounts must be positive");
e8ef3da7 1378 return false;
1f00f4e9 1379 }
e8ef3da7 1380
b33d1f5e 1381 wtxNew.fTimeReceivedIsTxTime = true;
4c6e2295 1382 wtxNew.BindWallet(this);
4949004d 1383 CMutableTransaction txNew;
e8ef3da7 1384
ba7fcc8d
PT
1385 // Discourage fee sniping.
1386 //
1387 // However because of a off-by-one-error in previous versions we need to
1388 // neuter it by setting nLockTime to at least one less than nBestHeight.
1389 // Secondly currently propagation of transactions created for block heights
1390 // corresponding to blocks that were just mined may be iffy - transactions
1391 // aren't re-accepted into the mempool - we additionally neuter the code by
1392 // going ten blocks back. Doesn't yet do anything for sniping, but does act
1393 // to shake out wallet bugs like not showing nLockTime'd transactions at
1394 // all.
1395 txNew.nLockTime = std::max(0, chainActive.Height() - 10);
1396
1397 // Secondly occasionally randomly pick a nLockTime even further back, so
1398 // that transactions that are delayed after signing for whatever reason,
1399 // e.g. high-latency mix networks and some CoinJoin implementations, have
1400 // better privacy.
1401 if (GetRandInt(10) == 0)
1402 txNew.nLockTime = std::max(0, (int)txNew.nLockTime - GetRandInt(100));
1403
1404 assert(txNew.nLockTime <= (unsigned int)chainActive.Height());
1405 assert(txNew.nLockTime < LOCKTIME_THRESHOLD);
1406
e8ef3da7 1407 {
f8dcd5ca 1408 LOCK2(cs_main, cs_wallet);
e8ef3da7 1409 {
c1c9d5b4 1410 nFeeRet = 0;
050d2e95 1411 while (true)
e8ef3da7 1412 {
4949004d
PW
1413 txNew.vin.clear();
1414 txNew.vout.clear();
e8ef3da7
WL
1415 wtxNew.fFromMe = true;
1416
a372168e 1417 CAmount nTotalValue = nValue + nFeeRet;
e8ef3da7
WL
1418 double dPriority = 0;
1419 // vouts to the payees
a372168e 1420 BOOST_FOREACH (const PAIRTYPE(CScript, CAmount)& s, vecSend)
8de9bb53
GA
1421 {
1422 CTxOut txout(s.second, s.first);
13fc83c7 1423 if (txout.IsDust(::minRelayTxFee))
1f00f4e9
GA
1424 {
1425 strFailReason = _("Transaction amount too small");
8de9bb53 1426 return false;
1f00f4e9 1427 }
4949004d 1428 txNew.vout.push_back(txout);
8de9bb53 1429 }
e8ef3da7
WL
1430
1431 // Choose coins to use
1432 set<pair<const CWalletTx*,unsigned int> > setCoins;
a372168e 1433 CAmount nValueIn = 0;
6a86c24d 1434 if (!SelectCoins(nTotalValue, setCoins, nValueIn, coinControl))
1f00f4e9
GA
1435 {
1436 strFailReason = _("Insufficient funds");
e8ef3da7 1437 return false;
1f00f4e9 1438 }
e8ef3da7
WL
1439 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1440 {
a372168e 1441 CAmount nCredit = pcoin.first->vout[pcoin.second].nValue;
d7836552
GM
1442 //The priority after the next block (depth+1) is used instead of the current,
1443 //reflecting an assumption the user would accept a bit more delay for
1444 //a chance at a free transaction.
1445 dPriority += (double)nCredit * (pcoin.first->GetDepthInMainChain()+1);
e8ef3da7
WL
1446 }
1447
a372168e 1448 CAmount nChange = nValueIn - nValue - nFeeRet;
a7dd11c6
PW
1449
1450 if (nChange > 0)
e8ef3da7 1451 {
bf798734
GA
1452 // Fill a vout to ourself
1453 // TODO: pass in scriptChange instead of reservekey so
1454 // change transaction isn't always pay-to-bitcoin-address
e8ef3da7 1455 CScript scriptChange;
6a86c24d
CL
1456
1457 // coin control: send change to custom address
1458 if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange))
0be990ba 1459 scriptChange = GetScriptForDestination(coinControl->destChange);
6a86c24d
CL
1460
1461 // no coin control: send change to newly generated address
1462 else
1463 {
1464 // Note: We use a new key here to keep it from being obvious which side is the change.
1465 // The drawback is that by not reusing a previous key, the change may be lost if a
1466 // backup is restored, if the backup doesn't have the new private key for the change.
1467 // If we reused the old key, it would be possible to add code to look for and
1468 // rediscover unknown transactions that were written with keys of ours to recover
1469 // post-backup change.
1470
1471 // Reserve a new key pair from key pool
1472 CPubKey vchPubKey;
9b59e3bd
GM
1473 bool ret;
1474 ret = reservekey.GetReservedKey(vchPubKey);
1475 assert(ret); // should never fail, as we just unlocked
6a86c24d 1476
0be990ba 1477 scriptChange = GetScriptForDestination(vchPubKey.GetID());
6a86c24d 1478 }
e8ef3da7 1479
8de9bb53
GA
1480 CTxOut newTxOut(nChange, scriptChange);
1481
1482 // Never create dust outputs; if we would, just
1483 // add the dust to the fee.
13fc83c7 1484 if (newTxOut.IsDust(::minRelayTxFee))
8de9bb53
GA
1485 {
1486 nFeeRet += nChange;
1487 reservekey.ReturnKey();
1488 }
1489 else
1490 {
1491 // Insert change txn at random position:
4949004d
PW
1492 vector<CTxOut>::iterator position = txNew.vout.begin()+GetRandInt(txNew.vout.size()+1);
1493 txNew.vout.insert(position, newTxOut);
8de9bb53 1494 }
e8ef3da7
WL
1495 }
1496 else
1497 reservekey.ReturnKey();
1498
1499 // Fill vin
ba7fcc8d
PT
1500 //
1501 // Note how the sequence number is set to max()-1 so that the
1502 // nLockTime set above actually works.
e8ef3da7 1503 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
ba7fcc8d
PT
1504 txNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second,CScript(),
1505 std::numeric_limits<unsigned int>::max()-1));
e8ef3da7
WL
1506
1507 // Sign
1508 int nIn = 0;
1509 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
4949004d 1510 if (!SignSignature(*this, *coin.first, txNew, nIn++))
1f00f4e9
GA
1511 {
1512 strFailReason = _("Signing transaction failed");
e8ef3da7 1513 return false;
1f00f4e9 1514 }
e8ef3da7 1515
4949004d
PW
1516 // Embed the constructed transaction data in wtxNew.
1517 *static_cast<CTransaction*>(&wtxNew) = CTransaction(txNew);
1518
e8ef3da7 1519 // Limit size
6b6aaa16 1520 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
41e1a0d7 1521 if (nBytes >= MAX_STANDARD_TX_SIZE)
1f00f4e9
GA
1522 {
1523 strFailReason = _("Transaction too large");
e8ef3da7 1524 return false;
1f00f4e9 1525 }
4d707d51 1526 dPriority = wtxNew.ComputePriority(dPriority, nBytes);
e8ef3da7 1527
aa279d61
GM
1528 // Can we complete this as a free transaction?
1529 if (fSendFreeTransactions && nBytes <= MAX_FREE_TRANSACTION_CREATE_SIZE)
1530 {
1531 // Not enough fee: enough priority?
1532 double dPriorityNeeded = mempool.estimatePriority(nTxConfirmTarget);
1533 // Not enough mempool history to estimate: use hard-coded AllowFree.
1534 if (dPriorityNeeded <= 0 && AllowFree(dPriority))
1535 break;
1536
1537 // Small enough, and priority high enough, to send for free
1538 if (dPriorityNeeded > 0 && dPriority >= dPriorityNeeded)
1539 break;
1540 }
b33d1f5e 1541
aa279d61 1542 CAmount nFeeNeeded = GetMinimumFee(nBytes, nTxConfirmTarget, mempool);
b33d1f5e 1543
aa279d61
GM
1544 // If we made it here and we aren't even able to meet the relay fee on the next pass, give up
1545 // because we must be at the maximum allowed fee.
1546 if (nFeeNeeded < ::minRelayTxFee.GetFee(nBytes))
e8ef3da7 1547 {
aa279d61
GM
1548 strFailReason = _("Transaction too large for fee policy");
1549 return false;
e8ef3da7
WL
1550 }
1551
aa279d61
GM
1552 if (nFeeRet >= nFeeNeeded)
1553 break; // Done, enough fee included.
b33d1f5e
GA
1554
1555 // Include more fee and try again.
1556 nFeeRet = nFeeNeeded;
1557 continue;
e8ef3da7
WL
1558 }
1559 }
1560 }
1561 return true;
1562}
1563
a372168e
MF
1564bool CWallet::CreateTransaction(CScript scriptPubKey, const CAmount& nValue,
1565 CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, std::string& strFailReason, const CCoinControl* coinControl)
e8ef3da7 1566{
a372168e 1567 vector< pair<CScript, CAmount> > vecSend;
e8ef3da7 1568 vecSend.push_back(make_pair(scriptPubKey, nValue));
6a86c24d 1569 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, strFailReason, coinControl);
e8ef3da7
WL
1570}
1571
5b40d886
MF
1572/**
1573 * Call after CreateTransaction unless you want to abort
1574 */
e8ef3da7
WL
1575bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
1576{
e8ef3da7 1577 {
f8dcd5ca 1578 LOCK2(cs_main, cs_wallet);
7d9d134b 1579 LogPrintf("CommitTransaction:\n%s", wtxNew.ToString());
e8ef3da7
WL
1580 {
1581 // This is only to keep the database open to defeat the auto-flush for the
1582 // duration of this scope. This is the only place where this optimization
1583 // maybe makes sense; please don't do it anywhere else.
1584 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
1585
1586 // Take key pair from key pool so it won't be used again
1587 reservekey.KeepKey();
1588
1589 // Add tx to wallet, because if it has change it's also ours,
1590 // otherwise just for transaction history.
1591 AddToWallet(wtxNew);
1592
93a18a36 1593 // Notify that old coins are spent
e8ef3da7
WL
1594 set<CWalletTx*> setCoins;
1595 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
1596 {
1597 CWalletTx &coin = mapWallet[txin.prevout.hash];
4c6e2295 1598 coin.BindWallet(this);
fe4a6550 1599 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
e8ef3da7
WL
1600 }
1601
1602 if (fFileBacked)
1603 delete pwalletdb;
1604 }
1605
1606 // Track how many getdata requests our transaction gets
6cc4a62c 1607 mapRequestCount[wtxNew.GetHash()] = 0;
e8ef3da7
WL
1608
1609 // Broadcast
b1f15b21 1610 if (!wtxNew.AcceptToMemoryPool(false))
e8ef3da7
WL
1611 {
1612 // This must not fail. The transaction has already been signed and recorded.
881a85a2 1613 LogPrintf("CommitTransaction() : Error: Transaction not valid");
e8ef3da7
WL
1614 return false;
1615 }
1616 wtxNew.RelayWalletTransaction();
1617 }
e8ef3da7
WL
1618 return true;
1619}
1620
a372168e 1621CAmount CWallet::GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool& pool)
b33d1f5e
GA
1622{
1623 // payTxFee is user-set "I want to pay this much"
a372168e 1624 CAmount nFeeNeeded = payTxFee.GetFee(nTxBytes);
c1c9d5b4
CL
1625 // user selected total at least (default=true)
1626 if (fPayAtLeastCustomFee && nFeeNeeded > 0 && nFeeNeeded < payTxFee.GetFeePerK())
1627 nFeeNeeded = payTxFee.GetFeePerK();
b33d1f5e
GA
1628 // User didn't set: use -txconfirmtarget to estimate...
1629 if (nFeeNeeded == 0)
1630 nFeeNeeded = pool.estimateFee(nConfirmTarget).GetFee(nTxBytes);
1631 // ... unless we don't have enough mempool data, in which case fall
1632 // back to a hard-coded fee
1633 if (nFeeNeeded == 0)
13fc83c7 1634 nFeeNeeded = minTxFee.GetFee(nTxBytes);
aa279d61
GM
1635 // prevent user from paying a non-sense fee (like 1 satoshi): 0 < fee < minRelayFee
1636 if (nFeeNeeded < ::minRelayTxFee.GetFee(nTxBytes))
1637 nFeeNeeded = ::minRelayTxFee.GetFee(nTxBytes);
1638 // But always obey the maximum
1639 if (nFeeNeeded > maxTxFee)
1640 nFeeNeeded = maxTxFee;
b33d1f5e
GA
1641 return nFeeNeeded;
1642}
1643
e8ef3da7
WL
1644
1645
1646
eed1785f 1647DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
e8ef3da7
WL
1648{
1649 if (!fFileBacked)
4f76be1d 1650 return DB_LOAD_OK;
e8ef3da7 1651 fFirstRunRet = false;
eed1785f 1652 DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
d764d916 1653 if (nLoadWalletRet == DB_NEED_REWRITE)
9e9869d0 1654 {
d764d916
GA
1655 if (CDB::Rewrite(strWalletFile, "\x04pool"))
1656 {
012ca1c9 1657 LOCK(cs_wallet);
d764d916
GA
1658 setKeyPool.clear();
1659 // Note: can't top-up keypool here, because wallet is locked.
1660 // User will be prompted to unlock wallet the next operation
1661 // the requires a new key.
1662 }
9e9869d0
PW
1663 }
1664
7ec55267
MC
1665 if (nLoadWalletRet != DB_LOAD_OK)
1666 return nLoadWalletRet;
fd61d6f5 1667 fFirstRunRet = !vchDefaultKey.IsValid();
e8ef3da7 1668
39278369
CL
1669 uiInterface.LoadWallet(this);
1670
116df55e 1671 return DB_LOAD_OK;
e8ef3da7
WL
1672}
1673
ae3d0aba 1674
77cbd462 1675DBErrors CWallet::ZapWalletTx(std::vector<CWalletTx>& vWtx)
518f3bda
JG
1676{
1677 if (!fFileBacked)
1678 return DB_LOAD_OK;
77cbd462 1679 DBErrors nZapWalletTxRet = CWalletDB(strWalletFile,"cr+").ZapWalletTx(this, vWtx);
518f3bda
JG
1680 if (nZapWalletTxRet == DB_NEED_REWRITE)
1681 {
1682 if (CDB::Rewrite(strWalletFile, "\x04pool"))
1683 {
1684 LOCK(cs_wallet);
1685 setKeyPool.clear();
1686 // Note: can't top-up keypool here, because wallet is locked.
1687 // User will be prompted to unlock wallet the next operation
5b40d886 1688 // that requires a new key.
518f3bda
JG
1689 }
1690 }
1691
1692 if (nZapWalletTxRet != DB_LOAD_OK)
1693 return nZapWalletTxRet;
1694
1695 return DB_LOAD_OK;
1696}
1697
1698
a41d5fe0 1699bool CWallet::SetAddressBook(const CTxDestination& address, const string& strName, const string& strPurpose)
ae3d0aba 1700{
ca4cf5cf
GA
1701 bool fUpdated = false;
1702 {
1703 LOCK(cs_wallet); // mapAddressBook
1704 std::map<CTxDestination, CAddressBookData>::iterator mi = mapAddressBook.find(address);
1705 fUpdated = mi != mapAddressBook.end();
1706 mapAddressBook[address].name = strName;
1707 if (!strPurpose.empty()) /* update purpose only if requested */
1708 mapAddressBook[address].purpose = strPurpose;
1709 }
8d657a65 1710 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != ISMINE_NO,
ca4cf5cf 1711 strPurpose, (fUpdated ? CT_UPDATED : CT_NEW) );
ae3d0aba
WL
1712 if (!fFileBacked)
1713 return false;
a41d5fe0
GA
1714 if (!strPurpose.empty() && !CWalletDB(strWalletFile).WritePurpose(CBitcoinAddress(address).ToString(), strPurpose))
1715 return false;
10254401 1716 return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName);
ae3d0aba
WL
1717}
1718
a41d5fe0 1719bool CWallet::DelAddressBook(const CTxDestination& address)
ae3d0aba 1720{
b10e1470 1721 {
ca4cf5cf
GA
1722 LOCK(cs_wallet); // mapAddressBook
1723
1724 if(fFileBacked)
b10e1470 1725 {
ca4cf5cf
GA
1726 // Delete destdata tuples associated with address
1727 std::string strAddress = CBitcoinAddress(address).ToString();
1728 BOOST_FOREACH(const PAIRTYPE(string, string) &item, mapAddressBook[address].destdata)
1729 {
1730 CWalletDB(strWalletFile).EraseDestData(strAddress, item.first);
1731 }
b10e1470 1732 }
ca4cf5cf 1733 mapAddressBook.erase(address);
b10e1470
WL
1734 }
1735
8d657a65 1736 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != ISMINE_NO, "", CT_DELETED);
ca4cf5cf 1737
ae3d0aba
WL
1738 if (!fFileBacked)
1739 return false;
a41d5fe0 1740 CWalletDB(strWalletFile).ErasePurpose(CBitcoinAddress(address).ToString());
10254401 1741 return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString());
ae3d0aba
WL
1742}
1743
fd61d6f5 1744bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
ae3d0aba
WL
1745{
1746 if (fFileBacked)
1747 {
1748 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
1749 return false;
1750 }
1751 vchDefaultKey = vchPubKey;
1752 return true;
1753}
1754
5b40d886
MF
1755/**
1756 * Mark old keypool keys as used,
1757 * and generate all new keys
1758 */
37971fcc
GA
1759bool CWallet::NewKeyPool()
1760{
37971fcc 1761 {
f8dcd5ca 1762 LOCK(cs_wallet);
37971fcc 1763 CWalletDB walletdb(strWalletFile);
51ed9ec9 1764 BOOST_FOREACH(int64_t nIndex, setKeyPool)
37971fcc
GA
1765 walletdb.ErasePool(nIndex);
1766 setKeyPool.clear();
1767
1768 if (IsLocked())
1769 return false;
1770
51ed9ec9 1771 int64_t nKeys = max(GetArg("-keypool", 100), (int64_t)0);
37971fcc
GA
1772 for (int i = 0; i < nKeys; i++)
1773 {
51ed9ec9 1774 int64_t nIndex = i+1;
37971fcc
GA
1775 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
1776 setKeyPool.insert(nIndex);
1777 }
f48742c2 1778 LogPrintf("CWallet::NewKeyPool wrote %d new keys\n", nKeys);
37971fcc
GA
1779 }
1780 return true;
1781}
1782
13dd2d09 1783bool CWallet::TopUpKeyPool(unsigned int kpSize)
e8ef3da7 1784{
e8ef3da7 1785 {
f8dcd5ca
PW
1786 LOCK(cs_wallet);
1787
4e87d341
MC
1788 if (IsLocked())
1789 return false;
1790
e8ef3da7
WL
1791 CWalletDB walletdb(strWalletFile);
1792
1793 // Top up key pool
13dd2d09
JG
1794 unsigned int nTargetSize;
1795 if (kpSize > 0)
1796 nTargetSize = kpSize;
1797 else
51ed9ec9 1798 nTargetSize = max(GetArg("-keypool", 100), (int64_t) 0);
13dd2d09 1799
faf705a4 1800 while (setKeyPool.size() < (nTargetSize + 1))
e8ef3da7 1801 {
51ed9ec9 1802 int64_t nEnd = 1;
e8ef3da7
WL
1803 if (!setKeyPool.empty())
1804 nEnd = *(--setKeyPool.end()) + 1;
1805 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
4e87d341 1806 throw runtime_error("TopUpKeyPool() : writing generated key failed");
e8ef3da7 1807 setKeyPool.insert(nEnd);
783b182c 1808 LogPrintf("keypool added key %d, size=%u\n", nEnd, setKeyPool.size());
e8ef3da7 1809 }
4e87d341
MC
1810 }
1811 return true;
1812}
1813
51ed9ec9 1814void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool)
4e87d341
MC
1815{
1816 nIndex = -1;
fd61d6f5 1817 keypool.vchPubKey = CPubKey();
4e87d341 1818 {
f8dcd5ca
PW
1819 LOCK(cs_wallet);
1820
4e87d341
MC
1821 if (!IsLocked())
1822 TopUpKeyPool();
e8ef3da7
WL
1823
1824 // Get the oldest key
4e87d341
MC
1825 if(setKeyPool.empty())
1826 return;
1827
1828 CWalletDB walletdb(strWalletFile);
1829
e8ef3da7
WL
1830 nIndex = *(setKeyPool.begin());
1831 setKeyPool.erase(setKeyPool.begin());
1832 if (!walletdb.ReadPool(nIndex, keypool))
1833 throw runtime_error("ReserveKeyFromKeyPool() : read failed");
fd61d6f5 1834 if (!HaveKey(keypool.vchPubKey.GetID()))
e8ef3da7 1835 throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
fd61d6f5 1836 assert(keypool.vchPubKey.IsValid());
f48742c2 1837 LogPrintf("keypool reserve %d\n", nIndex);
e8ef3da7
WL
1838 }
1839}
1840
51ed9ec9 1841void CWallet::KeepKey(int64_t nIndex)
e8ef3da7
WL
1842{
1843 // Remove from key pool
1844 if (fFileBacked)
1845 {
1846 CWalletDB walletdb(strWalletFile);
6cc4a62c 1847 walletdb.ErasePool(nIndex);
e8ef3da7 1848 }
f48742c2 1849 LogPrintf("keypool keep %d\n", nIndex);
e8ef3da7
WL
1850}
1851
51ed9ec9 1852void CWallet::ReturnKey(int64_t nIndex)
e8ef3da7
WL
1853{
1854 // Return to key pool
f8dcd5ca
PW
1855 {
1856 LOCK(cs_wallet);
e8ef3da7 1857 setKeyPool.insert(nIndex);
f8dcd5ca 1858 }
f48742c2 1859 LogPrintf("keypool return %d\n", nIndex);
e8ef3da7
WL
1860}
1861
71ac5052 1862bool CWallet::GetKeyFromPool(CPubKey& result)
e8ef3da7 1863{
51ed9ec9 1864 int64_t nIndex = 0;
e8ef3da7 1865 CKeyPool keypool;
7db3b75b 1866 {
f8dcd5ca 1867 LOCK(cs_wallet);
ed02c95d
GA
1868 ReserveKeyFromKeyPool(nIndex, keypool);
1869 if (nIndex == -1)
7db3b75b 1870 {
ed02c95d
GA
1871 if (IsLocked()) return false;
1872 result = GenerateNewKey();
7db3b75b
GA
1873 return true;
1874 }
ed02c95d
GA
1875 KeepKey(nIndex);
1876 result = keypool.vchPubKey;
7db3b75b 1877 }
7db3b75b 1878 return true;
e8ef3da7
WL
1879}
1880
51ed9ec9 1881int64_t CWallet::GetOldestKeyPoolTime()
e8ef3da7 1882{
51ed9ec9 1883 int64_t nIndex = 0;
e8ef3da7
WL
1884 CKeyPool keypool;
1885 ReserveKeyFromKeyPool(nIndex, keypool);
4e87d341
MC
1886 if (nIndex == -1)
1887 return GetTime();
e8ef3da7
WL
1888 ReturnKey(nIndex);
1889 return keypool.nTime;
1890}
1891
a372168e 1892std::map<CTxDestination, CAmount> CWallet::GetAddressBalances()
22dfd735 1893{
a372168e 1894 map<CTxDestination, CAmount> balances;
22dfd735 1895
1896 {
1897 LOCK(cs_wallet);
1898 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
1899 {
1900 CWalletTx *pcoin = &walletEntry.second;
1901
0542619d 1902 if (!IsFinalTx(*pcoin) || !pcoin->IsTrusted())
22dfd735 1903 continue;
1904
1905 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
1906 continue;
1907
1908 int nDepth = pcoin->GetDepthInMainChain();
a3e192a3 1909 if (nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? 0 : 1))
22dfd735 1910 continue;
1911
b1093efa 1912 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
22dfd735 1913 {
b1093efa 1914 CTxDestination addr;
22dfd735 1915 if (!IsMine(pcoin->vout[i]))
1916 continue;
b1093efa
GM
1917 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr))
1918 continue;
22dfd735 1919
a372168e 1920 CAmount n = IsSpent(walletEntry.first, i) ? 0 : pcoin->vout[i].nValue;
22dfd735 1921
22dfd735 1922 if (!balances.count(addr))
1923 balances[addr] = 0;
1924 balances[addr] += n;
1925 }
1926 }
1927 }
1928
1929 return balances;
1930}
1931
b1093efa 1932set< set<CTxDestination> > CWallet::GetAddressGroupings()
22dfd735 1933{
95691680 1934 AssertLockHeld(cs_wallet); // mapWallet
b1093efa
GM
1935 set< set<CTxDestination> > groupings;
1936 set<CTxDestination> grouping;
22dfd735 1937
1938 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
1939 {
1940 CWalletTx *pcoin = &walletEntry.second;
1941
a3fad211 1942 if (pcoin->vin.size() > 0)
22dfd735 1943 {
a3fad211 1944 bool any_mine = false;
22dfd735 1945 // group all input addresses with each other
1946 BOOST_FOREACH(CTxIn txin, pcoin->vin)
b1093efa
GM
1947 {
1948 CTxDestination address;
a3fad211
GM
1949 if(!IsMine(txin)) /* If this input isn't mine, ignore it */
1950 continue;
b1093efa
GM
1951 if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
1952 continue;
1953 grouping.insert(address);
a3fad211 1954 any_mine = true;
b1093efa 1955 }
22dfd735 1956
1957 // group change with input addresses
a3fad211
GM
1958 if (any_mine)
1959 {
1960 BOOST_FOREACH(CTxOut txout, pcoin->vout)
1961 if (IsChange(txout))
1962 {
1963 CTxDestination txoutAddr;
1964 if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
1965 continue;
1966 grouping.insert(txoutAddr);
1967 }
1968 }
1969 if (grouping.size() > 0)
1970 {
1971 groupings.insert(grouping);
1972 grouping.clear();
1973 }
22dfd735 1974 }
1975
1976 // group lone addrs by themselves
b1093efa 1977 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
22dfd735 1978 if (IsMine(pcoin->vout[i]))
1979 {
b1093efa
GM
1980 CTxDestination address;
1981 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address))
1982 continue;
1983 grouping.insert(address);
22dfd735 1984 groupings.insert(grouping);
1985 grouping.clear();
1986 }
1987 }
1988
b1093efa
GM
1989 set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
1990 map< CTxDestination, set<CTxDestination>* > setmap; // map addresses to the unique group containing it
1991 BOOST_FOREACH(set<CTxDestination> grouping, groupings)
22dfd735 1992 {
1993 // make a set of all the groups hit by this new group
b1093efa
GM
1994 set< set<CTxDestination>* > hits;
1995 map< CTxDestination, set<CTxDestination>* >::iterator it;
1996 BOOST_FOREACH(CTxDestination address, grouping)
22dfd735 1997 if ((it = setmap.find(address)) != setmap.end())
1998 hits.insert((*it).second);
1999
2000 // merge all hit groups into a new single group and delete old groups
b1093efa
GM
2001 set<CTxDestination>* merged = new set<CTxDestination>(grouping);
2002 BOOST_FOREACH(set<CTxDestination>* hit, hits)
22dfd735 2003 {
2004 merged->insert(hit->begin(), hit->end());
2005 uniqueGroupings.erase(hit);
2006 delete hit;
2007 }
2008 uniqueGroupings.insert(merged);
2009
2010 // update setmap
b1093efa 2011 BOOST_FOREACH(CTxDestination element, *merged)
22dfd735 2012 setmap[element] = merged;
2013 }
2014
b1093efa
GM
2015 set< set<CTxDestination> > ret;
2016 BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings)
22dfd735 2017 {
2018 ret.insert(*uniqueGrouping);
2019 delete uniqueGrouping;
2020 }
2021
2022 return ret;
2023}
2024
3624356e
GA
2025set<CTxDestination> CWallet::GetAccountAddresses(string strAccount) const
2026{
43422a01 2027 LOCK(cs_wallet);
3624356e
GA
2028 set<CTxDestination> result;
2029 BOOST_FOREACH(const PAIRTYPE(CTxDestination, CAddressBookData)& item, mapAddressBook)
2030 {
2031 const CTxDestination& address = item.first;
2032 const string& strName = item.second.name;
2033 if (strName == strAccount)
2034 result.insert(address);
2035 }
2036 return result;
2037}
2038
360cfe14 2039bool CReserveKey::GetReservedKey(CPubKey& pubkey)
e8ef3da7
WL
2040{
2041 if (nIndex == -1)
2042 {
2043 CKeyPool keypool;
2044 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
0d7b28e5
MC
2045 if (nIndex != -1)
2046 vchPubKey = keypool.vchPubKey;
360cfe14 2047 else {
6c37f7fd 2048 return false;
cee69980 2049 }
e8ef3da7 2050 }
fd61d6f5 2051 assert(vchPubKey.IsValid());
360cfe14
PW
2052 pubkey = vchPubKey;
2053 return true;
e8ef3da7
WL
2054}
2055
2056void CReserveKey::KeepKey()
2057{
2058 if (nIndex != -1)
2059 pwallet->KeepKey(nIndex);
2060 nIndex = -1;
fd61d6f5 2061 vchPubKey = CPubKey();
e8ef3da7
WL
2062}
2063
2064void CReserveKey::ReturnKey()
2065{
2066 if (nIndex != -1)
2067 pwallet->ReturnKey(nIndex);
2068 nIndex = -1;
fd61d6f5 2069 vchPubKey = CPubKey();
e8ef3da7 2070}
ae3d0aba 2071
434e4273 2072void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
30ab2c9c
PW
2073{
2074 setAddress.clear();
2075
2076 CWalletDB walletdb(strWalletFile);
2077
f8dcd5ca 2078 LOCK2(cs_main, cs_wallet);
51ed9ec9 2079 BOOST_FOREACH(const int64_t& id, setKeyPool)
30ab2c9c
PW
2080 {
2081 CKeyPool keypool;
2082 if (!walletdb.ReadPool(id, keypool))
2083 throw runtime_error("GetAllReserveKeyHashes() : read failed");
fd61d6f5 2084 assert(keypool.vchPubKey.IsValid());
10254401
PW
2085 CKeyID keyID = keypool.vchPubKey.GetID();
2086 if (!HaveKey(keyID))
30ab2c9c 2087 throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
10254401 2088 setAddress.insert(keyID);
30ab2c9c
PW
2089 }
2090}
fe4a6550
WL
2091
2092void CWallet::UpdatedTransaction(const uint256 &hashTx)
2093{
2094 {
2095 LOCK(cs_wallet);
2096 // Only notify UI if this transaction is in this wallet
2097 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
2098 if (mi != mapWallet.end())
2099 NotifyTransactionChanged(this, hashTx, CT_UPDATED);
2100 }
2101}
fdbb537d
JG
2102
2103void CWallet::LockCoin(COutPoint& output)
2104{
95691680 2105 AssertLockHeld(cs_wallet); // setLockedCoins
fdbb537d
JG
2106 setLockedCoins.insert(output);
2107}
2108
2109void CWallet::UnlockCoin(COutPoint& output)
2110{
95691680 2111 AssertLockHeld(cs_wallet); // setLockedCoins
fdbb537d
JG
2112 setLockedCoins.erase(output);
2113}
2114
2115void CWallet::UnlockAllCoins()
2116{
95691680 2117 AssertLockHeld(cs_wallet); // setLockedCoins
fdbb537d
JG
2118 setLockedCoins.clear();
2119}
2120
2121bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const
2122{
95691680 2123 AssertLockHeld(cs_wallet); // setLockedCoins
fdbb537d
JG
2124 COutPoint outpt(hash, n);
2125
2126 return (setLockedCoins.count(outpt) > 0);
2127}
2128
2129void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts)
2130{
95691680 2131 AssertLockHeld(cs_wallet); // setLockedCoins
fdbb537d
JG
2132 for (std::set<COutPoint>::iterator it = setLockedCoins.begin();
2133 it != setLockedCoins.end(); it++) {
2134 COutPoint outpt = (*it);
2135 vOutpts.push_back(outpt);
2136 }
2137}
2138
5b40d886 2139/** @} */ // end of Actions
8b59a3d3 2140
2141class CAffectedKeysVisitor : public boost::static_visitor<void> {
2142private:
2143 const CKeyStore &keystore;
2144 std::vector<CKeyID> &vKeys;
2145
2146public:
2147 CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector<CKeyID> &vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {}
2148
2149 void Process(const CScript &script) {
2150 txnouttype type;
2151 std::vector<CTxDestination> vDest;
2152 int nRequired;
2153 if (ExtractDestinations(script, type, vDest, nRequired)) {
2154 BOOST_FOREACH(const CTxDestination &dest, vDest)
2155 boost::apply_visitor(*this, dest);
2156 }
2157 }
2158
2159 void operator()(const CKeyID &keyId) {
2160 if (keystore.HaveKey(keyId))
2161 vKeys.push_back(keyId);
2162 }
2163
2164 void operator()(const CScriptID &scriptId) {
2165 CScript script;
2166 if (keystore.GetCScript(scriptId, script))
2167 Process(script);
2168 }
2169
2170 void operator()(const CNoDestination &none) {}
2171};
2172
51ed9ec9 2173void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const {
95691680 2174 AssertLockHeld(cs_wallet); // mapKeyMetadata
434e4273
PW
2175 mapKeyBirth.clear();
2176
2177 // get birth times for keys with metadata
2178 for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++)
2179 if (it->second.nCreateTime)
2180 mapKeyBirth[it->first] = it->second.nCreateTime;
2181
2182 // map in which we'll infer heights of other keys
4c6d41b8 2183 CBlockIndex *pindexMax = chainActive[std::max(0, chainActive.Height() - 144)]; // the tip can be reorganised; use a 144-block safety margin
434e4273
PW
2184 std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
2185 std::set<CKeyID> setKeys;
2186 GetKeys(setKeys);
2187 BOOST_FOREACH(const CKeyID &keyid, setKeys) {
2188 if (mapKeyBirth.count(keyid) == 0)
2189 mapKeyFirstBlock[keyid] = pindexMax;
2190 }
2191 setKeys.clear();
2192
2193 // if there are no such keys, we're done
2194 if (mapKeyFirstBlock.empty())
2195 return;
2196
2197 // find first block that affects those keys, if there are any left
2198 std::vector<CKeyID> vAffected;
2199 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
2200 // iterate over all wallet transactions...
2201 const CWalletTx &wtx = (*it).second;
145d5be8 2202 BlockMap::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
4c6d41b8 2203 if (blit != mapBlockIndex.end() && chainActive.Contains(blit->second)) {
434e4273
PW
2204 // ... which are already in a block
2205 int nHeight = blit->second->nHeight;
2206 BOOST_FOREACH(const CTxOut &txout, wtx.vout) {
2207 // iterate over all their outputs
8b59a3d3 2208 CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey);
434e4273
PW
2209 BOOST_FOREACH(const CKeyID &keyid, vAffected) {
2210 // ... and all their affected keys
2211 std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
2212 if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
2213 rit->second = blit->second;
2214 }
2215 vAffected.clear();
2216 }
2217 }
2218 }
2219
2220 // Extract block timestamps for those keys
2221 for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
209377a7 2222 mapKeyBirth[it->first] = it->second->GetBlockTime() - 7200; // block times can be 2h off
434e4273 2223}
b10e1470
WL
2224
2225bool CWallet::AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
2226{
8476d5d4
CL
2227 if (boost::get<CNoDestination>(&dest))
2228 return false;
2229
b10e1470
WL
2230 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
2231 if (!fFileBacked)
2232 return true;
2233 return CWalletDB(strWalletFile).WriteDestData(CBitcoinAddress(dest).ToString(), key, value);
2234}
2235
2236bool CWallet::EraseDestData(const CTxDestination &dest, const std::string &key)
2237{
2238 if (!mapAddressBook[dest].destdata.erase(key))
2239 return false;
2240 if (!fFileBacked)
2241 return true;
2242 return CWalletDB(strWalletFile).EraseDestData(CBitcoinAddress(dest).ToString(), key);
2243}
2244
2245bool CWallet::LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
2246{
2247 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
2248 return true;
2249}
2250
2251bool CWallet::GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const
2252{
2253 std::map<CTxDestination, CAddressBookData>::const_iterator i = mapAddressBook.find(dest);
2254 if(i != mapAddressBook.end())
2255 {
2256 CAddressBookData::StringMap::const_iterator j = i->second.destdata.find(key);
2257 if(j != i->second.destdata.end())
2258 {
2259 if(value)
2260 *value = j->second;
2261 return true;
2262 }
2263 }
2264 return false;
2265}
af8297c0
WL
2266
2267CKeyPool::CKeyPool()
2268{
2269 nTime = GetTime();
2270}
2271
2272CKeyPool::CKeyPool(const CPubKey& vchPubKeyIn)
2273{
2274 nTime = GetTime();
2275 vchPubKey = vchPubKeyIn;
2276}
2277
2278CWalletKey::CWalletKey(int64_t nExpires)
2279{
2280 nTimeCreated = (nExpires ? GetTime() : 0);
2281 nTimeExpires = nExpires;
2282}
0101483f 2283
4b0deb3b 2284int CMerkleTx::SetMerkleBranch(const CBlock& block)
0101483f
WL
2285{
2286 AssertLockHeld(cs_main);
2287 CBlock blockTmp;
2288
4b0deb3b
DK
2289 // Update the tx's hashBlock
2290 hashBlock = block.GetHash();
0101483f 2291
4b0deb3b
DK
2292 // Locate the transaction
2293 for (nIndex = 0; nIndex < (int)block.vtx.size(); nIndex++)
2294 if (block.vtx[nIndex] == *(CTransaction*)this)
2295 break;
2296 if (nIndex == (int)block.vtx.size())
2297 {
2298 vMerkleBranch.clear();
2299 nIndex = -1;
2300 LogPrintf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
2301 return 0;
0101483f
WL
2302 }
2303
4b0deb3b
DK
2304 // Fill in merkle branch
2305 vMerkleBranch = block.GetMerkleBranch(nIndex);
2306
0101483f 2307 // Is the tx in a block that's in the main chain
145d5be8 2308 BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
0101483f
WL
2309 if (mi == mapBlockIndex.end())
2310 return 0;
4b0deb3b 2311 const CBlockIndex* pindex = (*mi).second;
0101483f
WL
2312 if (!pindex || !chainActive.Contains(pindex))
2313 return 0;
2314
2315 return chainActive.Height() - pindex->nHeight + 1;
2316}
2317
a31e8bad 2318int CMerkleTx::GetDepthInMainChainINTERNAL(const CBlockIndex* &pindexRet) const
0101483f 2319{
4f152496 2320 if (hashBlock.IsNull() || nIndex == -1)
0101483f
WL
2321 return 0;
2322 AssertLockHeld(cs_main);
2323
2324 // Find the block it claims to be in
145d5be8 2325 BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
0101483f
WL
2326 if (mi == mapBlockIndex.end())
2327 return 0;
2328 CBlockIndex* pindex = (*mi).second;
2329 if (!pindex || !chainActive.Contains(pindex))
2330 return 0;
2331
2332 // Make sure the merkle branch connects to this block
2333 if (!fMerkleVerified)
2334 {
2335 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
2336 return 0;
2337 fMerkleVerified = true;
2338 }
2339
2340 pindexRet = pindex;
2341 return chainActive.Height() - pindex->nHeight + 1;
2342}
2343
a31e8bad 2344int CMerkleTx::GetDepthInMainChain(const CBlockIndex* &pindexRet) const
0101483f
WL
2345{
2346 AssertLockHeld(cs_main);
2347 int nResult = GetDepthInMainChainINTERNAL(pindexRet);
2348 if (nResult == 0 && !mempool.exists(GetHash()))
2349 return -1; // Not in chain, not in mempool
2350
2351 return nResult;
2352}
2353
2354int CMerkleTx::GetBlocksToMaturity() const
2355{
2356 if (!IsCoinBase())
2357 return 0;
2358 return max(0, (COINBASE_MATURITY+1) - GetDepthInMainChain());
2359}
2360
2361
2362bool CMerkleTx::AcceptToMemoryPool(bool fLimitFree, bool fRejectInsaneFee)
2363{
2364 CValidationState state;
2365 return ::AcceptToMemoryPool(mempool, state, *this, fLimitFree, NULL, fRejectInsaneFee);
2366}
2367
This page took 0.589476 seconds and 4 git commands to generate.