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