Merge pull request #5470
[VerusCoin.git] / src / wallet.cpp
CommitLineData
b2120e22 1// Copyright (c) 2009-2010 Satoshi Nakamoto
57702541 2// Copyright (c) 2009-2014 The Bitcoin 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);
b33d1f5e 29unsigned int nTxConfirmTarget = 1;
1bbca249 30bool bSpendZeroConfChange = true;
c1c9d5b4 31bool fSendFreeTransactions = false;
ed3e5e46 32bool fPayAtLeastCustomFee = true;
e8ef3da7 33
5b40d886
MF
34/**
35 * Fees smaller than this (in satoshi) are considered zero fee (for transaction creation)
36 * Override with -mintxfee
37 */
9b1627d1 38CFeeRate CWallet::minTxFee = CFeeRate(1000);
13fc83c7 39
5b40d886
MF
40/** @defgroup mapWallet
41 *
42 * @{
43 */
e8ef3da7 44
d650f96d
CM
45struct CompareValueOnly
46{
a372168e
MF
47 bool operator()(const pair<CAmount, pair<const CWalletTx*, unsigned int> >& t1,
48 const pair<CAmount, pair<const CWalletTx*, unsigned int> >& t2) const
d650f96d
CM
49 {
50 return t1.first < t2.first;
51 }
52};
53
ad49c256
WL
54std::string COutput::ToString() const
55{
2c2cc5da 56 return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString(), i, nDepth, FormatMoney(tx->vout[i].nValue));
ad49c256
WL
57}
58
93a18a36
GA
59const CWalletTx* CWallet::GetWalletTx(const uint256& hash) const
60{
61 LOCK(cs_wallet);
62 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(hash);
63 if (it == mapWallet.end())
64 return NULL;
65 return &(it->second);
66}
67
fd61d6f5 68CPubKey CWallet::GenerateNewKey()
9976cf07 69{
95691680 70 AssertLockHeld(cs_wallet); // mapKeyMetadata
439e1497 71 bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
38067c18 72
9976cf07 73 RandAddSeedPerfmon();
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;
582 if (wtxIn.hashBlock != 0)
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
633 if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
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
798 if (hashBlock != 0)
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?
814 if (nRequests == 0 && hashBlock != 0)
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
a372168e 1528 CAmount nFeeNeeded = GetMinimumFee(nBytes, nTxConfirmTarget, mempool);
b33d1f5e
GA
1529
1530 if (nFeeRet >= nFeeNeeded)
1531 break; // Done, enough fee included.
1532
1533 // Too big to send for free? Include more fee and try again:
0ed9675b 1534 if (!fSendFreeTransactions || nBytes > MAX_FREE_TRANSACTION_CREATE_SIZE)
e8ef3da7 1535 {
b33d1f5e 1536 nFeeRet = nFeeNeeded;
e8ef3da7
WL
1537 continue;
1538 }
1539
b33d1f5e
GA
1540 // Not enough fee: enough priority?
1541 double dPriorityNeeded = mempool.estimatePriority(nTxConfirmTarget);
1542 // Not enough mempool history to estimate: use hard-coded AllowFree.
1543 if (dPriorityNeeded <= 0 && AllowFree(dPriority))
1544 break;
e8ef3da7 1545
b33d1f5e 1546 // Small enough, and priority high enough, to send for free
d88af560 1547 if (dPriorityNeeded > 0 && dPriority >= dPriorityNeeded)
b33d1f5e
GA
1548 break;
1549
1550 // Include more fee and try again.
1551 nFeeRet = nFeeNeeded;
1552 continue;
e8ef3da7
WL
1553 }
1554 }
1555 }
1556 return true;
1557}
1558
a372168e
MF
1559bool CWallet::CreateTransaction(CScript scriptPubKey, const CAmount& nValue,
1560 CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, std::string& strFailReason, const CCoinControl* coinControl)
e8ef3da7 1561{
a372168e 1562 vector< pair<CScript, CAmount> > vecSend;
e8ef3da7 1563 vecSend.push_back(make_pair(scriptPubKey, nValue));
6a86c24d 1564 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, strFailReason, coinControl);
e8ef3da7
WL
1565}
1566
5b40d886
MF
1567/**
1568 * Call after CreateTransaction unless you want to abort
1569 */
e8ef3da7
WL
1570bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
1571{
e8ef3da7 1572 {
f8dcd5ca 1573 LOCK2(cs_main, cs_wallet);
7d9d134b 1574 LogPrintf("CommitTransaction:\n%s", wtxNew.ToString());
e8ef3da7
WL
1575 {
1576 // This is only to keep the database open to defeat the auto-flush for the
1577 // duration of this scope. This is the only place where this optimization
1578 // maybe makes sense; please don't do it anywhere else.
1579 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
1580
1581 // Take key pair from key pool so it won't be used again
1582 reservekey.KeepKey();
1583
1584 // Add tx to wallet, because if it has change it's also ours,
1585 // otherwise just for transaction history.
1586 AddToWallet(wtxNew);
1587
93a18a36 1588 // Notify that old coins are spent
e8ef3da7
WL
1589 set<CWalletTx*> setCoins;
1590 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
1591 {
1592 CWalletTx &coin = mapWallet[txin.prevout.hash];
4c6e2295 1593 coin.BindWallet(this);
fe4a6550 1594 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
e8ef3da7
WL
1595 }
1596
1597 if (fFileBacked)
1598 delete pwalletdb;
1599 }
1600
1601 // Track how many getdata requests our transaction gets
6cc4a62c 1602 mapRequestCount[wtxNew.GetHash()] = 0;
e8ef3da7
WL
1603
1604 // Broadcast
b1f15b21 1605 if (!wtxNew.AcceptToMemoryPool(false))
e8ef3da7
WL
1606 {
1607 // This must not fail. The transaction has already been signed and recorded.
881a85a2 1608 LogPrintf("CommitTransaction() : Error: Transaction not valid");
e8ef3da7
WL
1609 return false;
1610 }
1611 wtxNew.RelayWalletTransaction();
1612 }
e8ef3da7
WL
1613 return true;
1614}
1615
a372168e 1616CAmount CWallet::GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool& pool)
b33d1f5e
GA
1617{
1618 // payTxFee is user-set "I want to pay this much"
a372168e 1619 CAmount nFeeNeeded = payTxFee.GetFee(nTxBytes);
e7876b29
CL
1620 // prevent user from paying a non-sense fee (like 1 satoshi): 0 < fee < minRelayFee
1621 if (nFeeNeeded > 0 && nFeeNeeded < ::minRelayTxFee.GetFee(nTxBytes))
1622 nFeeNeeded = ::minRelayTxFee.GetFee(nTxBytes);
c1c9d5b4
CL
1623 // user selected total at least (default=true)
1624 if (fPayAtLeastCustomFee && nFeeNeeded > 0 && nFeeNeeded < payTxFee.GetFeePerK())
1625 nFeeNeeded = payTxFee.GetFeePerK();
b33d1f5e
GA
1626 // User didn't set: use -txconfirmtarget to estimate...
1627 if (nFeeNeeded == 0)
1628 nFeeNeeded = pool.estimateFee(nConfirmTarget).GetFee(nTxBytes);
1629 // ... unless we don't have enough mempool data, in which case fall
1630 // back to a hard-coded fee
1631 if (nFeeNeeded == 0)
13fc83c7 1632 nFeeNeeded = minTxFee.GetFee(nTxBytes);
b33d1f5e
GA
1633 return nFeeNeeded;
1634}
1635
e8ef3da7
WL
1636
1637
1638
eed1785f 1639DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
e8ef3da7
WL
1640{
1641 if (!fFileBacked)
4f76be1d 1642 return DB_LOAD_OK;
e8ef3da7 1643 fFirstRunRet = false;
eed1785f 1644 DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
d764d916 1645 if (nLoadWalletRet == DB_NEED_REWRITE)
9e9869d0 1646 {
d764d916
GA
1647 if (CDB::Rewrite(strWalletFile, "\x04pool"))
1648 {
012ca1c9 1649 LOCK(cs_wallet);
d764d916
GA
1650 setKeyPool.clear();
1651 // Note: can't top-up keypool here, because wallet is locked.
1652 // User will be prompted to unlock wallet the next operation
1653 // the requires a new key.
1654 }
9e9869d0
PW
1655 }
1656
7ec55267
MC
1657 if (nLoadWalletRet != DB_LOAD_OK)
1658 return nLoadWalletRet;
fd61d6f5 1659 fFirstRunRet = !vchDefaultKey.IsValid();
e8ef3da7 1660
39278369
CL
1661 uiInterface.LoadWallet(this);
1662
116df55e 1663 return DB_LOAD_OK;
e8ef3da7
WL
1664}
1665
ae3d0aba 1666
77cbd462 1667DBErrors CWallet::ZapWalletTx(std::vector<CWalletTx>& vWtx)
518f3bda
JG
1668{
1669 if (!fFileBacked)
1670 return DB_LOAD_OK;
77cbd462 1671 DBErrors nZapWalletTxRet = CWalletDB(strWalletFile,"cr+").ZapWalletTx(this, vWtx);
518f3bda
JG
1672 if (nZapWalletTxRet == DB_NEED_REWRITE)
1673 {
1674 if (CDB::Rewrite(strWalletFile, "\x04pool"))
1675 {
1676 LOCK(cs_wallet);
1677 setKeyPool.clear();
1678 // Note: can't top-up keypool here, because wallet is locked.
1679 // User will be prompted to unlock wallet the next operation
5b40d886 1680 // that requires a new key.
518f3bda
JG
1681 }
1682 }
1683
1684 if (nZapWalletTxRet != DB_LOAD_OK)
1685 return nZapWalletTxRet;
1686
1687 return DB_LOAD_OK;
1688}
1689
1690
a41d5fe0 1691bool CWallet::SetAddressBook(const CTxDestination& address, const string& strName, const string& strPurpose)
ae3d0aba 1692{
ca4cf5cf
GA
1693 bool fUpdated = false;
1694 {
1695 LOCK(cs_wallet); // mapAddressBook
1696 std::map<CTxDestination, CAddressBookData>::iterator mi = mapAddressBook.find(address);
1697 fUpdated = mi != mapAddressBook.end();
1698 mapAddressBook[address].name = strName;
1699 if (!strPurpose.empty()) /* update purpose only if requested */
1700 mapAddressBook[address].purpose = strPurpose;
1701 }
8d657a65 1702 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != ISMINE_NO,
ca4cf5cf 1703 strPurpose, (fUpdated ? CT_UPDATED : CT_NEW) );
ae3d0aba
WL
1704 if (!fFileBacked)
1705 return false;
a41d5fe0
GA
1706 if (!strPurpose.empty() && !CWalletDB(strWalletFile).WritePurpose(CBitcoinAddress(address).ToString(), strPurpose))
1707 return false;
10254401 1708 return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName);
ae3d0aba
WL
1709}
1710
a41d5fe0 1711bool CWallet::DelAddressBook(const CTxDestination& address)
ae3d0aba 1712{
b10e1470 1713 {
ca4cf5cf
GA
1714 LOCK(cs_wallet); // mapAddressBook
1715
1716 if(fFileBacked)
b10e1470 1717 {
ca4cf5cf
GA
1718 // Delete destdata tuples associated with address
1719 std::string strAddress = CBitcoinAddress(address).ToString();
1720 BOOST_FOREACH(const PAIRTYPE(string, string) &item, mapAddressBook[address].destdata)
1721 {
1722 CWalletDB(strWalletFile).EraseDestData(strAddress, item.first);
1723 }
b10e1470 1724 }
ca4cf5cf 1725 mapAddressBook.erase(address);
b10e1470
WL
1726 }
1727
8d657a65 1728 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != ISMINE_NO, "", CT_DELETED);
ca4cf5cf 1729
ae3d0aba
WL
1730 if (!fFileBacked)
1731 return false;
a41d5fe0 1732 CWalletDB(strWalletFile).ErasePurpose(CBitcoinAddress(address).ToString());
10254401 1733 return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString());
ae3d0aba
WL
1734}
1735
fd61d6f5 1736bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
ae3d0aba
WL
1737{
1738 if (fFileBacked)
1739 {
1740 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
1741 return false;
1742 }
1743 vchDefaultKey = vchPubKey;
1744 return true;
1745}
1746
5b40d886
MF
1747/**
1748 * Mark old keypool keys as used,
1749 * and generate all new keys
1750 */
37971fcc
GA
1751bool CWallet::NewKeyPool()
1752{
37971fcc 1753 {
f8dcd5ca 1754 LOCK(cs_wallet);
37971fcc 1755 CWalletDB walletdb(strWalletFile);
51ed9ec9 1756 BOOST_FOREACH(int64_t nIndex, setKeyPool)
37971fcc
GA
1757 walletdb.ErasePool(nIndex);
1758 setKeyPool.clear();
1759
1760 if (IsLocked())
1761 return false;
1762
51ed9ec9 1763 int64_t nKeys = max(GetArg("-keypool", 100), (int64_t)0);
37971fcc
GA
1764 for (int i = 0; i < nKeys; i++)
1765 {
51ed9ec9 1766 int64_t nIndex = i+1;
37971fcc
GA
1767 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
1768 setKeyPool.insert(nIndex);
1769 }
f48742c2 1770 LogPrintf("CWallet::NewKeyPool wrote %d new keys\n", nKeys);
37971fcc
GA
1771 }
1772 return true;
1773}
1774
13dd2d09 1775bool CWallet::TopUpKeyPool(unsigned int kpSize)
e8ef3da7 1776{
e8ef3da7 1777 {
f8dcd5ca
PW
1778 LOCK(cs_wallet);
1779
4e87d341
MC
1780 if (IsLocked())
1781 return false;
1782
e8ef3da7
WL
1783 CWalletDB walletdb(strWalletFile);
1784
1785 // Top up key pool
13dd2d09
JG
1786 unsigned int nTargetSize;
1787 if (kpSize > 0)
1788 nTargetSize = kpSize;
1789 else
51ed9ec9 1790 nTargetSize = max(GetArg("-keypool", 100), (int64_t) 0);
13dd2d09 1791
faf705a4 1792 while (setKeyPool.size() < (nTargetSize + 1))
e8ef3da7 1793 {
51ed9ec9 1794 int64_t nEnd = 1;
e8ef3da7
WL
1795 if (!setKeyPool.empty())
1796 nEnd = *(--setKeyPool.end()) + 1;
1797 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
4e87d341 1798 throw runtime_error("TopUpKeyPool() : writing generated key failed");
e8ef3da7 1799 setKeyPool.insert(nEnd);
783b182c 1800 LogPrintf("keypool added key %d, size=%u\n", nEnd, setKeyPool.size());
e8ef3da7 1801 }
4e87d341
MC
1802 }
1803 return true;
1804}
1805
51ed9ec9 1806void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool)
4e87d341
MC
1807{
1808 nIndex = -1;
fd61d6f5 1809 keypool.vchPubKey = CPubKey();
4e87d341 1810 {
f8dcd5ca
PW
1811 LOCK(cs_wallet);
1812
4e87d341
MC
1813 if (!IsLocked())
1814 TopUpKeyPool();
e8ef3da7
WL
1815
1816 // Get the oldest key
4e87d341
MC
1817 if(setKeyPool.empty())
1818 return;
1819
1820 CWalletDB walletdb(strWalletFile);
1821
e8ef3da7
WL
1822 nIndex = *(setKeyPool.begin());
1823 setKeyPool.erase(setKeyPool.begin());
1824 if (!walletdb.ReadPool(nIndex, keypool))
1825 throw runtime_error("ReserveKeyFromKeyPool() : read failed");
fd61d6f5 1826 if (!HaveKey(keypool.vchPubKey.GetID()))
e8ef3da7 1827 throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
fd61d6f5 1828 assert(keypool.vchPubKey.IsValid());
f48742c2 1829 LogPrintf("keypool reserve %d\n", nIndex);
e8ef3da7
WL
1830 }
1831}
1832
51ed9ec9 1833void CWallet::KeepKey(int64_t nIndex)
e8ef3da7
WL
1834{
1835 // Remove from key pool
1836 if (fFileBacked)
1837 {
1838 CWalletDB walletdb(strWalletFile);
6cc4a62c 1839 walletdb.ErasePool(nIndex);
e8ef3da7 1840 }
f48742c2 1841 LogPrintf("keypool keep %d\n", nIndex);
e8ef3da7
WL
1842}
1843
51ed9ec9 1844void CWallet::ReturnKey(int64_t nIndex)
e8ef3da7
WL
1845{
1846 // Return to key pool
f8dcd5ca
PW
1847 {
1848 LOCK(cs_wallet);
e8ef3da7 1849 setKeyPool.insert(nIndex);
f8dcd5ca 1850 }
f48742c2 1851 LogPrintf("keypool return %d\n", nIndex);
e8ef3da7
WL
1852}
1853
71ac5052 1854bool CWallet::GetKeyFromPool(CPubKey& result)
e8ef3da7 1855{
51ed9ec9 1856 int64_t nIndex = 0;
e8ef3da7 1857 CKeyPool keypool;
7db3b75b 1858 {
f8dcd5ca 1859 LOCK(cs_wallet);
ed02c95d
GA
1860 ReserveKeyFromKeyPool(nIndex, keypool);
1861 if (nIndex == -1)
7db3b75b 1862 {
ed02c95d
GA
1863 if (IsLocked()) return false;
1864 result = GenerateNewKey();
7db3b75b
GA
1865 return true;
1866 }
ed02c95d
GA
1867 KeepKey(nIndex);
1868 result = keypool.vchPubKey;
7db3b75b 1869 }
7db3b75b 1870 return true;
e8ef3da7
WL
1871}
1872
51ed9ec9 1873int64_t CWallet::GetOldestKeyPoolTime()
e8ef3da7 1874{
51ed9ec9 1875 int64_t nIndex = 0;
e8ef3da7
WL
1876 CKeyPool keypool;
1877 ReserveKeyFromKeyPool(nIndex, keypool);
4e87d341
MC
1878 if (nIndex == -1)
1879 return GetTime();
e8ef3da7
WL
1880 ReturnKey(nIndex);
1881 return keypool.nTime;
1882}
1883
a372168e 1884std::map<CTxDestination, CAmount> CWallet::GetAddressBalances()
22dfd735 1885{
a372168e 1886 map<CTxDestination, CAmount> balances;
22dfd735 1887
1888 {
1889 LOCK(cs_wallet);
1890 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
1891 {
1892 CWalletTx *pcoin = &walletEntry.second;
1893
0542619d 1894 if (!IsFinalTx(*pcoin) || !pcoin->IsTrusted())
22dfd735 1895 continue;
1896
1897 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
1898 continue;
1899
1900 int nDepth = pcoin->GetDepthInMainChain();
a3e192a3 1901 if (nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? 0 : 1))
22dfd735 1902 continue;
1903
b1093efa 1904 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
22dfd735 1905 {
b1093efa 1906 CTxDestination addr;
22dfd735 1907 if (!IsMine(pcoin->vout[i]))
1908 continue;
b1093efa
GM
1909 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr))
1910 continue;
22dfd735 1911
a372168e 1912 CAmount n = IsSpent(walletEntry.first, i) ? 0 : pcoin->vout[i].nValue;
22dfd735 1913
22dfd735 1914 if (!balances.count(addr))
1915 balances[addr] = 0;
1916 balances[addr] += n;
1917 }
1918 }
1919 }
1920
1921 return balances;
1922}
1923
b1093efa 1924set< set<CTxDestination> > CWallet::GetAddressGroupings()
22dfd735 1925{
95691680 1926 AssertLockHeld(cs_wallet); // mapWallet
b1093efa
GM
1927 set< set<CTxDestination> > groupings;
1928 set<CTxDestination> grouping;
22dfd735 1929
1930 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
1931 {
1932 CWalletTx *pcoin = &walletEntry.second;
1933
a3fad211 1934 if (pcoin->vin.size() > 0)
22dfd735 1935 {
a3fad211 1936 bool any_mine = false;
22dfd735 1937 // group all input addresses with each other
1938 BOOST_FOREACH(CTxIn txin, pcoin->vin)
b1093efa
GM
1939 {
1940 CTxDestination address;
a3fad211
GM
1941 if(!IsMine(txin)) /* If this input isn't mine, ignore it */
1942 continue;
b1093efa
GM
1943 if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
1944 continue;
1945 grouping.insert(address);
a3fad211 1946 any_mine = true;
b1093efa 1947 }
22dfd735 1948
1949 // group change with input addresses
a3fad211
GM
1950 if (any_mine)
1951 {
1952 BOOST_FOREACH(CTxOut txout, pcoin->vout)
1953 if (IsChange(txout))
1954 {
1955 CTxDestination txoutAddr;
1956 if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
1957 continue;
1958 grouping.insert(txoutAddr);
1959 }
1960 }
1961 if (grouping.size() > 0)
1962 {
1963 groupings.insert(grouping);
1964 grouping.clear();
1965 }
22dfd735 1966 }
1967
1968 // group lone addrs by themselves
b1093efa 1969 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
22dfd735 1970 if (IsMine(pcoin->vout[i]))
1971 {
b1093efa
GM
1972 CTxDestination address;
1973 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address))
1974 continue;
1975 grouping.insert(address);
22dfd735 1976 groupings.insert(grouping);
1977 grouping.clear();
1978 }
1979 }
1980
b1093efa
GM
1981 set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
1982 map< CTxDestination, set<CTxDestination>* > setmap; // map addresses to the unique group containing it
1983 BOOST_FOREACH(set<CTxDestination> grouping, groupings)
22dfd735 1984 {
1985 // make a set of all the groups hit by this new group
b1093efa
GM
1986 set< set<CTxDestination>* > hits;
1987 map< CTxDestination, set<CTxDestination>* >::iterator it;
1988 BOOST_FOREACH(CTxDestination address, grouping)
22dfd735 1989 if ((it = setmap.find(address)) != setmap.end())
1990 hits.insert((*it).second);
1991
1992 // merge all hit groups into a new single group and delete old groups
b1093efa
GM
1993 set<CTxDestination>* merged = new set<CTxDestination>(grouping);
1994 BOOST_FOREACH(set<CTxDestination>* hit, hits)
22dfd735 1995 {
1996 merged->insert(hit->begin(), hit->end());
1997 uniqueGroupings.erase(hit);
1998 delete hit;
1999 }
2000 uniqueGroupings.insert(merged);
2001
2002 // update setmap
b1093efa 2003 BOOST_FOREACH(CTxDestination element, *merged)
22dfd735 2004 setmap[element] = merged;
2005 }
2006
b1093efa
GM
2007 set< set<CTxDestination> > ret;
2008 BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings)
22dfd735 2009 {
2010 ret.insert(*uniqueGrouping);
2011 delete uniqueGrouping;
2012 }
2013
2014 return ret;
2015}
2016
3624356e
GA
2017set<CTxDestination> CWallet::GetAccountAddresses(string strAccount) const
2018{
43422a01 2019 LOCK(cs_wallet);
3624356e
GA
2020 set<CTxDestination> result;
2021 BOOST_FOREACH(const PAIRTYPE(CTxDestination, CAddressBookData)& item, mapAddressBook)
2022 {
2023 const CTxDestination& address = item.first;
2024 const string& strName = item.second.name;
2025 if (strName == strAccount)
2026 result.insert(address);
2027 }
2028 return result;
2029}
2030
360cfe14 2031bool CReserveKey::GetReservedKey(CPubKey& pubkey)
e8ef3da7
WL
2032{
2033 if (nIndex == -1)
2034 {
2035 CKeyPool keypool;
2036 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
0d7b28e5
MC
2037 if (nIndex != -1)
2038 vchPubKey = keypool.vchPubKey;
360cfe14 2039 else {
6c37f7fd 2040 return false;
cee69980 2041 }
e8ef3da7 2042 }
fd61d6f5 2043 assert(vchPubKey.IsValid());
360cfe14
PW
2044 pubkey = vchPubKey;
2045 return true;
e8ef3da7
WL
2046}
2047
2048void CReserveKey::KeepKey()
2049{
2050 if (nIndex != -1)
2051 pwallet->KeepKey(nIndex);
2052 nIndex = -1;
fd61d6f5 2053 vchPubKey = CPubKey();
e8ef3da7
WL
2054}
2055
2056void CReserveKey::ReturnKey()
2057{
2058 if (nIndex != -1)
2059 pwallet->ReturnKey(nIndex);
2060 nIndex = -1;
fd61d6f5 2061 vchPubKey = CPubKey();
e8ef3da7 2062}
ae3d0aba 2063
434e4273 2064void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
30ab2c9c
PW
2065{
2066 setAddress.clear();
2067
2068 CWalletDB walletdb(strWalletFile);
2069
f8dcd5ca 2070 LOCK2(cs_main, cs_wallet);
51ed9ec9 2071 BOOST_FOREACH(const int64_t& id, setKeyPool)
30ab2c9c
PW
2072 {
2073 CKeyPool keypool;
2074 if (!walletdb.ReadPool(id, keypool))
2075 throw runtime_error("GetAllReserveKeyHashes() : read failed");
fd61d6f5 2076 assert(keypool.vchPubKey.IsValid());
10254401
PW
2077 CKeyID keyID = keypool.vchPubKey.GetID();
2078 if (!HaveKey(keyID))
30ab2c9c 2079 throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
10254401 2080 setAddress.insert(keyID);
30ab2c9c
PW
2081 }
2082}
fe4a6550
WL
2083
2084void CWallet::UpdatedTransaction(const uint256 &hashTx)
2085{
2086 {
2087 LOCK(cs_wallet);
2088 // Only notify UI if this transaction is in this wallet
2089 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
2090 if (mi != mapWallet.end())
2091 NotifyTransactionChanged(this, hashTx, CT_UPDATED);
2092 }
2093}
fdbb537d
JG
2094
2095void CWallet::LockCoin(COutPoint& output)
2096{
95691680 2097 AssertLockHeld(cs_wallet); // setLockedCoins
fdbb537d
JG
2098 setLockedCoins.insert(output);
2099}
2100
2101void CWallet::UnlockCoin(COutPoint& output)
2102{
95691680 2103 AssertLockHeld(cs_wallet); // setLockedCoins
fdbb537d
JG
2104 setLockedCoins.erase(output);
2105}
2106
2107void CWallet::UnlockAllCoins()
2108{
95691680 2109 AssertLockHeld(cs_wallet); // setLockedCoins
fdbb537d
JG
2110 setLockedCoins.clear();
2111}
2112
2113bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const
2114{
95691680 2115 AssertLockHeld(cs_wallet); // setLockedCoins
fdbb537d
JG
2116 COutPoint outpt(hash, n);
2117
2118 return (setLockedCoins.count(outpt) > 0);
2119}
2120
2121void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts)
2122{
95691680 2123 AssertLockHeld(cs_wallet); // setLockedCoins
fdbb537d
JG
2124 for (std::set<COutPoint>::iterator it = setLockedCoins.begin();
2125 it != setLockedCoins.end(); it++) {
2126 COutPoint outpt = (*it);
2127 vOutpts.push_back(outpt);
2128 }
2129}
2130
5b40d886 2131/** @} */ // end of Actions
8b59a3d3 2132
2133class CAffectedKeysVisitor : public boost::static_visitor<void> {
2134private:
2135 const CKeyStore &keystore;
2136 std::vector<CKeyID> &vKeys;
2137
2138public:
2139 CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector<CKeyID> &vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {}
2140
2141 void Process(const CScript &script) {
2142 txnouttype type;
2143 std::vector<CTxDestination> vDest;
2144 int nRequired;
2145 if (ExtractDestinations(script, type, vDest, nRequired)) {
2146 BOOST_FOREACH(const CTxDestination &dest, vDest)
2147 boost::apply_visitor(*this, dest);
2148 }
2149 }
2150
2151 void operator()(const CKeyID &keyId) {
2152 if (keystore.HaveKey(keyId))
2153 vKeys.push_back(keyId);
2154 }
2155
2156 void operator()(const CScriptID &scriptId) {
2157 CScript script;
2158 if (keystore.GetCScript(scriptId, script))
2159 Process(script);
2160 }
2161
2162 void operator()(const CNoDestination &none) {}
2163};
2164
51ed9ec9 2165void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const {
95691680 2166 AssertLockHeld(cs_wallet); // mapKeyMetadata
434e4273
PW
2167 mapKeyBirth.clear();
2168
2169 // get birth times for keys with metadata
2170 for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++)
2171 if (it->second.nCreateTime)
2172 mapKeyBirth[it->first] = it->second.nCreateTime;
2173
2174 // map in which we'll infer heights of other keys
4c6d41b8 2175 CBlockIndex *pindexMax = chainActive[std::max(0, chainActive.Height() - 144)]; // the tip can be reorganised; use a 144-block safety margin
434e4273
PW
2176 std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
2177 std::set<CKeyID> setKeys;
2178 GetKeys(setKeys);
2179 BOOST_FOREACH(const CKeyID &keyid, setKeys) {
2180 if (mapKeyBirth.count(keyid) == 0)
2181 mapKeyFirstBlock[keyid] = pindexMax;
2182 }
2183 setKeys.clear();
2184
2185 // if there are no such keys, we're done
2186 if (mapKeyFirstBlock.empty())
2187 return;
2188
2189 // find first block that affects those keys, if there are any left
2190 std::vector<CKeyID> vAffected;
2191 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
2192 // iterate over all wallet transactions...
2193 const CWalletTx &wtx = (*it).second;
145d5be8 2194 BlockMap::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
4c6d41b8 2195 if (blit != mapBlockIndex.end() && chainActive.Contains(blit->second)) {
434e4273
PW
2196 // ... which are already in a block
2197 int nHeight = blit->second->nHeight;
2198 BOOST_FOREACH(const CTxOut &txout, wtx.vout) {
2199 // iterate over all their outputs
8b59a3d3 2200 CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey);
434e4273
PW
2201 BOOST_FOREACH(const CKeyID &keyid, vAffected) {
2202 // ... and all their affected keys
2203 std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
2204 if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
2205 rit->second = blit->second;
2206 }
2207 vAffected.clear();
2208 }
2209 }
2210 }
2211
2212 // Extract block timestamps for those keys
2213 for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
209377a7 2214 mapKeyBirth[it->first] = it->second->GetBlockTime() - 7200; // block times can be 2h off
434e4273 2215}
b10e1470
WL
2216
2217bool CWallet::AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
2218{
8476d5d4
CL
2219 if (boost::get<CNoDestination>(&dest))
2220 return false;
2221
b10e1470
WL
2222 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
2223 if (!fFileBacked)
2224 return true;
2225 return CWalletDB(strWalletFile).WriteDestData(CBitcoinAddress(dest).ToString(), key, value);
2226}
2227
2228bool CWallet::EraseDestData(const CTxDestination &dest, const std::string &key)
2229{
2230 if (!mapAddressBook[dest].destdata.erase(key))
2231 return false;
2232 if (!fFileBacked)
2233 return true;
2234 return CWalletDB(strWalletFile).EraseDestData(CBitcoinAddress(dest).ToString(), key);
2235}
2236
2237bool CWallet::LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
2238{
2239 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
2240 return true;
2241}
2242
2243bool CWallet::GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const
2244{
2245 std::map<CTxDestination, CAddressBookData>::const_iterator i = mapAddressBook.find(dest);
2246 if(i != mapAddressBook.end())
2247 {
2248 CAddressBookData::StringMap::const_iterator j = i->second.destdata.find(key);
2249 if(j != i->second.destdata.end())
2250 {
2251 if(value)
2252 *value = j->second;
2253 return true;
2254 }
2255 }
2256 return false;
2257}
af8297c0
WL
2258
2259CKeyPool::CKeyPool()
2260{
2261 nTime = GetTime();
2262}
2263
2264CKeyPool::CKeyPool(const CPubKey& vchPubKeyIn)
2265{
2266 nTime = GetTime();
2267 vchPubKey = vchPubKeyIn;
2268}
2269
2270CWalletKey::CWalletKey(int64_t nExpires)
2271{
2272 nTimeCreated = (nExpires ? GetTime() : 0);
2273 nTimeExpires = nExpires;
2274}
0101483f 2275
4b0deb3b 2276int CMerkleTx::SetMerkleBranch(const CBlock& block)
0101483f
WL
2277{
2278 AssertLockHeld(cs_main);
2279 CBlock blockTmp;
2280
4b0deb3b
DK
2281 // Update the tx's hashBlock
2282 hashBlock = block.GetHash();
0101483f 2283
4b0deb3b
DK
2284 // Locate the transaction
2285 for (nIndex = 0; nIndex < (int)block.vtx.size(); nIndex++)
2286 if (block.vtx[nIndex] == *(CTransaction*)this)
2287 break;
2288 if (nIndex == (int)block.vtx.size())
2289 {
2290 vMerkleBranch.clear();
2291 nIndex = -1;
2292 LogPrintf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
2293 return 0;
0101483f
WL
2294 }
2295
4b0deb3b
DK
2296 // Fill in merkle branch
2297 vMerkleBranch = block.GetMerkleBranch(nIndex);
2298
0101483f 2299 // Is the tx in a block that's in the main chain
145d5be8 2300 BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
0101483f
WL
2301 if (mi == mapBlockIndex.end())
2302 return 0;
4b0deb3b 2303 const CBlockIndex* pindex = (*mi).second;
0101483f
WL
2304 if (!pindex || !chainActive.Contains(pindex))
2305 return 0;
2306
2307 return chainActive.Height() - pindex->nHeight + 1;
2308}
2309
a31e8bad 2310int CMerkleTx::GetDepthInMainChainINTERNAL(const CBlockIndex* &pindexRet) const
0101483f
WL
2311{
2312 if (hashBlock == 0 || nIndex == -1)
2313 return 0;
2314 AssertLockHeld(cs_main);
2315
2316 // Find the block it claims to be in
145d5be8 2317 BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
0101483f
WL
2318 if (mi == mapBlockIndex.end())
2319 return 0;
2320 CBlockIndex* pindex = (*mi).second;
2321 if (!pindex || !chainActive.Contains(pindex))
2322 return 0;
2323
2324 // Make sure the merkle branch connects to this block
2325 if (!fMerkleVerified)
2326 {
2327 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
2328 return 0;
2329 fMerkleVerified = true;
2330 }
2331
2332 pindexRet = pindex;
2333 return chainActive.Height() - pindex->nHeight + 1;
2334}
2335
a31e8bad 2336int CMerkleTx::GetDepthInMainChain(const CBlockIndex* &pindexRet) const
0101483f
WL
2337{
2338 AssertLockHeld(cs_main);
2339 int nResult = GetDepthInMainChainINTERNAL(pindexRet);
2340 if (nResult == 0 && !mempool.exists(GetHash()))
2341 return -1; // Not in chain, not in mempool
2342
2343 return nResult;
2344}
2345
2346int CMerkleTx::GetBlocksToMaturity() const
2347{
2348 if (!IsCoinBase())
2349 return 0;
2350 return max(0, (COINBASE_MATURITY+1) - GetDepthInMainChain());
2351}
2352
2353
2354bool CMerkleTx::AcceptToMemoryPool(bool fLimitFree, bool fRejectInsaneFee)
2355{
2356 CValidationState state;
2357 return ::AcceptToMemoryPool(mempool, state, *this, fLimitFree, NULL, fRejectInsaneFee);
2358}
2359
This page took 0.594864 seconds and 4 git commands to generate.