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