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.
13 //////////////////////////////////////////////////////////////////////////////
18 std::vector<unsigned char> CWallet::GenerateNewKey()
24 throw std::runtime_error("CWallet::GenerateNewKey() : AddKey failed");
25 return key.GetPubKey();
28 bool CWallet::AddKey(const CKey& key)
30 if (!CCryptoKeyStore::AddKey(key))
35 return CWalletDB(strWalletFile).WriteKey(key.GetPubKey(), key.GetPrivKey());
39 bool CWallet::AddCryptedKey(const vector<unsigned char> &vchPubKey, const vector<unsigned char> &vchCryptedSecret)
41 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
45 CRITICAL_BLOCK(cs_wallet)
47 if (pwalletdbEncryption)
48 return pwalletdbEncryption->WriteCryptedKey(vchPubKey, vchCryptedSecret);
50 return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret);
55 bool CWallet::AddCScript(const CScript& redeemScript)
57 if (!CCryptoKeyStore::AddCScript(redeemScript))
61 return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript);
64 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
70 CKeyingMaterial vMasterKey;
72 CRITICAL_BLOCK(cs_wallet)
73 BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
75 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
77 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
79 if (CCryptoKeyStore::Unlock(vMasterKey))
85 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
87 bool fWasLocked = IsLocked();
89 CRITICAL_BLOCK(cs_wallet)
94 CKeyingMaterial vMasterKey;
95 BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
97 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
99 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
101 if (CCryptoKeyStore::Unlock(vMasterKey))
103 int64 nStartTime = GetTimeMillis();
104 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
105 pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
107 nStartTime = GetTimeMillis();
108 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
109 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
111 if (pMasterKey.second.nDeriveIterations < 25000)
112 pMasterKey.second.nDeriveIterations = 25000;
114 printf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
116 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
118 if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
120 CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
132 // This class implements an addrIncoming entry that causes pre-0.4
133 // clients to crash on startup if reading a private-key-encrypted wallet.
134 class CCorruptAddress
139 if (nType & SER_DISK)
144 bool CWallet::SetMinVersion(int nVersion, CWalletDB* pwalletdbIn)
146 if (nWalletVersion >= nVersion)
149 nWalletVersion = nVersion;
153 CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile);
154 if (nWalletVersion >= 40000)
156 // Versions prior to 0.4.0 did not support the "minversion" record.
157 // Use a CCorruptAddress to make them crash instead.
158 CCorruptAddress corruptAddress;
159 pwalletdb->WriteSetting("addrIncoming", corruptAddress);
161 if (nWalletVersion > 40000)
162 pwalletdb->WriteMinVersion(nWalletVersion);
170 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
175 CKeyingMaterial vMasterKey;
176 RandAddSeedPerfmon();
178 vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
179 RAND_bytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
181 CMasterKey kMasterKey;
183 RandAddSeedPerfmon();
184 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
185 RAND_bytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
188 int64 nStartTime = GetTimeMillis();
189 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
190 kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
192 nStartTime = GetTimeMillis();
193 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
194 kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
196 if (kMasterKey.nDeriveIterations < 25000)
197 kMasterKey.nDeriveIterations = 25000;
199 printf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
201 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
203 if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
206 CRITICAL_BLOCK(cs_wallet)
208 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
211 pwalletdbEncryption = new CWalletDB(strWalletFile);
212 pwalletdbEncryption->TxnBegin();
213 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
216 if (!EncryptKeys(vMasterKey))
219 pwalletdbEncryption->TxnAbort();
220 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.
223 // Encryption was introduced in version 0.4.0
224 SetMinVersion(40000, pwalletdbEncryption);
228 if (!pwalletdbEncryption->TxnCommit())
229 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.
231 pwalletdbEncryption->Close();
232 pwalletdbEncryption = NULL;
236 Unlock(strWalletPassphrase);
240 // Need to completely rewrite the wallet file; if we don't, bdb might keep
241 // bits of the unencrypted private key in slack space in the database file.
242 CDB::Rewrite(strWalletFile);
248 void CWallet::WalletUpdateSpent(const CTransaction &tx)
250 // Anytime a signature is successfully verified, it's proof the outpoint is spent.
251 // Update the wallet spent flag if it doesn't know due to wallet.dat being
252 // restored from backup or the user making copies of wallet.dat.
253 CRITICAL_BLOCK(cs_wallet)
255 BOOST_FOREACH(const CTxIn& txin, tx.vin)
257 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
258 if (mi != mapWallet.end())
260 CWalletTx& wtx = (*mi).second;
261 if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n]))
263 printf("WalletUpdateSpent found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
264 wtx.MarkSpent(txin.prevout.n);
266 vWalletUpdated.push_back(txin.prevout.hash);
273 void CWallet::MarkDirty()
275 CRITICAL_BLOCK(cs_wallet)
277 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
278 item.second.MarkDirty();
282 bool CWallet::AddToWallet(const CWalletTx& wtxIn)
284 uint256 hash = wtxIn.GetHash();
285 CRITICAL_BLOCK(cs_wallet)
287 // Inserts only if not already there, returns tx inserted or tx found
288 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
289 CWalletTx& wtx = (*ret.first).second;
290 wtx.BindWallet(this);
291 bool fInsertedNew = ret.second;
293 wtx.nTimeReceived = GetAdjustedTime();
295 bool fUpdated = false;
299 if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
301 wtx.hashBlock = wtxIn.hashBlock;
304 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
306 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
307 wtx.nIndex = wtxIn.nIndex;
310 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
312 wtx.fFromMe = wtxIn.fFromMe;
315 fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);
319 printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
322 if (fInsertedNew || fUpdated)
323 if (!wtx.WriteToDisk())
326 // If default receiving address gets used, replace it with a new one
327 CScript scriptDefaultKey;
328 scriptDefaultKey.SetBitcoinAddress(vchDefaultKey);
329 BOOST_FOREACH(const CTxOut& txout, wtx.vout)
331 if (txout.scriptPubKey == scriptDefaultKey)
333 std::vector<unsigned char> newDefaultKey;
334 if (GetKeyFromPool(newDefaultKey, false))
336 SetDefaultKey(newDefaultKey);
337 SetAddressBookName(CBitcoinAddress(vchDefaultKey), "");
343 vWalletUpdated.push_back(hash);
345 // since AddToWallet is called directly for self-originating transactions, check for consumption of own coins
346 WalletUpdateSpent(wtx);
354 // Add a transaction to the wallet, or update it.
355 // pblock is optional, but should be provided if the transaction is known to be in a block.
356 // If fUpdate is true, existing transactions will be updated.
357 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fFindBlock)
359 uint256 hash = tx.GetHash();
360 CRITICAL_BLOCK(cs_wallet)
362 bool fExisted = mapWallet.count(hash);
363 if (fExisted && !fUpdate) return false;
364 if (fExisted || IsMine(tx) || IsFromMe(tx))
366 CWalletTx wtx(this,tx);
367 // Get merkle branch if transaction was found in a block
369 wtx.SetMerkleBranch(pblock);
370 return AddToWallet(wtx);
373 WalletUpdateSpent(tx);
378 bool CWallet::EraseFromWallet(uint256 hash)
382 CRITICAL_BLOCK(cs_wallet)
384 if (mapWallet.erase(hash))
385 CWalletDB(strWalletFile).EraseTx(hash);
391 bool CWallet::IsMine(const CTxIn &txin) const
393 CRITICAL_BLOCK(cs_wallet)
395 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
396 if (mi != mapWallet.end())
398 const CWalletTx& prev = (*mi).second;
399 if (txin.prevout.n < prev.vout.size())
400 if (IsMine(prev.vout[txin.prevout.n]))
407 int64 CWallet::GetDebit(const CTxIn &txin) const
409 CRITICAL_BLOCK(cs_wallet)
411 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
412 if (mi != mapWallet.end())
414 const CWalletTx& prev = (*mi).second;
415 if (txin.prevout.n < prev.vout.size())
416 if (IsMine(prev.vout[txin.prevout.n]))
417 return prev.vout[txin.prevout.n].nValue;
423 bool CWallet::IsChange(const CTxOut& txout) const
425 CBitcoinAddress address;
427 // TODO: fix handling of 'change' outputs. The assumption is that any
428 // payment to a TX_PUBKEYHASH that is mine but isn't in the address book
429 // is change. That assumption is likely to break when we implement multisignature
430 // wallets that return change back into a multi-signature-protected address;
431 // a better way of identifying which outputs are 'the send' and which are
432 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
433 // which output, if any, was change).
434 if (ExtractAddress(txout.scriptPubKey, address) && HaveKey(address))
435 CRITICAL_BLOCK(cs_wallet)
436 if (!mapAddressBook.count(address))
441 int64 CWalletTx::GetTxTime() const
443 return nTimeReceived;
446 int CWalletTx::GetRequestCount() const
448 // Returns -1 if it wasn't being tracked
450 CRITICAL_BLOCK(pwallet->cs_wallet)
457 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
458 if (mi != pwallet->mapRequestCount.end())
459 nRequests = (*mi).second;
464 // Did anyone request this transaction?
465 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
466 if (mi != pwallet->mapRequestCount.end())
468 nRequests = (*mi).second;
470 // How about the block it's in?
471 if (nRequests == 0 && hashBlock != 0)
473 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
474 if (mi != pwallet->mapRequestCount.end())
475 nRequests = (*mi).second;
477 nRequests = 1; // If it's in someone else's block it must have got out
485 void CWalletTx::GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, list<pair<CBitcoinAddress, int64> >& listReceived,
486 list<pair<CBitcoinAddress, int64> >& listSent, int64& nFee, string& strSentAccount) const
488 nGeneratedImmature = nGeneratedMature = nFee = 0;
489 listReceived.clear();
491 strSentAccount = strFromAccount;
495 if (GetBlocksToMaturity() > 0)
496 nGeneratedImmature = pwallet->GetCredit(*this);
498 nGeneratedMature = GetCredit();
503 int64 nDebit = GetDebit();
504 if (nDebit > 0) // debit>0 means we signed/sent this transaction
506 int64 nValueOut = GetValueOut();
507 nFee = nDebit - nValueOut;
511 BOOST_FOREACH(const CTxOut& txout, vout)
513 CBitcoinAddress address;
514 vector<unsigned char> vchPubKey;
515 if (!ExtractAddress(txout.scriptPubKey, address))
517 printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
518 this->GetHash().ToString().c_str());
519 address = " unknown ";
522 // Don't report 'change' txouts
523 if (nDebit > 0 && pwallet->IsChange(txout))
527 listSent.push_back(make_pair(address, txout.nValue));
529 if (pwallet->IsMine(txout))
530 listReceived.push_back(make_pair(address, txout.nValue));
535 void CWalletTx::GetAccountAmounts(const string& strAccount, int64& nGenerated, int64& nReceived,
536 int64& nSent, int64& nFee) const
538 nGenerated = nReceived = nSent = nFee = 0;
540 int64 allGeneratedImmature, allGeneratedMature, allFee;
541 allGeneratedImmature = allGeneratedMature = allFee = 0;
542 string strSentAccount;
543 list<pair<CBitcoinAddress, int64> > listReceived;
544 list<pair<CBitcoinAddress, int64> > listSent;
545 GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount);
547 if (strAccount == "")
548 nGenerated = allGeneratedMature;
549 if (strAccount == strSentAccount)
551 BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress,int64)& s, listSent)
555 CRITICAL_BLOCK(pwallet->cs_wallet)
557 BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress,int64)& r, listReceived)
559 if (pwallet->mapAddressBook.count(r.first))
561 map<CBitcoinAddress, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);
562 if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)
563 nReceived += r.second;
565 else if (strAccount.empty())
567 nReceived += r.second;
573 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
577 const int COPY_DEPTH = 3;
578 if (SetMerkleBranch() < COPY_DEPTH)
580 vector<uint256> vWorkQueue;
581 BOOST_FOREACH(const CTxIn& txin, vin)
582 vWorkQueue.push_back(txin.prevout.hash);
584 // This critsect is OK because txdb is already open
585 CRITICAL_BLOCK(pwallet->cs_wallet)
587 map<uint256, const CMerkleTx*> mapWalletPrev;
588 set<uint256> setAlreadyDone;
589 for (int i = 0; i < vWorkQueue.size(); i++)
591 uint256 hash = vWorkQueue[i];
592 if (setAlreadyDone.count(hash))
594 setAlreadyDone.insert(hash);
597 map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
598 if (mi != pwallet->mapWallet.end())
601 BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev)
602 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
604 else if (mapWalletPrev.count(hash))
606 tx = *mapWalletPrev[hash];
608 else if (!fClient && txdb.ReadDiskTx(hash, tx))
614 printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
618 int nDepth = tx.SetMerkleBranch();
619 vtxPrev.push_back(tx);
621 if (nDepth < COPY_DEPTH)
622 BOOST_FOREACH(const CTxIn& txin, tx.vin)
623 vWorkQueue.push_back(txin.prevout.hash);
628 reverse(vtxPrev.begin(), vtxPrev.end());
631 bool CWalletTx::WriteToDisk()
633 return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
636 // Scan the block chain (starting in pindexStart) for transactions
637 // from or to us. If fUpdate is true, found transactions that already
638 // exist in the wallet will be updated.
639 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
643 CBlockIndex* pindex = pindexStart;
644 CRITICAL_BLOCK(cs_wallet)
649 block.ReadFromDisk(pindex, true);
650 BOOST_FOREACH(CTransaction& tx, block.vtx)
652 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
655 pindex = pindex->pnext;
661 int CWallet::ScanForWalletTransaction(const uint256& hashTx)
664 tx.ReadFromDisk(COutPoint(hashTx, 0));
665 if (AddToWalletIfInvolvingMe(tx, NULL, true, true))
670 void CWallet::ReacceptWalletTransactions()
674 while (fRepeat) CRITICAL_BLOCK(cs_wallet)
677 vector<CDiskTxPos> vMissingTx;
678 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
680 CWalletTx& wtx = item.second;
681 if (wtx.IsCoinBase() && wtx.IsSpent(0))
685 bool fUpdated = false;
686 if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
688 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
689 if (txindex.vSpent.size() != wtx.vout.size())
691 printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %d != wtx.vout.size() %d\n", txindex.vSpent.size(), wtx.vout.size());
694 for (int i = 0; i < txindex.vSpent.size(); i++)
698 if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i]))
702 vMissingTx.push_back(txindex.vSpent[i]);
707 printf("ReacceptWalletTransactions found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
714 // Reaccept any txes of ours that aren't already in a block
715 if (!wtx.IsCoinBase())
716 wtx.AcceptWalletTransaction(txdb, false);
719 if (!vMissingTx.empty())
721 // TODO: optimize this to scan just part of the block chain?
722 if (ScanForWalletTransactions(pindexGenesisBlock))
723 fRepeat = true; // Found missing transactions: re-do Reaccept.
728 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
730 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
732 if (!tx.IsCoinBase())
734 uint256 hash = tx.GetHash();
735 if (!txdb.ContainsTx(hash))
736 RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx);
741 uint256 hash = GetHash();
742 if (!txdb.ContainsTx(hash))
744 printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
745 RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this);
750 void CWalletTx::RelayWalletTransaction()
753 RelayWalletTransaction(txdb);
756 void CWallet::ResendWalletTransactions()
758 // Do this infrequently and randomly to avoid giving away
759 // that these are our transactions.
760 static int64 nNextTime;
761 if (GetTime() < nNextTime)
763 bool fFirst = (nNextTime == 0);
764 nNextTime = GetTime() + GetRand(30 * 60);
768 // Only do it if there's been a new block since last time
769 static int64 nLastTime;
770 if (nTimeBestReceived < nLastTime)
772 nLastTime = GetTime();
774 // Rebroadcast any of our txes that aren't in a block yet
775 printf("ResendWalletTransactions()\n");
777 CRITICAL_BLOCK(cs_wallet)
779 // Sort them in chronological order
780 multimap<unsigned int, CWalletTx*> mapSorted;
781 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
783 CWalletTx& wtx = item.second;
784 // Don't rebroadcast until it's had plenty of time that
785 // it should have gotten in already by now.
786 if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
787 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
789 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
791 CWalletTx& wtx = *item.second;
792 wtx.RelayWalletTransaction(txdb);
802 //////////////////////////////////////////////////////////////////////////////
808 int64 CWallet::GetBalance() const
811 CRITICAL_BLOCK(cs_wallet)
813 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
815 const CWalletTx* pcoin = &(*it).second;
816 if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
818 nTotal += pcoin->GetAvailableCredit();
825 int64 CWallet::GetUnconfirmedBalance() const
828 CRITICAL_BLOCK(cs_wallet)
830 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
832 const CWalletTx* pcoin = &(*it).second;
833 if (pcoin->IsFinal() && pcoin->IsConfirmed())
835 nTotal += pcoin->GetAvailableCredit();
841 bool CWallet::SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
846 // List of values less than target
847 pair<int64, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
848 coinLowestLarger.first = std::numeric_limits<int64>::max();
849 coinLowestLarger.second.first = NULL;
850 vector<pair<int64, pair<const CWalletTx*,unsigned int> > > vValue;
851 int64 nTotalLower = 0;
853 CRITICAL_BLOCK(cs_wallet)
855 vector<const CWalletTx*> vCoins;
856 vCoins.reserve(mapWallet.size());
857 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
858 vCoins.push_back(&(*it).second);
859 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
861 BOOST_FOREACH(const CWalletTx* pcoin, vCoins)
863 if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
866 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
869 int nDepth = pcoin->GetDepthInMainChain();
870 if (nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs))
873 for (int i = 0; i < pcoin->vout.size(); i++)
875 if (pcoin->IsSpent(i) || !IsMine(pcoin->vout[i]))
878 int64 n = pcoin->vout[i].nValue;
883 pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin,i));
885 if (n == nTargetValue)
887 setCoinsRet.insert(coin.second);
888 nValueRet += coin.first;
891 else if (n < nTargetValue + CENT)
893 vValue.push_back(coin);
896 else if (n < coinLowestLarger.first)
898 coinLowestLarger = coin;
904 if (nTotalLower == nTargetValue || nTotalLower == nTargetValue + CENT)
906 for (int i = 0; i < vValue.size(); ++i)
908 setCoinsRet.insert(vValue[i].second);
909 nValueRet += vValue[i].first;
914 if (nTotalLower < nTargetValue + (coinLowestLarger.second.first ? CENT : 0))
916 if (coinLowestLarger.second.first == NULL)
918 setCoinsRet.insert(coinLowestLarger.second);
919 nValueRet += coinLowestLarger.first;
923 if (nTotalLower >= nTargetValue + CENT)
924 nTargetValue += CENT;
926 // Solve subset sum by stochastic approximation
927 sort(vValue.rbegin(), vValue.rend());
928 vector<char> vfIncluded;
929 vector<char> vfBest(vValue.size(), true);
930 int64 nBest = nTotalLower;
932 for (int nRep = 0; nRep < 1000 && nBest != nTargetValue; nRep++)
934 vfIncluded.assign(vValue.size(), false);
936 bool fReachedTarget = false;
937 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
939 for (int i = 0; i < vValue.size(); i++)
941 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
943 nTotal += vValue[i].first;
944 vfIncluded[i] = true;
945 if (nTotal >= nTargetValue)
947 fReachedTarget = true;
953 nTotal -= vValue[i].first;
954 vfIncluded[i] = false;
961 // If the next larger is still closer, return it
962 if (coinLowestLarger.second.first && coinLowestLarger.first - nTargetValue <= nBest - nTargetValue)
964 setCoinsRet.insert(coinLowestLarger.second);
965 nValueRet += coinLowestLarger.first;
968 for (int i = 0; i < vValue.size(); i++)
971 setCoinsRet.insert(vValue[i].second);
972 nValueRet += vValue[i].first;
976 printf("SelectCoins() best subset: ");
977 for (int i = 0; i < vValue.size(); i++)
979 printf("%s ", FormatMoney(vValue[i].first).c_str());
980 printf("total %s\n", FormatMoney(nBest).c_str());
986 bool CWallet::SelectCoins(int64 nTargetValue, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
988 return (SelectCoinsMinConf(nTargetValue, 1, 6, setCoinsRet, nValueRet) ||
989 SelectCoinsMinConf(nTargetValue, 1, 1, setCoinsRet, nValueRet) ||
990 SelectCoinsMinConf(nTargetValue, 0, 1, setCoinsRet, nValueRet));
996 bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
999 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1005 if (vecSend.empty() || nValue < 0)
1008 wtxNew.BindWallet(this);
1010 CRITICAL_BLOCK(cs_main)
1011 CRITICAL_BLOCK(cs_wallet)
1013 // txdb must be opened before the mapWallet lock
1016 nFeeRet = nTransactionFee;
1020 wtxNew.vout.clear();
1021 wtxNew.fFromMe = true;
1023 int64 nTotalValue = nValue + nFeeRet;
1024 double dPriority = 0;
1025 // vouts to the payees
1026 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1027 wtxNew.vout.push_back(CTxOut(s.second, s.first));
1029 // Choose coins to use
1030 set<pair<const CWalletTx*,unsigned int> > setCoins;
1032 if (!SelectCoins(nTotalValue, setCoins, nValueIn))
1034 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1036 int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
1037 dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
1040 int64 nChange = nValueIn - nValue - nFeeRet;
1041 // if sub-cent change is required, the fee must be raised to at least MIN_TX_FEE
1042 // or until nChange becomes zero
1043 // NOTE: this depends on the exact behaviour of GetMinFee
1044 if (nFeeRet < MIN_TX_FEE && nChange > 0 && nChange < CENT)
1046 int64 nMoveToFee = min(nChange, MIN_TX_FEE - nFeeRet);
1047 nChange -= nMoveToFee;
1048 nFeeRet += nMoveToFee;
1053 // Note: We use a new key here to keep it from being obvious which side is the change.
1054 // The drawback is that by not reusing a previous key, the change may be lost if a
1055 // backup is restored, if the backup doesn't have the new private key for the change.
1056 // If we reused the old key, it would be possible to add code to look for and
1057 // rediscover unknown transactions that were written with keys of ours to recover
1058 // post-backup change.
1060 // Reserve a new key pair from key pool
1061 vector<unsigned char> vchPubKey = reservekey.GetReservedKey();
1062 // assert(mapKeys.count(vchPubKey));
1064 // Fill a vout to ourself
1065 // TODO: pass in scriptChange instead of reservekey so
1066 // change transaction isn't always pay-to-bitcoin-address
1067 CScript scriptChange;
1068 scriptChange.SetBitcoinAddress(vchPubKey);
1070 // Insert change txn at random position:
1071 vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
1072 wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
1075 reservekey.ReturnKey();
1078 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1079 wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
1083 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1084 if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
1088 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK);
1089 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1091 dPriority /= nBytes;
1093 // Check that enough fee is included
1094 int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
1095 bool fAllowFree = CTransaction::AllowFree(dPriority);
1096 int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND);
1097 if (nFeeRet < max(nPayFee, nMinFee))
1099 nFeeRet = max(nPayFee, nMinFee);
1103 // Fill vtxPrev by copying from previous transactions vtxPrev
1104 wtxNew.AddSupportingTransactions(txdb);
1105 wtxNew.fTimeReceivedIsTxTime = true;
1114 bool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
1116 vector< pair<CScript, int64> > vecSend;
1117 vecSend.push_back(make_pair(scriptPubKey, nValue));
1118 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet);
1121 // Call after CreateTransaction unless you want to abort
1122 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
1124 CRITICAL_BLOCK(cs_main)
1125 CRITICAL_BLOCK(cs_wallet)
1127 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
1129 // This is only to keep the database open to defeat the auto-flush for the
1130 // duration of this scope. This is the only place where this optimization
1131 // maybe makes sense; please don't do it anywhere else.
1132 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
1134 // Take key pair from key pool so it won't be used again
1135 reservekey.KeepKey();
1137 // Add tx to wallet, because if it has change it's also ours,
1138 // otherwise just for transaction history.
1139 AddToWallet(wtxNew);
1141 // Mark old coins as spent
1142 set<CWalletTx*> setCoins;
1143 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
1145 CWalletTx &coin = mapWallet[txin.prevout.hash];
1146 coin.BindWallet(this);
1147 coin.MarkSpent(txin.prevout.n);
1149 vWalletUpdated.push_back(coin.GetHash());
1156 // Track how many getdata requests our transaction gets
1157 mapRequestCount[wtxNew.GetHash()] = 0;
1160 if (!wtxNew.AcceptToMemoryPool())
1162 // This must not fail. The transaction has already been signed and recorded.
1163 printf("CommitTransaction() : Error: Transaction not valid");
1166 wtxNew.RelayWalletTransaction();
1175 string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1177 CReserveKey reservekey(this);
1182 string strError = _("Error: Wallet locked, unable to create transaction ");
1183 printf("SendMoney() : %s", strError.c_str());
1186 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
1189 if (nValue + nFeeRequired > GetBalance())
1190 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());
1192 strError = _("Error: Transaction creation failed ");
1193 printf("SendMoney() : %s", strError.c_str());
1197 if (fAskFee && !ThreadSafeAskFee(nFeeRequired, _("Sending..."), NULL))
1200 if (!CommitTransaction(wtxNew, reservekey))
1201 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.");
1209 string CWallet::SendMoneyToBitcoinAddress(const CBitcoinAddress& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1213 return _("Invalid amount");
1214 if (nValue + nTransactionFee > GetBalance())
1215 return _("Insufficient funds");
1217 // Parse bitcoin address
1218 CScript scriptPubKey;
1219 scriptPubKey.SetBitcoinAddress(address);
1221 return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
1227 int CWallet::LoadWallet(bool& fFirstRunRet)
1231 fFirstRunRet = false;
1232 int nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
1233 if (nLoadWalletRet == DB_NEED_REWRITE)
1235 if (CDB::Rewrite(strWalletFile, "\x04pool"))
1238 // Note: can't top-up keypool here, because wallet is locked.
1239 // User will be prompted to unlock wallet the next operation
1240 // the requires a new key.
1242 nLoadWalletRet = DB_NEED_REWRITE;
1245 if (nLoadWalletRet != DB_LOAD_OK)
1246 return nLoadWalletRet;
1247 fFirstRunRet = vchDefaultKey.empty();
1249 if (!HaveKey(Hash160(vchDefaultKey)))
1251 // Create new keyUser and set as default key
1252 RandAddSeedPerfmon();
1254 std::vector<unsigned char> newDefaultKey;
1255 if (!GetKeyFromPool(newDefaultKey, false))
1256 return DB_LOAD_FAIL;
1257 SetDefaultKey(newDefaultKey);
1258 if (!SetAddressBookName(CBitcoinAddress(vchDefaultKey), ""))
1259 return DB_LOAD_FAIL;
1262 CreateThread(ThreadFlushWalletDB, &strWalletFile);
1267 bool CWallet::SetAddressBookName(const CBitcoinAddress& address, const string& strName)
1269 mapAddressBook[address] = strName;
1272 return CWalletDB(strWalletFile).WriteName(address.ToString(), strName);
1275 bool CWallet::DelAddressBookName(const CBitcoinAddress& address)
1277 mapAddressBook.erase(address);
1280 return CWalletDB(strWalletFile).EraseName(address.ToString());
1284 void CWallet::PrintWallet(const CBlock& block)
1286 CRITICAL_BLOCK(cs_wallet)
1288 if (mapWallet.count(block.vtx[0].GetHash()))
1290 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
1291 printf(" mine: %d %d %d", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
1297 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
1299 CRITICAL_BLOCK(cs_wallet)
1301 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
1302 if (mi != mapWallet.end())
1311 bool CWallet::SetDefaultKey(const std::vector<unsigned char> &vchPubKey)
1315 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
1318 vchDefaultKey = vchPubKey;
1322 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
1324 if (!pwallet->fFileBacked)
1326 strWalletFileOut = pwallet->strWalletFile;
1331 // Mark old keypool keys as used,
1332 // and generate all new keys
1334 bool CWallet::NewKeyPool()
1336 CRITICAL_BLOCK(cs_wallet)
1338 CWalletDB walletdb(strWalletFile);
1339 BOOST_FOREACH(int64 nIndex, setKeyPool)
1340 walletdb.ErasePool(nIndex);
1346 int64 nKeys = max(GetArg("-keypool", 100), (int64)0);
1347 for (int i = 0; i < nKeys; i++)
1350 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
1351 setKeyPool.insert(nIndex);
1353 printf("CWallet::NewKeyPool wrote %"PRI64d" new keys\n", nKeys);
1358 bool CWallet::TopUpKeyPool()
1360 CRITICAL_BLOCK(cs_wallet)
1365 CWalletDB walletdb(strWalletFile);
1368 int64 nTargetSize = max(GetArg("-keypool", 100), (int64)0);
1369 while (setKeyPool.size() < nTargetSize+1)
1372 if (!setKeyPool.empty())
1373 nEnd = *(--setKeyPool.end()) + 1;
1374 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
1375 throw runtime_error("TopUpKeyPool() : writing generated key failed");
1376 setKeyPool.insert(nEnd);
1377 printf("keypool added key %"PRI64d", size=%d\n", nEnd, setKeyPool.size());
1383 void CWallet::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool)
1386 keypool.vchPubKey.clear();
1387 CRITICAL_BLOCK(cs_wallet)
1392 // Get the oldest key
1393 if(setKeyPool.empty())
1396 CWalletDB walletdb(strWalletFile);
1398 nIndex = *(setKeyPool.begin());
1399 setKeyPool.erase(setKeyPool.begin());
1400 if (!walletdb.ReadPool(nIndex, keypool))
1401 throw runtime_error("ReserveKeyFromKeyPool() : read failed");
1402 if (!HaveKey(Hash160(keypool.vchPubKey)))
1403 throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
1404 assert(!keypool.vchPubKey.empty());
1405 printf("keypool reserve %"PRI64d"\n", nIndex);
1409 int64 CWallet::AddReserveKey(const CKeyPool& keypool)
1411 CRITICAL_BLOCK(cs_main)
1412 CRITICAL_BLOCK(cs_wallet)
1414 CWalletDB walletdb(strWalletFile);
1416 int64 nIndex = 1 + *(--setKeyPool.end());
1417 if (!walletdb.WritePool(nIndex, keypool))
1418 throw runtime_error("AddReserveKey() : writing added key failed");
1419 setKeyPool.insert(nIndex);
1425 void CWallet::KeepKey(int64 nIndex)
1427 // Remove from key pool
1430 CWalletDB walletdb(strWalletFile);
1431 walletdb.ErasePool(nIndex);
1433 printf("keypool keep %"PRI64d"\n", nIndex);
1436 void CWallet::ReturnKey(int64 nIndex)
1438 // Return to key pool
1439 CRITICAL_BLOCK(cs_wallet)
1440 setKeyPool.insert(nIndex);
1441 printf("keypool return %"PRI64d"\n", nIndex);
1444 bool CWallet::GetKeyFromPool(vector<unsigned char>& result, bool fAllowReuse)
1448 CRITICAL_BLOCK(cs_wallet)
1450 ReserveKeyFromKeyPool(nIndex, keypool);
1453 if (fAllowReuse && !vchDefaultKey.empty())
1455 result = vchDefaultKey;
1458 if (IsLocked()) return false;
1459 result = GenerateNewKey();
1463 result = keypool.vchPubKey;
1468 int64 CWallet::GetOldestKeyPoolTime()
1472 ReserveKeyFromKeyPool(nIndex, keypool);
1476 return keypool.nTime;
1479 vector<unsigned char> CReserveKey::GetReservedKey()
1484 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
1486 vchPubKey = keypool.vchPubKey;
1489 printf("CReserveKey::GetReservedKey(): Warning: using default key instead of a new key, top up your keypool.");
1490 vchPubKey = pwallet->vchDefaultKey;
1493 assert(!vchPubKey.empty());
1497 void CReserveKey::KeepKey()
1500 pwallet->KeepKey(nIndex);
1505 void CReserveKey::ReturnKey()
1508 pwallet->ReturnKey(nIndex);
1513 void CWallet::GetAllReserveAddresses(set<CBitcoinAddress>& setAddress)
1517 CWalletDB walletdb(strWalletFile);
1519 CRITICAL_BLOCK(cs_main)
1520 CRITICAL_BLOCK(cs_wallet)
1521 BOOST_FOREACH(const int64& id, setKeyPool)
1524 if (!walletdb.ReadPool(id, keypool))
1525 throw runtime_error("GetAllReserveKeyHashes() : read failed");
1526 CBitcoinAddress address(keypool.vchPubKey);
1527 assert(!keypool.vchPubKey.empty());
1528 if (!HaveKey(address))
1529 throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
1530 setAddress.insert(address);