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.
15 //////////////////////////////////////////////////////////////////////////////
20 bool CWallet::AddKey(const CKey& key)
22 if (!CCryptoKeyStore::AddKey(key))
27 return CWalletDB(strWalletFile).WriteKey(key.GetPubKey(), key.GetPrivKey());
31 bool CWallet::AddCryptedKey(const vector<unsigned char> &vchPubKey, const vector<unsigned char> &vchCryptedSecret)
33 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
37 CRITICAL_BLOCK(cs_wallet)
39 if (pwalletdbEncryption)
40 return pwalletdbEncryption->WriteCryptedKey(vchPubKey, vchCryptedSecret);
42 return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret);
47 bool CWallet::AddCScript(const uint160 &hash, const CScript& redeemScript)
49 if (!CCryptoKeyStore::AddCScript(hash, redeemScript))
53 return CWalletDB(strWalletFile).WriteCScript(hash, redeemScript);
56 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
62 CKeyingMaterial vMasterKey;
64 CRITICAL_BLOCK(cs_wallet)
65 BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
67 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
69 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
71 if (CCryptoKeyStore::Unlock(vMasterKey))
77 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
79 bool fWasLocked = IsLocked();
81 CRITICAL_BLOCK(cs_wallet)
86 CKeyingMaterial vMasterKey;
87 BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
89 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
91 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
93 if (CCryptoKeyStore::Unlock(vMasterKey))
95 int64_t nStartTime = GetTimeMillis();
96 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
97 pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
99 nStartTime = GetTimeMillis();
100 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
101 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
103 if (pMasterKey.second.nDeriveIterations < 25000)
104 pMasterKey.second.nDeriveIterations = 25000;
106 printf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
108 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
110 if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
112 CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
124 // This class implements an addrIncoming entry that causes pre-0.4
125 // clients to crash on startup if reading a private-key-encrypted wallet.
126 class CCorruptAddress
131 if (nType & SER_DISK)
136 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
141 CKeyingMaterial vMasterKey;
142 RandAddSeedPerfmon();
144 vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
145 RAND_bytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
147 CMasterKey kMasterKey;
149 RandAddSeedPerfmon();
150 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
151 RAND_bytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
154 int64_t nStartTime = GetTimeMillis();
155 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
156 kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
158 nStartTime = GetTimeMillis();
159 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
160 kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
162 if (kMasterKey.nDeriveIterations < 25000)
163 kMasterKey.nDeriveIterations = 25000;
165 printf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
167 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
169 if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
172 CRITICAL_BLOCK(cs_wallet)
174 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
177 pwalletdbEncryption = new CWalletDB(strWalletFile);
178 pwalletdbEncryption->TxnBegin();
179 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
182 if (!EncryptKeys(vMasterKey))
185 pwalletdbEncryption->TxnAbort();
186 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.
191 CCorruptAddress corruptAddress;
192 pwalletdbEncryption->WriteSetting("addrIncoming", corruptAddress);
193 if (!pwalletdbEncryption->TxnCommit())
194 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.
196 pwalletdbEncryption->Close();
197 pwalletdbEncryption = NULL;
201 Unlock(strWalletPassphrase);
205 // Need to completely rewrite the wallet file; if we don't, bdb might keep
206 // bits of the unencrypted private key in slack space in the database file.
207 CDB::Rewrite(strWalletFile);
213 void CWallet::WalletUpdateSpent(const CTransaction &tx)
215 // Anytime a signature is successfully verified, it's proof the outpoint is spent.
216 // Update the wallet spent flag if it doesn't know due to wallet.dat being
217 // restored from backup or the user making copies of wallet.dat.
218 CRITICAL_BLOCK(cs_wallet)
220 BOOST_FOREACH(const CTxIn& txin, tx.vin)
222 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
223 if (mi != mapWallet.end())
225 CWalletTx& wtx = (*mi).second;
226 if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n]))
228 printf("WalletUpdateSpent found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
229 wtx.MarkSpent(txin.prevout.n);
231 vWalletUpdated.push_back(txin.prevout.hash);
238 void CWallet::MarkDirty()
240 CRITICAL_BLOCK(cs_wallet)
242 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
243 item.second.MarkDirty();
247 bool CWallet::AddToWallet(const CWalletTx& wtxIn)
249 uint256 hash = wtxIn.GetHash();
250 CRITICAL_BLOCK(cs_wallet)
252 // Inserts only if not already there, returns tx inserted or tx found
253 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
254 CWalletTx& wtx = (*ret.first).second;
255 wtx.BindWallet(this);
256 bool fInsertedNew = ret.second;
258 wtx.nTimeReceived = GetAdjustedTime();
260 bool fUpdated = false;
264 if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
266 wtx.hashBlock = wtxIn.hashBlock;
269 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
271 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
272 wtx.nIndex = wtxIn.nIndex;
275 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
277 wtx.fFromMe = wtxIn.fFromMe;
280 fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);
284 printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
287 if (fInsertedNew || fUpdated)
288 if (!wtx.WriteToDisk())
291 // If default receiving address gets used, replace it with a new one
292 CScript scriptDefaultKey;
293 scriptDefaultKey.SetBitcoinAddress(vchDefaultKey);
294 BOOST_FOREACH(const CTxOut& txout, wtx.vout)
296 if (txout.scriptPubKey == scriptDefaultKey)
298 std::vector<unsigned char> newDefaultKey;
299 if (GetKeyFromPool(newDefaultKey, false))
301 SetDefaultKey(newDefaultKey);
302 SetAddressBookName(CBitcoinAddress(vchDefaultKey), "");
308 vWalletUpdated.push_back(hash);
310 // since AddToWallet is called directly for self-originating transactions, check for consumption of own coins
311 WalletUpdateSpent(wtx);
319 // Add a transaction to the wallet, or update it.
320 // pblock is optional, but should be provided if the transaction is known to be in a block.
321 // If fUpdate is true, existing transactions will be updated.
322 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fFindBlock)
324 uint256 hash = tx.GetHash();
325 CRITICAL_BLOCK(cs_wallet)
327 bool fExisted = mapWallet.count(hash);
328 if (fExisted && !fUpdate) return false;
329 if (fExisted || IsMine(tx) || IsFromMe(tx))
331 CWalletTx wtx(this,tx);
332 // Get merkle branch if transaction was found in a block
334 wtx.SetMerkleBranch(pblock);
335 return AddToWallet(wtx);
338 WalletUpdateSpent(tx);
343 bool CWallet::EraseFromWallet(uint256 hash)
347 CRITICAL_BLOCK(cs_wallet)
349 if (mapWallet.erase(hash))
350 CWalletDB(strWalletFile).EraseTx(hash);
356 bool CWallet::IsMine(const CTxIn &txin) const
358 CRITICAL_BLOCK(cs_wallet)
360 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
361 if (mi != mapWallet.end())
363 const CWalletTx& prev = (*mi).second;
364 if (txin.prevout.n < prev.vout.size())
365 if (IsMine(prev.vout[txin.prevout.n]))
372 int64_t CWallet::GetDebit(const CTxIn &txin) const
374 CRITICAL_BLOCK(cs_wallet)
376 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
377 if (mi != mapWallet.end())
379 const CWalletTx& prev = (*mi).second;
380 if (txin.prevout.n < prev.vout.size())
381 if (IsMine(prev.vout[txin.prevout.n]))
382 return prev.vout[txin.prevout.n].nValue;
388 bool CWallet::IsChange(const CTxOut& txout) const
390 CBitcoinAddress address;
392 // TODO: fix handling of 'change' outputs. The assumption is that any
393 // payment to a TX_PUBKEYHASH that is mine but isn't in the address book
394 // is change. That assumption is likely to break when we implement multisignature
395 // wallets that return change back into a multi-signature-protected address;
396 // a better way of identifying which outputs are 'the send' and which are
397 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
398 // which output, if any, was change).
399 if (ExtractAddress(txout.scriptPubKey, this, address))
400 CRITICAL_BLOCK(cs_wallet)
401 if (!mapAddressBook.count(address))
406 int64_t CWalletTx::GetTxTime() const
408 return nTimeReceived;
411 int CWalletTx::GetRequestCount() const
413 // Returns -1 if it wasn't being tracked
415 CRITICAL_BLOCK(pwallet->cs_wallet)
422 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
423 if (mi != pwallet->mapRequestCount.end())
424 nRequests = (*mi).second;
429 // Did anyone request this transaction?
430 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
431 if (mi != pwallet->mapRequestCount.end())
433 nRequests = (*mi).second;
435 // How about the block it's in?
436 if (nRequests == 0 && hashBlock != 0)
438 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
439 if (mi != pwallet->mapRequestCount.end())
440 nRequests = (*mi).second;
442 nRequests = 1; // If it's in someone else's block it must have got out
450 void CWalletTx::GetAmounts(int64_t& nGeneratedImmature, int64_t& nGeneratedMature, list<pair<CBitcoinAddress, int64_t> >& listReceived,
451 list<pair<CBitcoinAddress, int64_t> >& listSent, int64_t& nFee, string& strSentAccount) const
453 nGeneratedImmature = nGeneratedMature = nFee = 0;
454 listReceived.clear();
456 strSentAccount = strFromAccount;
460 if (GetBlocksToMaturity() > 0)
461 nGeneratedImmature = pwallet->GetCredit(*this);
463 nGeneratedMature = GetCredit();
468 int64_t nDebit = GetDebit();
469 if (nDebit > 0) // debit>0 means we signed/sent this transaction
471 int64_t nValueOut = GetValueOut();
472 nFee = nDebit - nValueOut;
476 BOOST_FOREACH(const CTxOut& txout, vout)
478 CBitcoinAddress address;
479 vector<unsigned char> vchPubKey;
480 if (!ExtractAddress(txout.scriptPubKey, NULL, address))
482 printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
483 this->GetHash().ToString().c_str());
484 address = " unknown ";
487 // Don't report 'change' txouts
488 if (nDebit > 0 && pwallet->IsChange(txout))
492 listSent.push_back(make_pair(address, txout.nValue));
494 if (pwallet->IsMine(txout))
495 listReceived.push_back(make_pair(address, txout.nValue));
500 void CWalletTx::GetAccountAmounts(const string& strAccount, int64_t& nGenerated, int64_t& nReceived,
501 int64_t& nSent, int64_t& nFee) const
503 nGenerated = nReceived = nSent = nFee = 0;
505 int64_t allGeneratedImmature, allGeneratedMature, allFee;
506 allGeneratedImmature = allGeneratedMature = allFee = 0;
507 string strSentAccount;
508 list<pair<CBitcoinAddress, int64_t> > listReceived;
509 list<pair<CBitcoinAddress, int64_t> > listSent;
510 GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount);
512 if (strAccount == "")
513 nGenerated = allGeneratedMature;
514 if (strAccount == strSentAccount)
516 BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress,int64_t)& s, listSent)
520 CRITICAL_BLOCK(pwallet->cs_wallet)
522 BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress,int64_t)& r, listReceived)
524 if (pwallet->mapAddressBook.count(r.first))
526 map<CBitcoinAddress, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);
527 if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)
528 nReceived += r.second;
530 else if (strAccount.empty())
532 nReceived += r.second;
538 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
542 const int COPY_DEPTH = 3;
543 if (SetMerkleBranch() < COPY_DEPTH)
545 vector<uint256> vWorkQueue;
546 BOOST_FOREACH(const CTxIn& txin, vin)
547 vWorkQueue.push_back(txin.prevout.hash);
549 // This critsect is OK because txdb is already open
550 CRITICAL_BLOCK(pwallet->cs_wallet)
552 map<uint256, const CMerkleTx*> mapWalletPrev;
553 set<uint256> setAlreadyDone;
554 for (int i = 0; i < vWorkQueue.size(); i++)
556 uint256 hash = vWorkQueue[i];
557 if (setAlreadyDone.count(hash))
559 setAlreadyDone.insert(hash);
562 map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
563 if (mi != pwallet->mapWallet.end())
566 BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev)
567 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
569 else if (mapWalletPrev.count(hash))
571 tx = *mapWalletPrev[hash];
573 else if (!fClient && txdb.ReadDiskTx(hash, tx))
579 printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
583 int nDepth = tx.SetMerkleBranch();
584 vtxPrev.push_back(tx);
586 if (nDepth < COPY_DEPTH)
587 BOOST_FOREACH(const CTxIn& txin, tx.vin)
588 vWorkQueue.push_back(txin.prevout.hash);
593 reverse(vtxPrev.begin(), vtxPrev.end());
596 bool CWalletTx::WriteToDisk()
598 return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
601 // Scan the block chain (starting in pindexStart) for transactions
602 // from or to us. If fUpdate is true, found transactions that already
603 // exist in the wallet will be updated.
604 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
608 CBlockIndex* pindex = pindexStart;
609 CRITICAL_BLOCK(cs_wallet)
614 block.ReadFromDisk(pindex, true);
615 BOOST_FOREACH(CTransaction& tx, block.vtx)
617 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
620 pindex = pindex->pnext;
626 int CWallet::ScanForWalletTransaction(const uint256& hashTx)
629 tx.ReadFromDisk(COutPoint(hashTx, 0));
630 if (AddToWalletIfInvolvingMe(tx, NULL, true, true))
635 void CWallet::ReacceptWalletTransactions()
639 while (fRepeat) CRITICAL_BLOCK(cs_wallet)
642 vector<CDiskTxPos> vMissingTx;
643 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
645 CWalletTx& wtx = item.second;
646 if (wtx.IsCoinBase() && wtx.IsSpent(0))
650 bool fUpdated = false;
651 if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
653 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
654 if (txindex.vSpent.size() != wtx.vout.size())
656 printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %d != wtx.vout.size() %d\n", txindex.vSpent.size(), wtx.vout.size());
659 for (int i = 0; i < txindex.vSpent.size(); i++)
663 if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i]))
667 vMissingTx.push_back(txindex.vSpent[i]);
672 printf("ReacceptWalletTransactions found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
679 // Reaccept any txes of ours that aren't already in a block
680 if (!wtx.IsCoinBase())
681 wtx.AcceptWalletTransaction(txdb, false);
684 if (!vMissingTx.empty())
686 // TODO: optimize this to scan just part of the block chain?
687 if (ScanForWalletTransactions(pindexGenesisBlock))
688 fRepeat = true; // Found missing transactions: re-do Reaccept.
693 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
695 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
697 if (!tx.IsCoinBase())
699 uint256 hash = tx.GetHash();
700 if (!txdb.ContainsTx(hash))
701 RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx);
706 uint256 hash = GetHash();
707 if (!txdb.ContainsTx(hash))
709 printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
710 RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this);
715 void CWalletTx::RelayWalletTransaction()
718 RelayWalletTransaction(txdb);
721 void CWallet::ResendWalletTransactions()
723 // Do this infrequently and randomly to avoid giving away
724 // that these are our transactions.
725 static int64_t nNextTime;
726 if (GetTime() < nNextTime)
728 bool fFirst = (nNextTime == 0);
729 nNextTime = GetTime() + GetRand(30 * 60);
733 // Only do it if there's been a new block since last time
734 static int64_t nLastTime;
735 if (nTimeBestReceived < nLastTime)
737 nLastTime = GetTime();
739 // Rebroadcast any of our txes that aren't in a block yet
740 printf("ResendWalletTransactions()\n");
742 CRITICAL_BLOCK(cs_wallet)
744 // Sort them in chronological order
745 multimap<unsigned int, CWalletTx*> mapSorted;
746 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
748 CWalletTx& wtx = item.second;
749 // Don't rebroadcast until it's had plenty of time that
750 // it should have gotten in already by now.
751 if (nTimeBestReceived - (int64_t)wtx.nTimeReceived > 5 * 60)
752 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
754 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
756 CWalletTx& wtx = *item.second;
757 wtx.RelayWalletTransaction(txdb);
767 //////////////////////////////////////////////////////////////////////////////
773 int64_t CWallet::GetBalance() const
776 CRITICAL_BLOCK(cs_wallet)
778 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
780 const CWalletTx* pcoin = &(*it).second;
781 if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
783 nTotal += pcoin->GetAvailableCredit();
790 int64_t CWallet::GetUnconfirmedBalance() const
793 CRITICAL_BLOCK(cs_wallet)
795 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
797 const CWalletTx* pcoin = &(*it).second;
798 if (pcoin->IsFinal() && pcoin->IsConfirmed())
800 nTotal += pcoin->GetAvailableCredit();
806 bool CWallet::SelectCoinsMinConf(int64_t nTargetValue, int nConfMine, int nConfTheirs, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64_t& nValueRet) const
811 // List of values less than target
812 pair<int64_t, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
813 coinLowestLarger.first = std::numeric_limits<int64_t>::max();
814 coinLowestLarger.second.first = NULL;
815 vector<pair<int64_t, pair<const CWalletTx*,unsigned int> > > vValue;
816 int64_t nTotalLower = 0;
818 CRITICAL_BLOCK(cs_wallet)
820 vector<const CWalletTx*> vCoins;
821 vCoins.reserve(mapWallet.size());
822 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
823 vCoins.push_back(&(*it).second);
824 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
826 BOOST_FOREACH(const CWalletTx* pcoin, vCoins)
828 if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
831 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
834 int nDepth = pcoin->GetDepthInMainChain();
835 if (nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs))
838 for (int i = 0; i < pcoin->vout.size(); i++)
840 if (pcoin->IsSpent(i) || !IsMine(pcoin->vout[i]))
843 int64_t n = pcoin->vout[i].nValue;
848 pair<int64_t,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin,i));
850 if (n == nTargetValue)
852 setCoinsRet.insert(coin.second);
853 nValueRet += coin.first;
856 else if (n < nTargetValue + CENT)
858 vValue.push_back(coin);
861 else if (n < coinLowestLarger.first)
863 coinLowestLarger = coin;
869 if (nTotalLower == nTargetValue || nTotalLower == nTargetValue + CENT)
871 for (int i = 0; i < vValue.size(); ++i)
873 setCoinsRet.insert(vValue[i].second);
874 nValueRet += vValue[i].first;
879 if (nTotalLower < nTargetValue + (coinLowestLarger.second.first ? CENT : 0))
881 if (coinLowestLarger.second.first == NULL)
883 setCoinsRet.insert(coinLowestLarger.second);
884 nValueRet += coinLowestLarger.first;
888 if (nTotalLower >= nTargetValue + CENT)
889 nTargetValue += CENT;
891 // Solve subset sum by stochastic approximation
892 sort(vValue.rbegin(), vValue.rend());
893 vector<char> vfIncluded;
894 vector<char> vfBest(vValue.size(), true);
895 int64_t nBest = nTotalLower;
897 for (int nRep = 0; nRep < 1000 && nBest != nTargetValue; nRep++)
899 vfIncluded.assign(vValue.size(), false);
901 bool fReachedTarget = false;
902 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
904 for (int i = 0; i < vValue.size(); i++)
906 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
908 nTotal += vValue[i].first;
909 vfIncluded[i] = true;
910 if (nTotal >= nTargetValue)
912 fReachedTarget = true;
918 nTotal -= vValue[i].first;
919 vfIncluded[i] = false;
926 // If the next larger is still closer, return it
927 if (coinLowestLarger.second.first && coinLowestLarger.first - nTargetValue <= nBest - nTargetValue)
929 setCoinsRet.insert(coinLowestLarger.second);
930 nValueRet += coinLowestLarger.first;
933 for (int i = 0; i < vValue.size(); i++)
936 setCoinsRet.insert(vValue[i].second);
937 nValueRet += vValue[i].first;
941 printf("SelectCoins() best subset: ");
942 for (int i = 0; i < vValue.size(); i++)
944 printf("%s ", FormatMoney(vValue[i].first).c_str());
945 printf("total %s\n", FormatMoney(nBest).c_str());
951 bool CWallet::SelectCoins(int64_t nTargetValue, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64_t& nValueRet) const
953 return (SelectCoinsMinConf(nTargetValue, 1, 6, setCoinsRet, nValueRet) ||
954 SelectCoinsMinConf(nTargetValue, 1, 1, setCoinsRet, nValueRet) ||
955 SelectCoinsMinConf(nTargetValue, 0, 1, setCoinsRet, nValueRet));
961 bool CWallet::CreateTransaction(const vector<pair<CScript, int64_t> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet)
964 BOOST_FOREACH (const PAIRTYPE(CScript, int64_t)& s, vecSend)
970 if (vecSend.empty() || nValue < 0)
973 wtxNew.BindWallet(this);
975 CRITICAL_BLOCK(cs_main)
976 CRITICAL_BLOCK(cs_wallet)
978 // txdb must be opened before the mapWallet lock
981 nFeeRet = nTransactionFee;
986 wtxNew.fFromMe = true;
988 int64_t nTotalValue = nValue + nFeeRet;
989 double dPriority = 0;
990 // vouts to the payees
991 BOOST_FOREACH (const PAIRTYPE(CScript, int64_t)& s, vecSend)
992 wtxNew.vout.push_back(CTxOut(s.second, s.first));
994 // Choose coins to use
995 set<pair<const CWalletTx*,unsigned int> > setCoins;
996 int64_t nValueIn = 0;
997 if (!SelectCoins(nTotalValue, setCoins, nValueIn))
999 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1001 int64_t nCredit = pcoin.first->vout[pcoin.second].nValue;
1002 dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
1005 int64_t nChange = nValueIn - nValue - nFeeRet;
1006 // if sub-cent change is required, the fee must be raised to at least MIN_TX_FEE
1007 // or until nChange becomes zero
1008 // NOTE: this depends on the exact behaviour of GetMinFee
1009 if (nFeeRet < MIN_TX_FEE && nChange > 0 && nChange < CENT)
1011 int64_t nMoveToFee = min(nChange, MIN_TX_FEE - nFeeRet);
1012 nChange -= nMoveToFee;
1013 nFeeRet += nMoveToFee;
1018 // Note: We use a new key here to keep it from being obvious which side is the change.
1019 // The drawback is that by not reusing a previous key, the change may be lost if a
1020 // backup is restored, if the backup doesn't have the new private key for the change.
1021 // If we reused the old key, it would be possible to add code to look for and
1022 // rediscover unknown transactions that were written with keys of ours to recover
1023 // post-backup change.
1025 // Reserve a new key pair from key pool
1026 vector<unsigned char> vchPubKey = reservekey.GetReservedKey();
1027 // assert(mapKeys.count(vchPubKey));
1029 // Fill a vout to ourself
1030 // TODO: pass in scriptChange instead of reservekey so
1031 // change transaction isn't always pay-to-bitcoin-address
1032 CScript scriptChange;
1033 scriptChange.SetBitcoinAddress(vchPubKey);
1035 // Insert change txn at random position:
1036 vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
1037 wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
1040 reservekey.ReturnKey();
1043 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1044 wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
1048 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1049 if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
1053 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK);
1054 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1056 dPriority /= nBytes;
1058 // Check that enough fee is included
1059 int64_t nPayFee = nTransactionFee * (1 + (int64_t)nBytes / 1000);
1060 bool fAllowFree = CTransaction::AllowFree(dPriority);
1061 int64_t nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND);
1062 if (nFeeRet < max(nPayFee, nMinFee))
1064 nFeeRet = max(nPayFee, nMinFee);
1068 // Fill vtxPrev by copying from previous transactions vtxPrev
1069 wtxNew.AddSupportingTransactions(txdb);
1070 wtxNew.fTimeReceivedIsTxTime = true;
1079 bool CWallet::CreateTransaction(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet)
1081 vector< pair<CScript, int64_t> > vecSend;
1082 vecSend.push_back(make_pair(scriptPubKey, nValue));
1083 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet);
1086 // Call after CreateTransaction unless you want to abort
1087 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
1089 CRITICAL_BLOCK(cs_main)
1090 CRITICAL_BLOCK(cs_wallet)
1092 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
1094 // This is only to keep the database open to defeat the auto-flush for the
1095 // duration of this scope. This is the only place where this optimization
1096 // maybe makes sense; please don't do it anywhere else.
1097 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
1099 // Take key pair from key pool so it won't be used again
1100 reservekey.KeepKey();
1102 // Add tx to wallet, because if it has change it's also ours,
1103 // otherwise just for transaction history.
1104 AddToWallet(wtxNew);
1106 // Mark old coins as spent
1107 set<CWalletTx*> setCoins;
1108 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
1110 CWalletTx &coin = mapWallet[txin.prevout.hash];
1111 coin.BindWallet(this);
1112 coin.MarkSpent(txin.prevout.n);
1114 vWalletUpdated.push_back(coin.GetHash());
1121 // Track how many getdata requests our transaction gets
1122 mapRequestCount[wtxNew.GetHash()] = 0;
1125 if (!wtxNew.AcceptToMemoryPool())
1127 // This must not fail. The transaction has already been signed and recorded.
1128 printf("CommitTransaction() : Error: Transaction not valid");
1131 wtxNew.RelayWalletTransaction();
1140 string CWallet::SendMoney(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, bool fAskFee)
1142 CReserveKey reservekey(this);
1143 int64_t nFeeRequired;
1147 string strError = _("Error: Wallet locked, unable to create transaction ");
1148 printf("SendMoney() : %s", strError.c_str());
1151 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
1154 if (nValue + nFeeRequired > GetBalance())
1155 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());
1157 strError = _("Error: Transaction creation failed ");
1158 printf("SendMoney() : %s", strError.c_str());
1162 if (fAskFee && !ThreadSafeAskFee(nFeeRequired, _("Sending..."), NULL))
1165 if (!CommitTransaction(wtxNew, reservekey))
1166 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.");
1174 string CWallet::SendMoneyToBitcoinAddress(const CBitcoinAddress& address, int64_t nValue, CWalletTx& wtxNew, bool fAskFee)
1178 return _("Invalid amount");
1179 if (nValue + nTransactionFee > GetBalance())
1180 return _("Insufficient funds");
1182 // Parse bitcoin address
1183 CScript scriptPubKey;
1184 scriptPubKey.SetBitcoinAddress(address);
1186 return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
1192 int CWallet::LoadWallet(bool& fFirstRunRet)
1196 fFirstRunRet = false;
1197 int nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
1198 if (nLoadWalletRet == DB_NEED_REWRITE)
1200 if (CDB::Rewrite(strWalletFile, "\x04pool"))
1203 // Note: can't top-up keypool here, because wallet is locked.
1204 // User will be prompted to unlock wallet the next operation
1205 // the requires a new key.
1207 nLoadWalletRet = DB_NEED_REWRITE;
1210 if (nLoadWalletRet != DB_LOAD_OK)
1211 return nLoadWalletRet;
1212 fFirstRunRet = vchDefaultKey.empty();
1214 if (!HaveKey(Hash160(vchDefaultKey)))
1216 // Create new keyUser and set as default key
1217 RandAddSeedPerfmon();
1219 std::vector<unsigned char> newDefaultKey;
1220 if (!GetKeyFromPool(newDefaultKey, false))
1221 return DB_LOAD_FAIL;
1222 SetDefaultKey(newDefaultKey);
1223 if (!SetAddressBookName(CBitcoinAddress(vchDefaultKey), ""))
1224 return DB_LOAD_FAIL;
1227 CreateThread(ThreadFlushWalletDB, &strWalletFile);
1232 bool CWallet::SetAddressBookName(const CBitcoinAddress& address, const string& strName)
1234 mapAddressBook[address] = strName;
1237 return CWalletDB(strWalletFile).WriteName(address.ToString(), strName);
1240 bool CWallet::DelAddressBookName(const CBitcoinAddress& address)
1242 mapAddressBook.erase(address);
1245 return CWalletDB(strWalletFile).EraseName(address.ToString());
1249 void CWallet::PrintWallet(const CBlock& block)
1251 CRITICAL_BLOCK(cs_wallet)
1253 if (mapWallet.count(block.vtx[0].GetHash()))
1255 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
1256 printf(" mine: %d %d %d", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
1262 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
1264 CRITICAL_BLOCK(cs_wallet)
1266 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
1267 if (mi != mapWallet.end())
1276 bool CWallet::SetDefaultKey(const std::vector<unsigned char> &vchPubKey)
1280 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
1283 vchDefaultKey = vchPubKey;
1287 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
1289 if (!pwallet->fFileBacked)
1291 strWalletFileOut = pwallet->strWalletFile;
1296 // Mark old keypool keys as used,
1297 // and generate all new keys
1299 bool CWallet::NewKeyPool()
1301 CRITICAL_BLOCK(cs_wallet)
1303 CWalletDB walletdb(strWalletFile);
1304 BOOST_FOREACH(int64_t nIndex, setKeyPool)
1305 walletdb.ErasePool(nIndex);
1311 int64_t nKeys = max(GetArg("-keypool", 100), (int64_t)0);
1312 for (int i = 0; i < nKeys; i++)
1314 int64_t nIndex = i+1;
1315 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
1316 setKeyPool.insert(nIndex);
1318 printf("CWallet::NewKeyPool wrote %"PRI64d" new keys\n", nKeys);
1323 bool CWallet::TopUpKeyPool()
1325 CRITICAL_BLOCK(cs_wallet)
1330 CWalletDB walletdb(strWalletFile);
1333 int64_t nTargetSize = max(GetArg("-keypool", 100), (int64_t)0);
1334 while (setKeyPool.size() < nTargetSize+1)
1337 if (!setKeyPool.empty())
1338 nEnd = *(--setKeyPool.end()) + 1;
1339 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
1340 throw runtime_error("TopUpKeyPool() : writing generated key failed");
1341 setKeyPool.insert(nEnd);
1342 printf("keypool added key %"PRI64d", size=%d\n", nEnd, setKeyPool.size());
1348 void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool)
1351 keypool.vchPubKey.clear();
1352 CRITICAL_BLOCK(cs_wallet)
1357 // Get the oldest key
1358 if(setKeyPool.empty())
1361 CWalletDB walletdb(strWalletFile);
1363 nIndex = *(setKeyPool.begin());
1364 setKeyPool.erase(setKeyPool.begin());
1365 if (!walletdb.ReadPool(nIndex, keypool))
1366 throw runtime_error("ReserveKeyFromKeyPool() : read failed");
1367 if (!HaveKey(Hash160(keypool.vchPubKey)))
1368 throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
1369 assert(!keypool.vchPubKey.empty());
1370 printf("keypool reserve %"PRI64d"\n", nIndex);
1374 int64_t CWallet::AddReserveKey(const CKeyPool& keypool)
1376 CRITICAL_BLOCK(cs_main)
1377 CRITICAL_BLOCK(cs_wallet)
1379 CWalletDB walletdb(strWalletFile);
1381 int64_t nIndex = 1 + *(--setKeyPool.end());
1382 if (!walletdb.WritePool(nIndex, keypool))
1383 throw runtime_error("AddReserveKey() : writing added key failed");
1384 setKeyPool.insert(nIndex);
1390 void CWallet::KeepKey(int64_t nIndex)
1392 // Remove from key pool
1395 CWalletDB walletdb(strWalletFile);
1396 walletdb.ErasePool(nIndex);
1398 printf("keypool keep %"PRI64d"\n", nIndex);
1401 void CWallet::ReturnKey(int64_t nIndex)
1403 // Return to key pool
1404 CRITICAL_BLOCK(cs_wallet)
1405 setKeyPool.insert(nIndex);
1406 printf("keypool return %"PRI64d"\n", nIndex);
1409 bool CWallet::GetKeyFromPool(vector<unsigned char>& result, bool fAllowReuse)
1413 CRITICAL_BLOCK(cs_wallet)
1415 ReserveKeyFromKeyPool(nIndex, keypool);
1418 if (fAllowReuse && !vchDefaultKey.empty())
1420 result = vchDefaultKey;
1423 if (IsLocked()) return false;
1424 result = GenerateNewKey();
1428 result = keypool.vchPubKey;
1433 int64_t CWallet::GetOldestKeyPoolTime()
1437 ReserveKeyFromKeyPool(nIndex, keypool);
1441 return keypool.nTime;
1444 vector<unsigned char> CReserveKey::GetReservedKey()
1449 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
1451 vchPubKey = keypool.vchPubKey;
1454 printf("CReserveKey::GetReservedKey(): Warning: using default key instead of a new key, top up your keypool.");
1455 vchPubKey = pwallet->vchDefaultKey;
1458 assert(!vchPubKey.empty());
1462 void CReserveKey::KeepKey()
1465 pwallet->KeepKey(nIndex);
1470 void CReserveKey::ReturnKey()
1473 pwallet->ReturnKey(nIndex);
1478 void CWallet::GetAllReserveAddresses(set<CBitcoinAddress>& setAddress)
1482 CWalletDB walletdb(strWalletFile);
1484 CRITICAL_BLOCK(cs_main)
1485 CRITICAL_BLOCK(cs_wallet)
1486 BOOST_FOREACH(const int64_t& id, setKeyPool)
1489 if (!walletdb.ReadPool(id, keypool))
1490 throw runtime_error("GetAllReserveKeyHashes() : read failed");
1491 CBitcoinAddress address(keypool.vchPubKey);
1492 assert(!keypool.vchPubKey.empty());
1493 if (!HaveKey(address))
1494 throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
1495 setAddress.insert(address);