1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2011 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.
13 //////////////////////////////////////////////////////////////////////////////
18 bool CWallet::AddKey(const CKey& key)
20 if (!CCryptoKeyStore::AddKey(key))
25 return CWalletDB(strWalletFile).WriteKey(key.GetPubKey(), key.GetPrivKey());
29 bool CWallet::AddCryptedKey(const vector<unsigned char> &vchPubKey, const vector<unsigned char> &vchCryptedSecret)
31 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
35 CRITICAL_BLOCK(cs_wallet)
37 if (pwalletdbEncryption)
38 return pwalletdbEncryption->WriteCryptedKey(vchPubKey, vchCryptedSecret);
40 return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret);
45 bool CWallet::AddCScript(const uint160 &hash, const CScript& redeemScript)
47 if (!CCryptoKeyStore::AddCScript(hash, redeemScript))
51 return CWalletDB(strWalletFile).WriteCScript(hash, redeemScript);
54 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
60 CKeyingMaterial vMasterKey;
62 CRITICAL_BLOCK(cs_wallet)
63 BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
65 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
67 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
69 if (CCryptoKeyStore::Unlock(vMasterKey))
75 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
77 bool fWasLocked = IsLocked();
79 CRITICAL_BLOCK(cs_wallet)
84 CKeyingMaterial vMasterKey;
85 BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
87 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
89 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
91 if (CCryptoKeyStore::Unlock(vMasterKey))
93 int64 nStartTime = GetTimeMillis();
94 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
95 pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
97 nStartTime = GetTimeMillis();
98 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
99 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
101 if (pMasterKey.second.nDeriveIterations < 25000)
102 pMasterKey.second.nDeriveIterations = 25000;
104 printf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
106 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
108 if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
110 CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
122 // This class implements an addrIncoming entry that causes pre-0.4
123 // clients to crash on startup if reading a private-key-encrypted wallet.
124 class CCorruptAddress
129 if (nType & SER_DISK)
134 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
139 CKeyingMaterial vMasterKey;
140 RandAddSeedPerfmon();
142 vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
143 RAND_bytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
145 CMasterKey kMasterKey;
147 RandAddSeedPerfmon();
148 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
149 RAND_bytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
152 int64 nStartTime = GetTimeMillis();
153 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
154 kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
156 nStartTime = GetTimeMillis();
157 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
158 kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
160 if (kMasterKey.nDeriveIterations < 25000)
161 kMasterKey.nDeriveIterations = 25000;
163 printf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
165 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
167 if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
170 CRITICAL_BLOCK(cs_wallet)
172 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
175 pwalletdbEncryption = new CWalletDB(strWalletFile);
176 pwalletdbEncryption->TxnBegin();
177 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
180 if (!EncryptKeys(vMasterKey))
183 pwalletdbEncryption->TxnAbort();
184 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.
189 CCorruptAddress corruptAddress;
190 pwalletdbEncryption->WriteSetting("addrIncoming", corruptAddress);
191 if (!pwalletdbEncryption->TxnCommit())
192 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.
194 pwalletdbEncryption->Close();
195 pwalletdbEncryption = NULL;
199 Unlock(strWalletPassphrase);
203 // Need to completely rewrite the wallet file; if we don't, bdb might keep
204 // bits of the unencrypted private key in slack space in the database file.
205 CDB::Rewrite(strWalletFile);
211 void CWallet::WalletUpdateSpent(const CTransaction &tx)
213 // Anytime a signature is successfully verified, it's proof the outpoint is spent.
214 // Update the wallet spent flag if it doesn't know due to wallet.dat being
215 // restored from backup or the user making copies of wallet.dat.
216 CRITICAL_BLOCK(cs_wallet)
218 BOOST_FOREACH(const CTxIn& txin, tx.vin)
220 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
221 if (mi != mapWallet.end())
223 CWalletTx& wtx = (*mi).second;
224 if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n]))
226 printf("WalletUpdateSpent found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
227 wtx.MarkSpent(txin.prevout.n);
229 vWalletUpdated.push_back(txin.prevout.hash);
236 void CWallet::MarkDirty()
238 CRITICAL_BLOCK(cs_wallet)
240 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
241 item.second.MarkDirty();
245 bool CWallet::AddToWallet(const CWalletTx& wtxIn)
247 uint256 hash = wtxIn.GetHash();
248 CRITICAL_BLOCK(cs_wallet)
250 // Inserts only if not already there, returns tx inserted or tx found
251 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
252 CWalletTx& wtx = (*ret.first).second;
253 wtx.BindWallet(this);
254 bool fInsertedNew = ret.second;
256 wtx.nTimeReceived = GetAdjustedTime();
258 bool fUpdated = false;
262 if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
264 wtx.hashBlock = wtxIn.hashBlock;
267 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
269 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
270 wtx.nIndex = wtxIn.nIndex;
273 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
275 wtx.fFromMe = wtxIn.fFromMe;
278 fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);
282 printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
285 if (fInsertedNew || fUpdated)
286 if (!wtx.WriteToDisk())
289 // If default receiving address gets used, replace it with a new one
290 CScript scriptDefaultKey;
291 scriptDefaultKey.SetBitcoinAddress(vchDefaultKey);
292 BOOST_FOREACH(const CTxOut& txout, wtx.vout)
294 if (txout.scriptPubKey == scriptDefaultKey)
296 std::vector<unsigned char> newDefaultKey;
297 if (GetKeyFromPool(newDefaultKey, false))
299 SetDefaultKey(newDefaultKey);
300 SetAddressBookName(CBitcoinAddress(vchDefaultKey), "");
306 vWalletUpdated.push_back(hash);
308 // since AddToWallet is called directly for self-originating transactions, check for consumption of own coins
309 WalletUpdateSpent(wtx);
317 // Add a transaction to the wallet, or update it.
318 // pblock is optional, but should be provided if the transaction is known to be in a block.
319 // If fUpdate is true, existing transactions will be updated.
320 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fFindBlock)
322 uint256 hash = tx.GetHash();
323 CRITICAL_BLOCK(cs_wallet)
325 bool fExisted = mapWallet.count(hash);
326 if (fExisted && !fUpdate) return false;
327 if (fExisted || IsMine(tx) || IsFromMe(tx))
329 CWalletTx wtx(this,tx);
330 // Get merkle branch if transaction was found in a block
332 wtx.SetMerkleBranch(pblock);
333 return AddToWallet(wtx);
336 WalletUpdateSpent(tx);
341 bool CWallet::EraseFromWallet(uint256 hash)
345 CRITICAL_BLOCK(cs_wallet)
347 if (mapWallet.erase(hash))
348 CWalletDB(strWalletFile).EraseTx(hash);
354 bool CWallet::IsMine(const CTxIn &txin) const
356 CRITICAL_BLOCK(cs_wallet)
358 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
359 if (mi != mapWallet.end())
361 const CWalletTx& prev = (*mi).second;
362 if (txin.prevout.n < prev.vout.size())
363 if (IsMine(prev.vout[txin.prevout.n]))
370 int64 CWallet::GetDebit(const CTxIn &txin) const
372 CRITICAL_BLOCK(cs_wallet)
374 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
375 if (mi != mapWallet.end())
377 const CWalletTx& prev = (*mi).second;
378 if (txin.prevout.n < prev.vout.size())
379 if (IsMine(prev.vout[txin.prevout.n]))
380 return prev.vout[txin.prevout.n].nValue;
386 bool CWallet::IsChange(const CTxOut& txout) const
388 CBitcoinAddress address;
390 // TODO: fix handling of 'change' outputs. The assumption is that any
391 // payment to a TX_PUBKEYHASH that is mine but isn't in the address book
392 // is change. That assumption is likely to break when we implement multisignature
393 // wallets that return change back into a multi-signature-protected address;
394 // a better way of identifying which outputs are 'the send' and which are
395 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
396 // which output, if any, was change).
397 if (ExtractAddress(txout.scriptPubKey, this, address))
398 CRITICAL_BLOCK(cs_wallet)
399 if (!mapAddressBook.count(address))
404 int64 CWalletTx::GetTxTime() const
406 return nTimeReceived;
409 int CWalletTx::GetRequestCount() const
411 // Returns -1 if it wasn't being tracked
413 CRITICAL_BLOCK(pwallet->cs_wallet)
420 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
421 if (mi != pwallet->mapRequestCount.end())
422 nRequests = (*mi).second;
427 // Did anyone request this transaction?
428 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
429 if (mi != pwallet->mapRequestCount.end())
431 nRequests = (*mi).second;
433 // How about the block it's in?
434 if (nRequests == 0 && hashBlock != 0)
436 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
437 if (mi != pwallet->mapRequestCount.end())
438 nRequests = (*mi).second;
440 nRequests = 1; // If it's in someone else's block it must have got out
448 void CWalletTx::GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, list<pair<CBitcoinAddress, int64> >& listReceived,
449 list<pair<CBitcoinAddress, int64> >& listSent, int64& nFee, string& strSentAccount) const
451 nGeneratedImmature = nGeneratedMature = nFee = 0;
452 listReceived.clear();
454 strSentAccount = strFromAccount;
458 if (GetBlocksToMaturity() > 0)
459 nGeneratedImmature = pwallet->GetCredit(*this);
461 nGeneratedMature = GetCredit();
466 int64 nDebit = GetDebit();
467 if (nDebit > 0) // debit>0 means we signed/sent this transaction
469 int64 nValueOut = GetValueOut();
470 nFee = nDebit - nValueOut;
474 BOOST_FOREACH(const CTxOut& txout, vout)
476 CBitcoinAddress address;
477 vector<unsigned char> vchPubKey;
478 if (!ExtractAddress(txout.scriptPubKey, NULL, address))
480 printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
481 this->GetHash().ToString().c_str());
482 address = " unknown ";
485 // Don't report 'change' txouts
486 if (nDebit > 0 && pwallet->IsChange(txout))
490 listSent.push_back(make_pair(address, txout.nValue));
492 if (pwallet->IsMine(txout))
493 listReceived.push_back(make_pair(address, txout.nValue));
498 void CWalletTx::GetAccountAmounts(const string& strAccount, int64& nGenerated, int64& nReceived,
499 int64& nSent, int64& nFee) const
501 nGenerated = nReceived = nSent = nFee = 0;
503 int64 allGeneratedImmature, allGeneratedMature, allFee;
504 allGeneratedImmature = allGeneratedMature = allFee = 0;
505 string strSentAccount;
506 list<pair<CBitcoinAddress, int64> > listReceived;
507 list<pair<CBitcoinAddress, int64> > listSent;
508 GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount);
510 if (strAccount == "")
511 nGenerated = allGeneratedMature;
512 if (strAccount == strSentAccount)
514 BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress,int64)& s, listSent)
518 CRITICAL_BLOCK(pwallet->cs_wallet)
520 BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress,int64)& r, listReceived)
522 if (pwallet->mapAddressBook.count(r.first))
524 map<CBitcoinAddress, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);
525 if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)
526 nReceived += r.second;
528 else if (strAccount.empty())
530 nReceived += r.second;
536 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
540 const int COPY_DEPTH = 3;
541 if (SetMerkleBranch() < COPY_DEPTH)
543 vector<uint256> vWorkQueue;
544 BOOST_FOREACH(const CTxIn& txin, vin)
545 vWorkQueue.push_back(txin.prevout.hash);
547 // This critsect is OK because txdb is already open
548 CRITICAL_BLOCK(pwallet->cs_wallet)
550 map<uint256, const CMerkleTx*> mapWalletPrev;
551 set<uint256> setAlreadyDone;
552 for (int i = 0; i < vWorkQueue.size(); i++)
554 uint256 hash = vWorkQueue[i];
555 if (setAlreadyDone.count(hash))
557 setAlreadyDone.insert(hash);
560 map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
561 if (mi != pwallet->mapWallet.end())
564 BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev)
565 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
567 else if (mapWalletPrev.count(hash))
569 tx = *mapWalletPrev[hash];
571 else if (!fClient && txdb.ReadDiskTx(hash, tx))
577 printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
581 int nDepth = tx.SetMerkleBranch();
582 vtxPrev.push_back(tx);
584 if (nDepth < COPY_DEPTH)
585 BOOST_FOREACH(const CTxIn& txin, tx.vin)
586 vWorkQueue.push_back(txin.prevout.hash);
591 reverse(vtxPrev.begin(), vtxPrev.end());
594 bool CWalletTx::WriteToDisk()
596 return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
599 // Scan the block chain (starting in pindexStart) for transactions
600 // from or to us. If fUpdate is true, found transactions that already
601 // exist in the wallet will be updated.
602 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
606 CBlockIndex* pindex = pindexStart;
607 CRITICAL_BLOCK(cs_wallet)
612 block.ReadFromDisk(pindex, true);
613 BOOST_FOREACH(CTransaction& tx, block.vtx)
615 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
618 pindex = pindex->pnext;
624 int CWallet::ScanForWalletTransaction(const uint256& hashTx)
627 tx.ReadFromDisk(COutPoint(hashTx, 0));
628 if (AddToWalletIfInvolvingMe(tx, NULL, true, true))
633 void CWallet::ReacceptWalletTransactions()
637 while (fRepeat) CRITICAL_BLOCK(cs_wallet)
640 vector<CDiskTxPos> vMissingTx;
641 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
643 CWalletTx& wtx = item.second;
644 if (wtx.IsCoinBase() && wtx.IsSpent(0))
648 bool fUpdated = false;
649 if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
651 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
652 if (txindex.vSpent.size() != wtx.vout.size())
654 printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %d != wtx.vout.size() %d\n", txindex.vSpent.size(), wtx.vout.size());
657 for (int i = 0; i < txindex.vSpent.size(); i++)
661 if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i]))
665 vMissingTx.push_back(txindex.vSpent[i]);
670 printf("ReacceptWalletTransactions found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
677 // Reaccept any txes of ours that aren't already in a block
678 if (!wtx.IsCoinBase())
679 wtx.AcceptWalletTransaction(txdb, false);
682 if (!vMissingTx.empty())
684 // TODO: optimize this to scan just part of the block chain?
685 if (ScanForWalletTransactions(pindexGenesisBlock))
686 fRepeat = true; // Found missing transactions: re-do Reaccept.
691 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
693 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
695 if (!tx.IsCoinBase())
697 uint256 hash = tx.GetHash();
698 if (!txdb.ContainsTx(hash))
699 RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx);
704 uint256 hash = GetHash();
705 if (!txdb.ContainsTx(hash))
707 printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
708 RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this);
713 void CWalletTx::RelayWalletTransaction()
716 RelayWalletTransaction(txdb);
719 void CWallet::ResendWalletTransactions()
721 // Do this infrequently and randomly to avoid giving away
722 // that these are our transactions.
723 static int64 nNextTime;
724 if (GetTime() < nNextTime)
726 bool fFirst = (nNextTime == 0);
727 nNextTime = GetTime() + GetRand(30 * 60);
731 // Only do it if there's been a new block since last time
732 static int64 nLastTime;
733 if (nTimeBestReceived < nLastTime)
735 nLastTime = GetTime();
737 // Rebroadcast any of our txes that aren't in a block yet
738 printf("ResendWalletTransactions()\n");
740 CRITICAL_BLOCK(cs_wallet)
742 // Sort them in chronological order
743 multimap<unsigned int, CWalletTx*> mapSorted;
744 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
746 CWalletTx& wtx = item.second;
747 // Don't rebroadcast until it's had plenty of time that
748 // it should have gotten in already by now.
749 if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
750 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
752 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
754 CWalletTx& wtx = *item.second;
755 wtx.RelayWalletTransaction(txdb);
765 //////////////////////////////////////////////////////////////////////////////
771 int64 CWallet::GetBalance() const
774 CRITICAL_BLOCK(cs_wallet)
776 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
778 const CWalletTx* pcoin = &(*it).second;
779 if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
781 nTotal += pcoin->GetAvailableCredit();
788 int64 CWallet::GetUnconfirmedBalance() const
791 CRITICAL_BLOCK(cs_wallet)
793 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
795 const CWalletTx* pcoin = &(*it).second;
796 if (pcoin->IsFinal() && pcoin->IsConfirmed())
798 nTotal += pcoin->GetAvailableCredit();
804 bool CWallet::SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
809 // List of values less than target
810 pair<int64, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
811 coinLowestLarger.first = INT64_MAX;
812 coinLowestLarger.second.first = NULL;
813 vector<pair<int64, pair<const CWalletTx*,unsigned int> > > vValue;
814 int64 nTotalLower = 0;
816 CRITICAL_BLOCK(cs_wallet)
818 vector<const CWalletTx*> vCoins;
819 vCoins.reserve(mapWallet.size());
820 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
821 vCoins.push_back(&(*it).second);
822 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
824 BOOST_FOREACH(const CWalletTx* pcoin, vCoins)
826 if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
829 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
832 int nDepth = pcoin->GetDepthInMainChain();
833 if (nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs))
836 for (int i = 0; i < pcoin->vout.size(); i++)
838 if (pcoin->IsSpent(i) || !IsMine(pcoin->vout[i]))
841 int64 n = pcoin->vout[i].nValue;
846 pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin,i));
848 if (n == nTargetValue)
850 setCoinsRet.insert(coin.second);
851 nValueRet += coin.first;
854 else if (n < nTargetValue + CENT)
856 vValue.push_back(coin);
859 else if (n < coinLowestLarger.first)
861 coinLowestLarger = coin;
867 if (nTotalLower == nTargetValue || nTotalLower == nTargetValue + CENT)
869 for (int i = 0; i < vValue.size(); ++i)
871 setCoinsRet.insert(vValue[i].second);
872 nValueRet += vValue[i].first;
877 if (nTotalLower < nTargetValue + (coinLowestLarger.second.first ? CENT : 0))
879 if (coinLowestLarger.second.first == NULL)
881 setCoinsRet.insert(coinLowestLarger.second);
882 nValueRet += coinLowestLarger.first;
886 if (nTotalLower >= nTargetValue + CENT)
887 nTargetValue += CENT;
889 // Solve subset sum by stochastic approximation
890 sort(vValue.rbegin(), vValue.rend());
891 vector<char> vfIncluded;
892 vector<char> vfBest(vValue.size(), true);
893 int64 nBest = nTotalLower;
895 for (int nRep = 0; nRep < 1000 && nBest != nTargetValue; nRep++)
897 vfIncluded.assign(vValue.size(), false);
899 bool fReachedTarget = false;
900 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
902 for (int i = 0; i < vValue.size(); i++)
904 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
906 nTotal += vValue[i].first;
907 vfIncluded[i] = true;
908 if (nTotal >= nTargetValue)
910 fReachedTarget = true;
916 nTotal -= vValue[i].first;
917 vfIncluded[i] = false;
924 // If the next larger is still closer, return it
925 if (coinLowestLarger.second.first && coinLowestLarger.first - nTargetValue <= nBest - nTargetValue)
927 setCoinsRet.insert(coinLowestLarger.second);
928 nValueRet += coinLowestLarger.first;
931 for (int i = 0; i < vValue.size(); i++)
934 setCoinsRet.insert(vValue[i].second);
935 nValueRet += vValue[i].first;
939 printf("SelectCoins() best subset: ");
940 for (int i = 0; i < vValue.size(); i++)
942 printf("%s ", FormatMoney(vValue[i].first).c_str());
943 printf("total %s\n", FormatMoney(nBest).c_str());
949 bool CWallet::SelectCoins(int64 nTargetValue, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
951 return (SelectCoinsMinConf(nTargetValue, 1, 6, setCoinsRet, nValueRet) ||
952 SelectCoinsMinConf(nTargetValue, 1, 1, setCoinsRet, nValueRet) ||
953 SelectCoinsMinConf(nTargetValue, 0, 1, setCoinsRet, nValueRet));
959 bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
962 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
968 if (vecSend.empty() || nValue < 0)
971 wtxNew.BindWallet(this);
973 CRITICAL_BLOCK(cs_main)
974 CRITICAL_BLOCK(cs_wallet)
976 // txdb must be opened before the mapWallet lock
979 nFeeRet = nTransactionFee;
984 wtxNew.fFromMe = true;
986 int64 nTotalValue = nValue + nFeeRet;
987 double dPriority = 0;
988 // vouts to the payees
989 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
990 wtxNew.vout.push_back(CTxOut(s.second, s.first));
992 // Choose coins to use
993 set<pair<const CWalletTx*,unsigned int> > setCoins;
995 if (!SelectCoins(nTotalValue, setCoins, nValueIn))
997 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
999 int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
1000 dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
1003 int64 nChange = nValueIn - nValue - nFeeRet;
1004 // if sub-cent change is required, the fee must be raised to at least MIN_TX_FEE
1005 // or until nChange becomes zero
1006 if (nFeeRet < MIN_TX_FEE && nChange > 0 && nChange < CENT)
1008 int64 nMoveToFee = min(nChange, MIN_TX_FEE - nFeeRet);
1009 nChange -= nMoveToFee;
1010 nFeeRet += nMoveToFee;
1015 // Note: We use a new key here to keep it from being obvious which side is the change.
1016 // The drawback is that by not reusing a previous key, the change may be lost if a
1017 // backup is restored, if the backup doesn't have the new private key for the change.
1018 // If we reused the old key, it would be possible to add code to look for and
1019 // rediscover unknown transactions that were written with keys of ours to recover
1020 // post-backup change.
1022 // Reserve a new key pair from key pool
1023 vector<unsigned char> vchPubKey = reservekey.GetReservedKey();
1024 // assert(mapKeys.count(vchPubKey));
1026 // Fill a vout to ourself
1027 // TODO: pass in scriptChange instead of reservekey so
1028 // change transaction isn't always pay-to-bitcoin-address
1029 CScript scriptChange;
1030 scriptChange.SetBitcoinAddress(vchPubKey);
1032 // Insert change txn at random position:
1033 vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
1034 wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
1037 reservekey.ReturnKey();
1040 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1041 wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
1045 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1046 if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
1050 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK);
1051 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1053 dPriority /= nBytes;
1055 // Check that enough fee is included
1056 int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
1057 bool fAllowFree = CTransaction::AllowFree(dPriority);
1058 int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree);
1059 if (nFeeRet < max(nPayFee, nMinFee))
1061 nFeeRet = max(nPayFee, nMinFee);
1065 // Fill vtxPrev by copying from previous transactions vtxPrev
1066 wtxNew.AddSupportingTransactions(txdb);
1067 wtxNew.fTimeReceivedIsTxTime = true;
1076 bool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
1078 vector< pair<CScript, int64> > vecSend;
1079 vecSend.push_back(make_pair(scriptPubKey, nValue));
1080 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet);
1083 // Call after CreateTransaction unless you want to abort
1084 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
1086 CRITICAL_BLOCK(cs_main)
1087 CRITICAL_BLOCK(cs_wallet)
1089 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
1091 // This is only to keep the database open to defeat the auto-flush for the
1092 // duration of this scope. This is the only place where this optimization
1093 // maybe makes sense; please don't do it anywhere else.
1094 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
1096 // Take key pair from key pool so it won't be used again
1097 reservekey.KeepKey();
1099 // Add tx to wallet, because if it has change it's also ours,
1100 // otherwise just for transaction history.
1101 AddToWallet(wtxNew);
1103 // Mark old coins as spent
1104 set<CWalletTx*> setCoins;
1105 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
1107 CWalletTx &coin = mapWallet[txin.prevout.hash];
1108 coin.BindWallet(this);
1109 coin.MarkSpent(txin.prevout.n);
1111 vWalletUpdated.push_back(coin.GetHash());
1118 // Track how many getdata requests our transaction gets
1119 mapRequestCount[wtxNew.GetHash()] = 0;
1122 if (!wtxNew.AcceptToMemoryPool())
1124 // This must not fail. The transaction has already been signed and recorded.
1125 printf("CommitTransaction() : Error: Transaction not valid");
1128 wtxNew.RelayWalletTransaction();
1137 string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1139 CReserveKey reservekey(this);
1144 string strError = _("Error: Wallet locked, unable to create transaction ");
1145 printf("SendMoney() : %s", strError.c_str());
1148 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
1151 if (nValue + nFeeRequired > GetBalance())
1152 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());
1154 strError = _("Error: Transaction creation failed ");
1155 printf("SendMoney() : %s", strError.c_str());
1159 if (fAskFee && !ThreadSafeAskFee(nFeeRequired, _("Sending..."), NULL))
1162 if (!CommitTransaction(wtxNew, reservekey))
1163 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.");
1171 string CWallet::SendMoneyToBitcoinAddress(const CBitcoinAddress& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1175 return _("Invalid amount");
1176 if (nValue + nTransactionFee > GetBalance())
1177 return _("Insufficient funds");
1179 // Parse bitcoin address
1180 CScript scriptPubKey;
1181 scriptPubKey.SetBitcoinAddress(address);
1183 return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
1189 int CWallet::LoadWallet(bool& fFirstRunRet)
1193 fFirstRunRet = false;
1194 int nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
1195 if (nLoadWalletRet == DB_NEED_REWRITE)
1197 if (CDB::Rewrite(strWalletFile, "\x04pool"))
1200 // Note: can't top-up keypool here, because wallet is locked.
1201 // User will be prompted to unlock wallet the next operation
1202 // the requires a new key.
1204 nLoadWalletRet = DB_NEED_REWRITE;
1207 if (nLoadWalletRet != DB_LOAD_OK)
1208 return nLoadWalletRet;
1209 fFirstRunRet = vchDefaultKey.empty();
1211 if (!HaveKey(Hash160(vchDefaultKey)))
1213 // Create new keyUser and set as default key
1214 RandAddSeedPerfmon();
1216 std::vector<unsigned char> newDefaultKey;
1217 if (!GetKeyFromPool(newDefaultKey, false))
1218 return DB_LOAD_FAIL;
1219 SetDefaultKey(newDefaultKey);
1220 if (!SetAddressBookName(CBitcoinAddress(vchDefaultKey), ""))
1221 return DB_LOAD_FAIL;
1224 CreateThread(ThreadFlushWalletDB, &strWalletFile);
1229 bool CWallet::SetAddressBookName(const CBitcoinAddress& address, const string& strName)
1231 mapAddressBook[address] = strName;
1234 return CWalletDB(strWalletFile).WriteName(address.ToString(), strName);
1237 bool CWallet::DelAddressBookName(const CBitcoinAddress& address)
1239 mapAddressBook.erase(address);
1242 return CWalletDB(strWalletFile).EraseName(address.ToString());
1246 void CWallet::PrintWallet(const CBlock& block)
1248 CRITICAL_BLOCK(cs_wallet)
1250 if (mapWallet.count(block.vtx[0].GetHash()))
1252 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
1253 printf(" mine: %d %d %d", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
1259 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
1261 CRITICAL_BLOCK(cs_wallet)
1263 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
1264 if (mi != mapWallet.end())
1273 bool CWallet::SetDefaultKey(const std::vector<unsigned char> &vchPubKey)
1277 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
1280 vchDefaultKey = vchPubKey;
1284 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
1286 if (!pwallet->fFileBacked)
1288 strWalletFileOut = pwallet->strWalletFile;
1293 // Mark old keypool keys as used,
1294 // and generate all new keys
1296 bool CWallet::NewKeyPool()
1298 CRITICAL_BLOCK(cs_wallet)
1300 CWalletDB walletdb(strWalletFile);
1301 BOOST_FOREACH(int64 nIndex, setKeyPool)
1302 walletdb.ErasePool(nIndex);
1308 int64 nKeys = max(GetArg("-keypool", 100), (int64)0);
1309 for (int i = 0; i < nKeys; i++)
1312 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
1313 setKeyPool.insert(nIndex);
1315 printf("CWallet::NewKeyPool wrote %"PRI64d" new keys\n", nKeys);
1320 bool CWallet::TopUpKeyPool()
1322 CRITICAL_BLOCK(cs_wallet)
1327 CWalletDB walletdb(strWalletFile);
1330 int64 nTargetSize = max(GetArg("-keypool", 100), (int64)0);
1331 while (setKeyPool.size() < nTargetSize+1)
1334 if (!setKeyPool.empty())
1335 nEnd = *(--setKeyPool.end()) + 1;
1336 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
1337 throw runtime_error("TopUpKeyPool() : writing generated key failed");
1338 setKeyPool.insert(nEnd);
1339 printf("keypool added key %"PRI64d", size=%d\n", nEnd, setKeyPool.size());
1345 void CWallet::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool)
1348 keypool.vchPubKey.clear();
1349 CRITICAL_BLOCK(cs_wallet)
1354 // Get the oldest key
1355 if(setKeyPool.empty())
1358 CWalletDB walletdb(strWalletFile);
1360 nIndex = *(setKeyPool.begin());
1361 setKeyPool.erase(setKeyPool.begin());
1362 if (!walletdb.ReadPool(nIndex, keypool))
1363 throw runtime_error("ReserveKeyFromKeyPool() : read failed");
1364 if (!HaveKey(Hash160(keypool.vchPubKey)))
1365 throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
1366 assert(!keypool.vchPubKey.empty());
1367 printf("keypool reserve %"PRI64d"\n", nIndex);
1371 int64 CWallet::AddReserveKey(const CKeyPool& keypool)
1373 CRITICAL_BLOCK(cs_main)
1374 CRITICAL_BLOCK(cs_wallet)
1376 CWalletDB walletdb(strWalletFile);
1378 int64 nIndex = 1 + *(--setKeyPool.end());
1379 if (!walletdb.WritePool(nIndex, keypool))
1380 throw runtime_error("AddReserveKey() : writing added key failed");
1381 setKeyPool.insert(nIndex);
1387 void CWallet::KeepKey(int64 nIndex)
1389 // Remove from key pool
1392 CWalletDB walletdb(strWalletFile);
1393 walletdb.ErasePool(nIndex);
1395 printf("keypool keep %"PRI64d"\n", nIndex);
1398 void CWallet::ReturnKey(int64 nIndex)
1400 // Return to key pool
1401 CRITICAL_BLOCK(cs_wallet)
1402 setKeyPool.insert(nIndex);
1403 printf("keypool return %"PRI64d"\n", nIndex);
1406 bool CWallet::GetKeyFromPool(vector<unsigned char>& result, bool fAllowReuse)
1410 CRITICAL_BLOCK(cs_wallet)
1412 ReserveKeyFromKeyPool(nIndex, keypool);
1415 if (fAllowReuse && !vchDefaultKey.empty())
1417 result = vchDefaultKey;
1420 if (IsLocked()) return false;
1421 result = GenerateNewKey();
1425 result = keypool.vchPubKey;
1430 int64 CWallet::GetOldestKeyPoolTime()
1434 ReserveKeyFromKeyPool(nIndex, keypool);
1438 return keypool.nTime;
1441 vector<unsigned char> CReserveKey::GetReservedKey()
1446 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
1448 vchPubKey = keypool.vchPubKey;
1451 printf("CReserveKey::GetReservedKey(): Warning: using default key instead of a new key, top up your keypool.");
1452 vchPubKey = pwallet->vchDefaultKey;
1455 assert(!vchPubKey.empty());
1459 void CReserveKey::KeepKey()
1462 pwallet->KeepKey(nIndex);
1467 void CReserveKey::ReturnKey()
1470 pwallet->ReturnKey(nIndex);
1475 void CWallet::GetAllReserveAddresses(set<CBitcoinAddress>& setAddress)
1479 CWalletDB walletdb(strWalletFile);
1481 CRITICAL_BLOCK(cs_main)
1482 CRITICAL_BLOCK(cs_wallet)
1483 BOOST_FOREACH(const int64& id, setKeyPool)
1486 if (!walletdb.ReadPool(id, keypool))
1487 throw runtime_error("GetAllReserveKeyHashes() : read failed");
1488 CBitcoinAddress address(keypool.vchPubKey);
1489 assert(!keypool.vchPubKey.empty());
1490 if (!HaveKey(address))
1491 throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
1492 setAddress.insert(address);