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 license.txt or http://www.opensource.org/licenses/mit-license.php.
9 #include "ui_interface.h"
14 //////////////////////////////////////////////////////////////////////////////
19 std::vector<unsigned char> CWallet::GenerateNewKey()
21 bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
25 key.MakeNewKey(fCompressed);
27 // Compressed public keys were introduced in version 0.6.0
29 SetMinVersion(FEATURE_COMPRPUBKEY);
32 throw std::runtime_error("CWallet::GenerateNewKey() : AddKey failed");
33 return key.GetPubKey();
36 bool CWallet::AddKey(const CKey& key)
38 if (!CCryptoKeyStore::AddKey(key))
43 return CWalletDB(strWalletFile).WriteKey(key.GetPubKey(), key.GetPrivKey());
47 bool CWallet::AddCryptedKey(const vector<unsigned char> &vchPubKey, const vector<unsigned char> &vchCryptedSecret)
49 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
55 if (pwalletdbEncryption)
56 return pwalletdbEncryption->WriteCryptedKey(vchPubKey, vchCryptedSecret);
58 return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret);
63 bool CWallet::AddCScript(const CScript& redeemScript)
65 if (!CCryptoKeyStore::AddCScript(redeemScript))
69 return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript);
72 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
78 CKeyingMaterial vMasterKey;
82 BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
84 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
86 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
88 if (CCryptoKeyStore::Unlock(vMasterKey))
95 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
97 bool fWasLocked = IsLocked();
104 CKeyingMaterial vMasterKey;
105 BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
107 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
109 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
111 if (CCryptoKeyStore::Unlock(vMasterKey))
113 int64 nStartTime = GetTimeMillis();
114 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
115 pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
117 nStartTime = GetTimeMillis();
118 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
119 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
121 if (pMasterKey.second.nDeriveIterations < 25000)
122 pMasterKey.second.nDeriveIterations = 25000;
124 printf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
126 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
128 if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
130 CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
141 void CWallet::SetBestChain(const CBlockLocator& loc)
143 CWalletDB walletdb(strWalletFile);
144 walletdb.WriteBestBlock(loc);
147 // This class implements an addrIncoming entry that causes pre-0.4
148 // clients to crash on startup if reading a private-key-encrypted wallet.
149 class CCorruptAddress
154 if (nType & SER_DISK)
159 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
161 if (nWalletVersion >= nVersion)
164 // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
165 if (fExplicit && nVersion > nWalletMaxVersion)
166 nVersion = FEATURE_LATEST;
168 nWalletVersion = nVersion;
170 if (nVersion > nWalletMaxVersion)
171 nWalletMaxVersion = nVersion;
175 CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile);
176 if (nWalletVersion >= 40000)
178 // Versions prior to 0.4.0 did not support the "minversion" record.
179 // Use a CCorruptAddress to make them crash instead.
180 CCorruptAddress corruptAddress;
181 pwalletdb->WriteSetting("addrIncoming", corruptAddress);
183 if (nWalletVersion > 40000)
184 pwalletdb->WriteMinVersion(nWalletVersion);
192 bool CWallet::SetMaxVersion(int nVersion)
194 // cannot downgrade below current version
195 if (nWalletVersion > nVersion)
198 nWalletMaxVersion = nVersion;
203 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
208 CKeyingMaterial vMasterKey;
209 RandAddSeedPerfmon();
211 vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
212 RAND_bytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
214 CMasterKey kMasterKey;
216 RandAddSeedPerfmon();
217 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
218 RAND_bytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
221 int64 nStartTime = GetTimeMillis();
222 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
223 kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
225 nStartTime = GetTimeMillis();
226 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
227 kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
229 if (kMasterKey.nDeriveIterations < 25000)
230 kMasterKey.nDeriveIterations = 25000;
232 printf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
234 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
236 if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
241 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
244 pwalletdbEncryption = new CWalletDB(strWalletFile);
245 pwalletdbEncryption->TxnBegin();
246 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
249 if (!EncryptKeys(vMasterKey))
252 pwalletdbEncryption->TxnAbort();
253 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.
256 // Encryption was introduced in version 0.4.0
257 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
261 if (!pwalletdbEncryption->TxnCommit())
262 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.
264 delete pwalletdbEncryption;
265 pwalletdbEncryption = NULL;
269 Unlock(strWalletPassphrase);
273 // Need to completely rewrite the wallet file; if we don't, bdb might keep
274 // bits of the unencrypted private key in slack space in the database file.
275 CDB::Rewrite(strWalletFile);
281 void CWallet::WalletUpdateSpent(const CTransaction &tx)
283 // Anytime a signature is successfully verified, it's proof the outpoint is spent.
284 // Update the wallet spent flag if it doesn't know due to wallet.dat being
285 // restored from backup or the user making copies of wallet.dat.
288 BOOST_FOREACH(const CTxIn& txin, tx.vin)
290 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
291 if (mi != mapWallet.end())
293 CWalletTx& wtx = (*mi).second;
294 if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n]))
296 printf("WalletUpdateSpent found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
297 wtx.MarkSpent(txin.prevout.n);
299 vWalletUpdated.push_back(txin.prevout.hash);
306 void CWallet::MarkDirty()
310 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
311 item.second.MarkDirty();
315 bool CWallet::AddToWallet(const CWalletTx& wtxIn)
317 uint256 hash = wtxIn.GetHash();
320 // Inserts only if not already there, returns tx inserted or tx found
321 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
322 CWalletTx& wtx = (*ret.first).second;
323 wtx.BindWallet(this);
324 bool fInsertedNew = ret.second;
326 wtx.nTimeReceived = GetAdjustedTime();
328 bool fUpdated = false;
332 if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
334 wtx.hashBlock = wtxIn.hashBlock;
337 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
339 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
340 wtx.nIndex = wtxIn.nIndex;
343 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
345 wtx.fFromMe = wtxIn.fFromMe;
348 fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);
352 printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
355 if (fInsertedNew || fUpdated)
356 if (!wtx.WriteToDisk())
359 // If default receiving address gets used, replace it with a new one
360 CScript scriptDefaultKey;
361 scriptDefaultKey.SetBitcoinAddress(vchDefaultKey);
362 BOOST_FOREACH(const CTxOut& txout, wtx.vout)
364 if (txout.scriptPubKey == scriptDefaultKey)
366 std::vector<unsigned char> newDefaultKey;
367 if (GetKeyFromPool(newDefaultKey, false))
369 SetDefaultKey(newDefaultKey);
370 SetAddressBookName(CBitcoinAddress(vchDefaultKey), "");
376 vWalletUpdated.push_back(hash);
378 // since AddToWallet is called directly for self-originating transactions, check for consumption of own coins
379 WalletUpdateSpent(wtx);
387 // Add a transaction to the wallet, or update it.
388 // pblock is optional, but should be provided if the transaction is known to be in a block.
389 // If fUpdate is true, existing transactions will be updated.
390 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fFindBlock)
392 uint256 hash = tx.GetHash();
395 bool fExisted = mapWallet.count(hash);
396 if (fExisted && !fUpdate) return false;
397 if (fExisted || IsMine(tx) || IsFromMe(tx))
399 CWalletTx wtx(this,tx);
400 // Get merkle branch if transaction was found in a block
402 wtx.SetMerkleBranch(pblock);
403 return AddToWallet(wtx);
406 WalletUpdateSpent(tx);
411 bool CWallet::EraseFromWallet(uint256 hash)
417 if (mapWallet.erase(hash))
418 CWalletDB(strWalletFile).EraseTx(hash);
424 bool CWallet::IsMine(const CTxIn &txin) const
428 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
429 if (mi != mapWallet.end())
431 const CWalletTx& prev = (*mi).second;
432 if (txin.prevout.n < prev.vout.size())
433 if (IsMine(prev.vout[txin.prevout.n]))
440 int64 CWallet::GetDebit(const CTxIn &txin) const
444 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
445 if (mi != mapWallet.end())
447 const CWalletTx& prev = (*mi).second;
448 if (txin.prevout.n < prev.vout.size())
449 if (IsMine(prev.vout[txin.prevout.n]))
450 return prev.vout[txin.prevout.n].nValue;
456 bool CWallet::IsChange(const CTxOut& txout) const
458 CBitcoinAddress address;
460 // TODO: fix handling of 'change' outputs. The assumption is that any
461 // payment to a TX_PUBKEYHASH that is mine but isn't in the address book
462 // is change. That assumption is likely to break when we implement multisignature
463 // wallets that return change back into a multi-signature-protected address;
464 // a better way of identifying which outputs are 'the send' and which are
465 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
466 // which output, if any, was change).
467 if (ExtractAddress(txout.scriptPubKey, address) && HaveKey(address))
470 if (!mapAddressBook.count(address))
476 int64 CWalletTx::GetTxTime() const
478 return nTimeReceived;
481 int CWalletTx::GetRequestCount() const
483 // Returns -1 if it wasn't being tracked
486 LOCK(pwallet->cs_wallet);
492 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
493 if (mi != pwallet->mapRequestCount.end())
494 nRequests = (*mi).second;
499 // Did anyone request this transaction?
500 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
501 if (mi != pwallet->mapRequestCount.end())
503 nRequests = (*mi).second;
505 // How about the block it's in?
506 if (nRequests == 0 && hashBlock != 0)
508 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
509 if (mi != pwallet->mapRequestCount.end())
510 nRequests = (*mi).second;
512 nRequests = 1; // If it's in someone else's block it must have got out
520 void CWalletTx::GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, list<pair<CBitcoinAddress, int64> >& listReceived,
521 list<pair<CBitcoinAddress, int64> >& listSent, int64& nFee, string& strSentAccount) const
523 nGeneratedImmature = nGeneratedMature = nFee = 0;
524 listReceived.clear();
526 strSentAccount = strFromAccount;
530 if (GetBlocksToMaturity() > 0)
531 nGeneratedImmature = pwallet->GetCredit(*this);
533 nGeneratedMature = GetCredit();
538 int64 nDebit = GetDebit();
539 if (nDebit > 0) // debit>0 means we signed/sent this transaction
541 int64 nValueOut = GetValueOut();
542 nFee = nDebit - nValueOut;
546 BOOST_FOREACH(const CTxOut& txout, vout)
548 CBitcoinAddress address;
549 vector<unsigned char> vchPubKey;
550 if (!ExtractAddress(txout.scriptPubKey, address))
552 printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
553 this->GetHash().ToString().c_str());
554 address = " unknown ";
557 // Don't report 'change' txouts
558 if (nDebit > 0 && pwallet->IsChange(txout))
562 listSent.push_back(make_pair(address, txout.nValue));
564 if (pwallet->IsMine(txout))
565 listReceived.push_back(make_pair(address, txout.nValue));
570 void CWalletTx::GetAccountAmounts(const string& strAccount, int64& nGenerated, int64& nReceived,
571 int64& nSent, int64& nFee) const
573 nGenerated = nReceived = nSent = nFee = 0;
575 int64 allGeneratedImmature, allGeneratedMature, allFee;
576 allGeneratedImmature = allGeneratedMature = allFee = 0;
577 string strSentAccount;
578 list<pair<CBitcoinAddress, int64> > listReceived;
579 list<pair<CBitcoinAddress, int64> > listSent;
580 GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount);
582 if (strAccount == "")
583 nGenerated = allGeneratedMature;
584 if (strAccount == strSentAccount)
586 BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress,int64)& s, listSent)
591 LOCK(pwallet->cs_wallet);
592 BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress,int64)& r, listReceived)
594 if (pwallet->mapAddressBook.count(r.first))
596 map<CBitcoinAddress, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);
597 if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)
598 nReceived += r.second;
600 else if (strAccount.empty())
602 nReceived += r.second;
608 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
612 const int COPY_DEPTH = 3;
613 if (SetMerkleBranch() < COPY_DEPTH)
615 vector<uint256> vWorkQueue;
616 BOOST_FOREACH(const CTxIn& txin, vin)
617 vWorkQueue.push_back(txin.prevout.hash);
619 // This critsect is OK because txdb is already open
621 LOCK(pwallet->cs_wallet);
622 map<uint256, const CMerkleTx*> mapWalletPrev;
623 set<uint256> setAlreadyDone;
624 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
626 uint256 hash = vWorkQueue[i];
627 if (setAlreadyDone.count(hash))
629 setAlreadyDone.insert(hash);
632 map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
633 if (mi != pwallet->mapWallet.end())
636 BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev)
637 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
639 else if (mapWalletPrev.count(hash))
641 tx = *mapWalletPrev[hash];
643 else if (!fClient && txdb.ReadDiskTx(hash, tx))
649 printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
653 int nDepth = tx.SetMerkleBranch();
654 vtxPrev.push_back(tx);
656 if (nDepth < COPY_DEPTH)
658 BOOST_FOREACH(const CTxIn& txin, tx.vin)
659 vWorkQueue.push_back(txin.prevout.hash);
665 reverse(vtxPrev.begin(), vtxPrev.end());
668 bool CWalletTx::WriteToDisk()
670 return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
673 // Scan the block chain (starting in pindexStart) for transactions
674 // from or to us. If fUpdate is true, found transactions that already
675 // exist in the wallet will be updated.
676 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
680 CBlockIndex* pindex = pindexStart;
686 block.ReadFromDisk(pindex, true);
687 BOOST_FOREACH(CTransaction& tx, block.vtx)
689 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
692 pindex = pindex->pnext;
698 int CWallet::ScanForWalletTransaction(const uint256& hashTx)
701 tx.ReadFromDisk(COutPoint(hashTx, 0));
702 if (AddToWalletIfInvolvingMe(tx, NULL, true, true))
707 void CWallet::ReacceptWalletTransactions()
715 vector<CDiskTxPos> vMissingTx;
716 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
718 CWalletTx& wtx = item.second;
719 if (wtx.IsCoinBase() && wtx.IsSpent(0))
723 bool fUpdated = false;
724 if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
726 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
727 if (txindex.vSpent.size() != wtx.vout.size())
729 printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %d != wtx.vout.size() %d\n", txindex.vSpent.size(), wtx.vout.size());
732 for (unsigned int i = 0; i < txindex.vSpent.size(); i++)
736 if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i]))
740 vMissingTx.push_back(txindex.vSpent[i]);
745 printf("ReacceptWalletTransactions found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
752 // Reaccept any txes of ours that aren't already in a block
753 if (!wtx.IsCoinBase())
754 wtx.AcceptWalletTransaction(txdb, false);
757 if (!vMissingTx.empty())
759 // TODO: optimize this to scan just part of the block chain?
760 if (ScanForWalletTransactions(pindexGenesisBlock))
761 fRepeat = true; // Found missing transactions: re-do Reaccept.
766 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
768 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
770 if (!tx.IsCoinBase())
772 uint256 hash = tx.GetHash();
773 if (!txdb.ContainsTx(hash))
774 RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx);
779 uint256 hash = GetHash();
780 if (!txdb.ContainsTx(hash))
782 printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
783 RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this);
788 void CWalletTx::RelayWalletTransaction()
791 RelayWalletTransaction(txdb);
794 void CWallet::ResendWalletTransactions()
796 // Do this infrequently and randomly to avoid giving away
797 // that these are our transactions.
798 static int64 nNextTime;
799 if (GetTime() < nNextTime)
801 bool fFirst = (nNextTime == 0);
802 nNextTime = GetTime() + GetRand(30 * 60);
806 // Only do it if there's been a new block since last time
807 static int64 nLastTime;
808 if (nTimeBestReceived < nLastTime)
810 nLastTime = GetTime();
812 // Rebroadcast any of our txes that aren't in a block yet
813 printf("ResendWalletTransactions()\n");
817 // Sort them in chronological order
818 multimap<unsigned int, CWalletTx*> mapSorted;
819 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
821 CWalletTx& wtx = item.second;
822 // Don't rebroadcast until it's had plenty of time that
823 // it should have gotten in already by now.
824 if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
825 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
827 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
829 CWalletTx& wtx = *item.second;
830 wtx.RelayWalletTransaction(txdb);
840 //////////////////////////////////////////////////////////////////////////////
846 int64 CWallet::GetBalance() const
851 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
853 const CWalletTx* pcoin = &(*it).second;
854 if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
856 nTotal += pcoin->GetAvailableCredit();
863 int64 CWallet::GetUnconfirmedBalance() const
868 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
870 const CWalletTx* pcoin = &(*it).second;
871 if (pcoin->IsFinal() && pcoin->IsConfirmed())
873 nTotal += pcoin->GetAvailableCredit();
879 bool CWallet::SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
884 // List of values less than target
885 pair<int64, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
886 coinLowestLarger.first = std::numeric_limits<int64>::max();
887 coinLowestLarger.second.first = NULL;
888 vector<pair<int64, pair<const CWalletTx*,unsigned int> > > vValue;
889 int64 nTotalLower = 0;
893 vector<const CWalletTx*> vCoins;
894 vCoins.reserve(mapWallet.size());
895 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
896 vCoins.push_back(&(*it).second);
897 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
899 BOOST_FOREACH(const CWalletTx* pcoin, vCoins)
901 if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
904 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
907 int nDepth = pcoin->GetDepthInMainChain();
908 if (nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs))
911 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
913 if (pcoin->IsSpent(i) || !IsMine(pcoin->vout[i]))
916 int64 n = pcoin->vout[i].nValue;
921 pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin,i));
923 if (n == nTargetValue)
925 setCoinsRet.insert(coin.second);
926 nValueRet += coin.first;
929 else if (n < nTargetValue + CENT)
931 vValue.push_back(coin);
934 else if (n < coinLowestLarger.first)
936 coinLowestLarger = coin;
942 if (nTotalLower == nTargetValue || nTotalLower == nTargetValue + CENT)
944 for (unsigned int i = 0; i < vValue.size(); ++i)
946 setCoinsRet.insert(vValue[i].second);
947 nValueRet += vValue[i].first;
952 if (nTotalLower < nTargetValue + (coinLowestLarger.second.first ? CENT : 0))
954 if (coinLowestLarger.second.first == NULL)
956 setCoinsRet.insert(coinLowestLarger.second);
957 nValueRet += coinLowestLarger.first;
961 if (nTotalLower >= nTargetValue + CENT)
962 nTargetValue += CENT;
964 // Solve subset sum by stochastic approximation
965 sort(vValue.rbegin(), vValue.rend());
966 vector<char> vfIncluded;
967 vector<char> vfBest(vValue.size(), true);
968 int64 nBest = nTotalLower;
970 for (int nRep = 0; nRep < 1000 && nBest != nTargetValue; nRep++)
972 vfIncluded.assign(vValue.size(), false);
974 bool fReachedTarget = false;
975 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
977 for (unsigned int i = 0; i < vValue.size(); i++)
979 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
981 nTotal += vValue[i].first;
982 vfIncluded[i] = true;
983 if (nTotal >= nTargetValue)
985 fReachedTarget = true;
991 nTotal -= vValue[i].first;
992 vfIncluded[i] = false;
999 // If the next larger is still closer, return it
1000 if (coinLowestLarger.second.first && coinLowestLarger.first - nTargetValue <= nBest - nTargetValue)
1002 setCoinsRet.insert(coinLowestLarger.second);
1003 nValueRet += coinLowestLarger.first;
1006 for (unsigned int i = 0; i < vValue.size(); i++)
1009 setCoinsRet.insert(vValue[i].second);
1010 nValueRet += vValue[i].first;
1014 printf("SelectCoins() best subset: ");
1015 for (unsigned int i = 0; i < vValue.size(); i++)
1017 printf("%s ", FormatMoney(vValue[i].first).c_str());
1018 printf("total %s\n", FormatMoney(nBest).c_str());
1024 bool CWallet::SelectCoins(int64 nTargetValue, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
1026 return (SelectCoinsMinConf(nTargetValue, 1, 6, setCoinsRet, nValueRet) ||
1027 SelectCoinsMinConf(nTargetValue, 1, 1, setCoinsRet, nValueRet) ||
1028 SelectCoinsMinConf(nTargetValue, 0, 1, setCoinsRet, nValueRet));
1034 bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
1037 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1043 if (vecSend.empty() || nValue < 0)
1046 wtxNew.BindWallet(this);
1049 LOCK2(cs_main, cs_wallet);
1050 // txdb must be opened before the mapWallet lock
1053 nFeeRet = nTransactionFee;
1057 wtxNew.vout.clear();
1058 wtxNew.fFromMe = true;
1060 int64 nTotalValue = nValue + nFeeRet;
1061 double dPriority = 0;
1062 // vouts to the payees
1063 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1064 wtxNew.vout.push_back(CTxOut(s.second, s.first));
1066 // Choose coins to use
1067 set<pair<const CWalletTx*,unsigned int> > setCoins;
1069 if (!SelectCoins(nTotalValue, setCoins, nValueIn))
1071 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1073 int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
1074 dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
1077 int64 nChange = nValueIn - nValue - nFeeRet;
1078 // if sub-cent change is required, the fee must be raised to at least MIN_TX_FEE
1079 // or until nChange becomes zero
1080 // NOTE: this depends on the exact behaviour of GetMinFee
1081 if (nFeeRet < MIN_TX_FEE && nChange > 0 && nChange < CENT)
1083 int64 nMoveToFee = min(nChange, MIN_TX_FEE - nFeeRet);
1084 nChange -= nMoveToFee;
1085 nFeeRet += nMoveToFee;
1090 // Note: We use a new key here to keep it from being obvious which side is the change.
1091 // The drawback is that by not reusing a previous key, the change may be lost if a
1092 // backup is restored, if the backup doesn't have the new private key for the change.
1093 // If we reused the old key, it would be possible to add code to look for and
1094 // rediscover unknown transactions that were written with keys of ours to recover
1095 // post-backup change.
1097 // Reserve a new key pair from key pool
1098 vector<unsigned char> vchPubKey = reservekey.GetReservedKey();
1099 // assert(mapKeys.count(vchPubKey));
1101 // Fill a vout to ourself
1102 // TODO: pass in scriptChange instead of reservekey so
1103 // change transaction isn't always pay-to-bitcoin-address
1104 CScript scriptChange;
1105 scriptChange.SetBitcoinAddress(vchPubKey);
1107 // Insert change txn at random position:
1108 vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
1109 wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
1112 reservekey.ReturnKey();
1115 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1116 wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
1120 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1121 if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
1125 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
1126 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1128 dPriority /= nBytes;
1130 // Check that enough fee is included
1131 int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
1132 bool fAllowFree = CTransaction::AllowFree(dPriority);
1133 int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND);
1134 if (nFeeRet < max(nPayFee, nMinFee))
1136 nFeeRet = max(nPayFee, nMinFee);
1140 // Fill vtxPrev by copying from previous transactions vtxPrev
1141 wtxNew.AddSupportingTransactions(txdb);
1142 wtxNew.fTimeReceivedIsTxTime = true;
1151 bool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
1153 vector< pair<CScript, int64> > vecSend;
1154 vecSend.push_back(make_pair(scriptPubKey, nValue));
1155 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet);
1158 // Call after CreateTransaction unless you want to abort
1159 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
1162 LOCK2(cs_main, cs_wallet);
1163 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
1165 // This is only to keep the database open to defeat the auto-flush for the
1166 // duration of this scope. This is the only place where this optimization
1167 // maybe makes sense; please don't do it anywhere else.
1168 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
1170 // Take key pair from key pool so it won't be used again
1171 reservekey.KeepKey();
1173 // Add tx to wallet, because if it has change it's also ours,
1174 // otherwise just for transaction history.
1175 AddToWallet(wtxNew);
1177 // Mark old coins as spent
1178 set<CWalletTx*> setCoins;
1179 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
1181 CWalletTx &coin = mapWallet[txin.prevout.hash];
1182 coin.BindWallet(this);
1183 coin.MarkSpent(txin.prevout.n);
1185 vWalletUpdated.push_back(coin.GetHash());
1192 // Track how many getdata requests our transaction gets
1193 mapRequestCount[wtxNew.GetHash()] = 0;
1196 if (!wtxNew.AcceptToMemoryPool())
1198 // This must not fail. The transaction has already been signed and recorded.
1199 printf("CommitTransaction() : Error: Transaction not valid");
1202 wtxNew.RelayWalletTransaction();
1211 string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1213 CReserveKey reservekey(this);
1218 string strError = _("Error: Wallet locked, unable to create transaction ");
1219 printf("SendMoney() : %s", strError.c_str());
1222 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
1225 if (nValue + nFeeRequired > GetBalance())
1226 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());
1228 strError = _("Error: Transaction creation failed ");
1229 printf("SendMoney() : %s", strError.c_str());
1233 if (fAskFee && !ThreadSafeAskFee(nFeeRequired, _("Sending...")))
1236 if (!CommitTransaction(wtxNew, reservekey))
1237 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.");
1245 string CWallet::SendMoneyToBitcoinAddress(const CBitcoinAddress& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1249 return _("Invalid amount");
1250 if (nValue + nTransactionFee > GetBalance())
1251 return _("Insufficient funds");
1253 // Parse bitcoin address
1254 CScript scriptPubKey;
1255 scriptPubKey.SetBitcoinAddress(address);
1257 return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
1263 int CWallet::LoadWallet(bool& fFirstRunRet)
1267 fFirstRunRet = false;
1268 int nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
1269 if (nLoadWalletRet == DB_NEED_REWRITE)
1271 if (CDB::Rewrite(strWalletFile, "\x04pool"))
1274 // Note: can't top-up keypool here, because wallet is locked.
1275 // User will be prompted to unlock wallet the next operation
1276 // the requires a new key.
1278 nLoadWalletRet = DB_NEED_REWRITE;
1281 if (nLoadWalletRet != DB_LOAD_OK)
1282 return nLoadWalletRet;
1283 fFirstRunRet = vchDefaultKey.empty();
1285 CreateThread(ThreadFlushWalletDB, &strWalletFile);
1290 bool CWallet::SetAddressBookName(const CBitcoinAddress& address, const string& strName)
1292 mapAddressBook[address] = strName;
1293 AddressBookRepaint();
1296 return CWalletDB(strWalletFile).WriteName(address.ToString(), strName);
1299 bool CWallet::DelAddressBookName(const CBitcoinAddress& address)
1301 mapAddressBook.erase(address);
1302 AddressBookRepaint();
1305 return CWalletDB(strWalletFile).EraseName(address.ToString());
1309 void CWallet::PrintWallet(const CBlock& block)
1313 if (mapWallet.count(block.vtx[0].GetHash()))
1315 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
1316 printf(" mine: %d %d %d", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
1322 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
1326 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
1327 if (mi != mapWallet.end())
1336 bool CWallet::SetDefaultKey(const std::vector<unsigned char> &vchPubKey)
1340 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
1343 vchDefaultKey = vchPubKey;
1347 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
1349 if (!pwallet->fFileBacked)
1351 strWalletFileOut = pwallet->strWalletFile;
1356 // Mark old keypool keys as used,
1357 // and generate all new keys
1359 bool CWallet::NewKeyPool()
1363 CWalletDB walletdb(strWalletFile);
1364 BOOST_FOREACH(int64 nIndex, setKeyPool)
1365 walletdb.ErasePool(nIndex);
1371 int64 nKeys = max(GetArg("-keypool", 100), (int64)0);
1372 for (int i = 0; i < nKeys; i++)
1375 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
1376 setKeyPool.insert(nIndex);
1378 printf("CWallet::NewKeyPool wrote %"PRI64d" new keys\n", nKeys);
1383 bool CWallet::TopUpKeyPool()
1391 CWalletDB walletdb(strWalletFile);
1394 unsigned int nTargetSize = max(GetArg("-keypool", 100), 0LL);
1395 while (setKeyPool.size() < (nTargetSize + 1))
1398 if (!setKeyPool.empty())
1399 nEnd = *(--setKeyPool.end()) + 1;
1400 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
1401 throw runtime_error("TopUpKeyPool() : writing generated key failed");
1402 setKeyPool.insert(nEnd);
1403 printf("keypool added key %"PRI64d", size=%d\n", nEnd, setKeyPool.size());
1409 void CWallet::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool)
1412 keypool.vchPubKey.clear();
1419 // Get the oldest key
1420 if(setKeyPool.empty())
1423 CWalletDB walletdb(strWalletFile);
1425 nIndex = *(setKeyPool.begin());
1426 setKeyPool.erase(setKeyPool.begin());
1427 if (!walletdb.ReadPool(nIndex, keypool))
1428 throw runtime_error("ReserveKeyFromKeyPool() : read failed");
1429 if (!HaveKey(Hash160(keypool.vchPubKey)))
1430 throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
1431 assert(!keypool.vchPubKey.empty());
1432 printf("keypool reserve %"PRI64d"\n", nIndex);
1436 int64 CWallet::AddReserveKey(const CKeyPool& keypool)
1439 LOCK2(cs_main, cs_wallet);
1440 CWalletDB walletdb(strWalletFile);
1442 int64 nIndex = 1 + *(--setKeyPool.end());
1443 if (!walletdb.WritePool(nIndex, keypool))
1444 throw runtime_error("AddReserveKey() : writing added key failed");
1445 setKeyPool.insert(nIndex);
1451 void CWallet::KeepKey(int64 nIndex)
1453 // Remove from key pool
1456 CWalletDB walletdb(strWalletFile);
1457 walletdb.ErasePool(nIndex);
1459 printf("keypool keep %"PRI64d"\n", nIndex);
1462 void CWallet::ReturnKey(int64 nIndex)
1464 // Return to key pool
1467 setKeyPool.insert(nIndex);
1469 printf("keypool return %"PRI64d"\n", nIndex);
1472 bool CWallet::GetKeyFromPool(vector<unsigned char>& result, bool fAllowReuse)
1478 ReserveKeyFromKeyPool(nIndex, keypool);
1481 if (fAllowReuse && !vchDefaultKey.empty())
1483 result = vchDefaultKey;
1486 if (IsLocked()) return false;
1487 result = GenerateNewKey();
1491 result = keypool.vchPubKey;
1496 int64 CWallet::GetOldestKeyPoolTime()
1500 ReserveKeyFromKeyPool(nIndex, keypool);
1504 return keypool.nTime;
1507 vector<unsigned char> CReserveKey::GetReservedKey()
1512 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
1514 vchPubKey = keypool.vchPubKey;
1517 printf("CReserveKey::GetReservedKey(): Warning: using default key instead of a new key, top up your keypool.");
1518 vchPubKey = pwallet->vchDefaultKey;
1521 assert(!vchPubKey.empty());
1525 void CReserveKey::KeepKey()
1528 pwallet->KeepKey(nIndex);
1533 void CReserveKey::ReturnKey()
1536 pwallet->ReturnKey(nIndex);
1541 void CWallet::GetAllReserveAddresses(set<CBitcoinAddress>& setAddress)
1545 CWalletDB walletdb(strWalletFile);
1547 LOCK2(cs_main, cs_wallet);
1548 BOOST_FOREACH(const int64& id, setKeyPool)
1551 if (!walletdb.ReadPool(id, keypool))
1552 throw runtime_error("GetAllReserveKeyHashes() : read failed");
1553 CBitcoinAddress address(keypool.vchPubKey);
1554 assert(!keypool.vchPubKey.empty());
1555 if (!HaveKey(address))
1556 throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
1557 setAddress.insert(address);