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