1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
13 //////////////////////////////////////////////////////////////////////////////
18 std::vector<unsigned char> CWallet::GenerateNewKey()
20 bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
24 key.MakeNewKey(fCompressed);
26 // Compressed public keys were introduced in version 0.6.0
28 SetMinVersion(FEATURE_COMPRPUBKEY);
31 throw std::runtime_error("CWallet::GenerateNewKey() : AddKey failed");
32 return key.GetPubKey();
35 bool CWallet::AddKey(const CKey& key)
37 if (!CCryptoKeyStore::AddKey(key))
42 return CWalletDB(strWalletFile).WriteKey(key.GetPubKey(), key.GetPrivKey());
46 bool CWallet::AddCryptedKey(const vector<unsigned char> &vchPubKey, const vector<unsigned char> &vchCryptedSecret)
48 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
52 CRITICAL_BLOCK(cs_wallet)
54 if (pwalletdbEncryption)
55 return pwalletdbEncryption->WriteCryptedKey(vchPubKey, vchCryptedSecret);
57 return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret);
62 bool CWallet::AddCScript(const CScript& redeemScript)
64 if (!CCryptoKeyStore::AddCScript(redeemScript))
68 return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript);
71 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
77 CKeyingMaterial vMasterKey;
79 CRITICAL_BLOCK(cs_wallet)
80 BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
82 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
84 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
86 if (CCryptoKeyStore::Unlock(vMasterKey))
92 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
94 bool fWasLocked = IsLocked();
96 CRITICAL_BLOCK(cs_wallet)
101 CKeyingMaterial vMasterKey;
102 BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
104 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
106 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
108 if (CCryptoKeyStore::Unlock(vMasterKey))
110 int64 nStartTime = GetTimeMillis();
111 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
112 pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
114 nStartTime = GetTimeMillis();
115 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
116 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
118 if (pMasterKey.second.nDeriveIterations < 25000)
119 pMasterKey.second.nDeriveIterations = 25000;
121 printf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
123 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
125 if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
127 CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
139 // This class implements an addrIncoming entry that causes pre-0.4
140 // clients to crash on startup if reading a private-key-encrypted wallet.
141 class CCorruptAddress
146 if (nType & SER_DISK)
151 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
153 if (nWalletVersion >= nVersion)
156 // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
157 if (fExplicit && nVersion > nWalletMaxVersion)
158 nVersion = FEATURE_LATEST;
160 nWalletVersion = nVersion;
162 if (nVersion > nWalletMaxVersion)
163 nWalletMaxVersion = nVersion;
167 CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile);
168 if (nWalletVersion >= 40000)
170 // Versions prior to 0.4.0 did not support the "minversion" record.
171 // Use a CCorruptAddress to make them crash instead.
172 CCorruptAddress corruptAddress;
173 pwalletdb->WriteSetting("addrIncoming", corruptAddress);
175 if (nWalletVersion > 40000)
176 pwalletdb->WriteMinVersion(nWalletVersion);
184 bool CWallet::SetMaxVersion(int nVersion)
186 // cannot downgrade below current version
187 if (nWalletVersion > nVersion)
190 nWalletMaxVersion = nVersion;
195 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
200 CKeyingMaterial vMasterKey;
201 RandAddSeedPerfmon();
203 vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
204 RAND_bytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
206 CMasterKey kMasterKey;
208 RandAddSeedPerfmon();
209 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
210 RAND_bytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
213 int64 nStartTime = GetTimeMillis();
214 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
215 kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
217 nStartTime = GetTimeMillis();
218 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
219 kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
221 if (kMasterKey.nDeriveIterations < 25000)
222 kMasterKey.nDeriveIterations = 25000;
224 printf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
226 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
228 if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
231 CRITICAL_BLOCK(cs_wallet)
233 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
236 pwalletdbEncryption = new CWalletDB(strWalletFile);
237 if (!pwalletdbEncryption->TxnBegin())
239 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
242 if (!EncryptKeys(vMasterKey))
245 pwalletdbEncryption->TxnAbort();
246 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.
249 // Encryption was introduced in version 0.4.0
250 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
254 if (!pwalletdbEncryption->TxnCommit())
255 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.
257 delete pwalletdbEncryption;
258 pwalletdbEncryption = NULL;
262 Unlock(strWalletPassphrase);
266 // Need to completely rewrite the wallet file; if we don't, bdb might keep
267 // bits of the unencrypted private key in slack space in the database file.
268 CDB::Rewrite(strWalletFile);
274 void CWallet::WalletUpdateSpent(const CTransaction &tx)
276 // Anytime a signature is successfully verified, it's proof the outpoint is spent.
277 // Update the wallet spent flag if it doesn't know due to wallet.dat being
278 // restored from backup or the user making copies of wallet.dat.
279 CRITICAL_BLOCK(cs_wallet)
281 BOOST_FOREACH(const CTxIn& txin, tx.vin)
283 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
284 if (mi != mapWallet.end())
286 CWalletTx& wtx = (*mi).second;
287 if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n]))
289 printf("WalletUpdateSpent found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
290 wtx.MarkSpent(txin.prevout.n);
292 vWalletUpdated.push_back(txin.prevout.hash);
299 void CWallet::MarkDirty()
301 CRITICAL_BLOCK(cs_wallet)
303 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
304 item.second.MarkDirty();
308 bool CWallet::AddToWallet(const CWalletTx& wtxIn)
310 uint256 hash = wtxIn.GetHash();
311 CRITICAL_BLOCK(cs_wallet)
313 // Inserts only if not already there, returns tx inserted or tx found
314 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
315 CWalletTx& wtx = (*ret.first).second;
316 wtx.BindWallet(this);
317 bool fInsertedNew = ret.second;
319 wtx.nTimeReceived = GetAdjustedTime();
321 bool fUpdated = false;
325 if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
327 wtx.hashBlock = wtxIn.hashBlock;
330 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
332 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
333 wtx.nIndex = wtxIn.nIndex;
336 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
338 wtx.fFromMe = wtxIn.fFromMe;
341 fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);
345 printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
348 if (fInsertedNew || fUpdated)
349 if (!wtx.WriteToDisk())
352 // If default receiving address gets used, replace it with a new one
353 CScript scriptDefaultKey;
354 scriptDefaultKey.SetBitcoinAddress(vchDefaultKey);
355 BOOST_FOREACH(const CTxOut& txout, wtx.vout)
357 if (txout.scriptPubKey == scriptDefaultKey)
359 std::vector<unsigned char> newDefaultKey;
360 if (GetKeyFromPool(newDefaultKey, false))
362 SetDefaultKey(newDefaultKey);
363 SetAddressBookName(CBitcoinAddress(vchDefaultKey), "");
369 vWalletUpdated.push_back(hash);
371 // since AddToWallet is called directly for self-originating transactions, check for consumption of own coins
372 WalletUpdateSpent(wtx);
380 // Add a transaction to the wallet, or update it.
381 // pblock is optional, but should be provided if the transaction is known to be in a block.
382 // If fUpdate is true, existing transactions will be updated.
383 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fFindBlock)
385 uint256 hash = tx.GetHash();
386 CRITICAL_BLOCK(cs_wallet)
388 bool fExisted = mapWallet.count(hash);
389 if (fExisted && !fUpdate) return false;
390 if (fExisted || IsMine(tx) || IsFromMe(tx))
392 CWalletTx wtx(this,tx);
393 // Get merkle branch if transaction was found in a block
395 wtx.SetMerkleBranch(pblock);
396 return AddToWallet(wtx);
399 WalletUpdateSpent(tx);
404 bool CWallet::EraseFromWallet(uint256 hash)
408 CRITICAL_BLOCK(cs_wallet)
410 if (mapWallet.erase(hash))
411 CWalletDB(strWalletFile).EraseTx(hash);
417 bool CWallet::IsMine(const CTxIn &txin) const
419 CRITICAL_BLOCK(cs_wallet)
421 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
422 if (mi != mapWallet.end())
424 const CWalletTx& prev = (*mi).second;
425 if (txin.prevout.n < prev.vout.size())
426 if (IsMine(prev.vout[txin.prevout.n]))
433 int64 CWallet::GetDebit(const CTxIn &txin) const
435 CRITICAL_BLOCK(cs_wallet)
437 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
438 if (mi != mapWallet.end())
440 const CWalletTx& prev = (*mi).second;
441 if (txin.prevout.n < prev.vout.size())
442 if (IsMine(prev.vout[txin.prevout.n]))
443 return prev.vout[txin.prevout.n].nValue;
449 bool CWallet::IsChange(const CTxOut& txout) const
451 CBitcoinAddress address;
453 // TODO: fix handling of 'change' outputs. The assumption is that any
454 // payment to a TX_PUBKEYHASH that is mine but isn't in the address book
455 // is change. That assumption is likely to break when we implement multisignature
456 // wallets that return change back into a multi-signature-protected address;
457 // a better way of identifying which outputs are 'the send' and which are
458 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
459 // which output, if any, was change).
460 if (ExtractAddress(txout.scriptPubKey, address) && HaveKey(address))
461 CRITICAL_BLOCK(cs_wallet)
462 if (!mapAddressBook.count(address))
467 int64 CWalletTx::GetTxTime() const
469 return nTimeReceived;
472 int CWalletTx::GetRequestCount() const
474 // Returns -1 if it wasn't being tracked
476 CRITICAL_BLOCK(pwallet->cs_wallet)
483 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
484 if (mi != pwallet->mapRequestCount.end())
485 nRequests = (*mi).second;
490 // Did anyone request this transaction?
491 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
492 if (mi != pwallet->mapRequestCount.end())
494 nRequests = (*mi).second;
496 // How about the block it's in?
497 if (nRequests == 0 && hashBlock != 0)
499 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
500 if (mi != pwallet->mapRequestCount.end())
501 nRequests = (*mi).second;
503 nRequests = 1; // If it's in someone else's block it must have got out
511 void CWalletTx::GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, list<pair<CBitcoinAddress, int64> >& listReceived,
512 list<pair<CBitcoinAddress, int64> >& listSent, int64& nFee, string& strSentAccount) const
514 nGeneratedImmature = nGeneratedMature = nFee = 0;
515 listReceived.clear();
517 strSentAccount = strFromAccount;
521 if (GetBlocksToMaturity() > 0)
522 nGeneratedImmature = pwallet->GetCredit(*this);
524 nGeneratedMature = GetCredit();
529 int64 nDebit = GetDebit();
530 if (nDebit > 0) // debit>0 means we signed/sent this transaction
532 int64 nValueOut = GetValueOut();
533 nFee = nDebit - nValueOut;
537 BOOST_FOREACH(const CTxOut& txout, vout)
539 CBitcoinAddress address;
540 vector<unsigned char> vchPubKey;
541 if (!ExtractAddress(txout.scriptPubKey, address))
543 printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
544 this->GetHash().ToString().c_str());
545 address = " unknown ";
548 // Don't report 'change' txouts
549 if (nDebit > 0 && pwallet->IsChange(txout))
553 listSent.push_back(make_pair(address, txout.nValue));
555 if (pwallet->IsMine(txout))
556 listReceived.push_back(make_pair(address, txout.nValue));
561 void CWalletTx::GetAccountAmounts(const string& strAccount, int64& nGenerated, int64& nReceived,
562 int64& nSent, int64& nFee) const
564 nGenerated = nReceived = nSent = nFee = 0;
566 int64 allGeneratedImmature, allGeneratedMature, allFee;
567 allGeneratedImmature = allGeneratedMature = allFee = 0;
568 string strSentAccount;
569 list<pair<CBitcoinAddress, int64> > listReceived;
570 list<pair<CBitcoinAddress, int64> > listSent;
571 GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount);
573 if (strAccount == "")
574 nGenerated = allGeneratedMature;
575 if (strAccount == strSentAccount)
577 BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress,int64)& s, listSent)
581 CRITICAL_BLOCK(pwallet->cs_wallet)
583 BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress,int64)& r, listReceived)
585 if (pwallet->mapAddressBook.count(r.first))
587 map<CBitcoinAddress, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);
588 if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)
589 nReceived += r.second;
591 else if (strAccount.empty())
593 nReceived += r.second;
599 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
603 const int COPY_DEPTH = 3;
604 if (SetMerkleBranch() < COPY_DEPTH)
606 vector<uint256> vWorkQueue;
607 BOOST_FOREACH(const CTxIn& txin, vin)
608 vWorkQueue.push_back(txin.prevout.hash);
610 // This critsect is OK because txdb is already open
611 CRITICAL_BLOCK(pwallet->cs_wallet)
613 map<uint256, const CMerkleTx*> mapWalletPrev;
614 set<uint256> setAlreadyDone;
615 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
617 uint256 hash = vWorkQueue[i];
618 if (setAlreadyDone.count(hash))
620 setAlreadyDone.insert(hash);
623 map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
624 if (mi != pwallet->mapWallet.end())
627 BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev)
628 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
630 else if (mapWalletPrev.count(hash))
632 tx = *mapWalletPrev[hash];
634 else if (!fClient && txdb.ReadDiskTx(hash, tx))
640 printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
644 int nDepth = tx.SetMerkleBranch();
645 vtxPrev.push_back(tx);
647 if (nDepth < COPY_DEPTH)
649 BOOST_FOREACH(const CTxIn& txin, tx.vin)
650 vWorkQueue.push_back(txin.prevout.hash);
656 reverse(vtxPrev.begin(), vtxPrev.end());
659 bool CWalletTx::WriteToDisk()
661 return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
664 // Scan the block chain (starting in pindexStart) for transactions
665 // from or to us. If fUpdate is true, found transactions that already
666 // exist in the wallet will be updated.
667 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
671 CBlockIndex* pindex = pindexStart;
672 CRITICAL_BLOCK(cs_wallet)
677 block.ReadFromDisk(pindex, true);
678 BOOST_FOREACH(CTransaction& tx, block.vtx)
680 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
683 pindex = pindex->pnext;
689 int CWallet::ScanForWalletTransaction(const uint256& hashTx)
692 tx.ReadFromDisk(COutPoint(hashTx, 0));
693 if (AddToWalletIfInvolvingMe(tx, NULL, true, true))
698 void CWallet::ReacceptWalletTransactions()
702 while (fRepeat) CRITICAL_BLOCK(cs_wallet)
705 vector<CDiskTxPos> vMissingTx;
706 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
708 CWalletTx& wtx = item.second;
709 if (wtx.IsCoinBase() && wtx.IsSpent(0))
713 bool fUpdated = false;
714 if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
716 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
717 if (txindex.vSpent.size() != wtx.vout.size())
719 printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %d != wtx.vout.size() %d\n", txindex.vSpent.size(), wtx.vout.size());
722 for (unsigned int i = 0; i < txindex.vSpent.size(); i++)
726 if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i]))
730 vMissingTx.push_back(txindex.vSpent[i]);
735 printf("ReacceptWalletTransactions found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
742 // Reaccept any txes of ours that aren't already in a block
743 if (!wtx.IsCoinBase())
744 wtx.AcceptWalletTransaction(txdb, false);
747 if (!vMissingTx.empty())
749 // TODO: optimize this to scan just part of the block chain?
750 if (ScanForWalletTransactions(pindexGenesisBlock))
751 fRepeat = true; // Found missing transactions: re-do Reaccept.
756 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
758 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
760 if (!tx.IsCoinBase())
762 uint256 hash = tx.GetHash();
763 if (!txdb.ContainsTx(hash))
764 RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx);
769 uint256 hash = GetHash();
770 if (!txdb.ContainsTx(hash))
772 printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
773 RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this);
778 void CWalletTx::RelayWalletTransaction()
781 RelayWalletTransaction(txdb);
784 void CWallet::ResendWalletTransactions()
786 // Do this infrequently and randomly to avoid giving away
787 // that these are our transactions.
788 static int64 nNextTime;
789 if (GetTime() < nNextTime)
791 bool fFirst = (nNextTime == 0);
792 nNextTime = GetTime() + GetRand(30 * 60);
796 // Only do it if there's been a new block since last time
797 static int64 nLastTime;
798 if (nTimeBestReceived < nLastTime)
800 nLastTime = GetTime();
802 // Rebroadcast any of our txes that aren't in a block yet
803 printf("ResendWalletTransactions()\n");
805 CRITICAL_BLOCK(cs_wallet)
807 // Sort them in chronological order
808 multimap<unsigned int, CWalletTx*> mapSorted;
809 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
811 CWalletTx& wtx = item.second;
812 // Don't rebroadcast until it's had plenty of time that
813 // it should have gotten in already by now.
814 if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
815 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
817 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
819 CWalletTx& wtx = *item.second;
820 wtx.RelayWalletTransaction(txdb);
830 //////////////////////////////////////////////////////////////////////////////
836 int64 CWallet::GetBalance() const
839 CRITICAL_BLOCK(cs_wallet)
841 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
843 const CWalletTx* pcoin = &(*it).second;
844 if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
846 nTotal += pcoin->GetAvailableCredit();
853 int64 CWallet::GetUnconfirmedBalance() const
856 CRITICAL_BLOCK(cs_wallet)
858 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
860 const CWalletTx* pcoin = &(*it).second;
861 if (pcoin->IsFinal() && pcoin->IsConfirmed())
863 nTotal += pcoin->GetAvailableCredit();
869 bool CWallet::SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
874 // List of values less than target
875 pair<int64, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
876 coinLowestLarger.first = std::numeric_limits<int64>::max();
877 coinLowestLarger.second.first = NULL;
878 vector<pair<int64, pair<const CWalletTx*,unsigned int> > > vValue;
879 int64 nTotalLower = 0;
881 CRITICAL_BLOCK(cs_wallet)
883 vector<const CWalletTx*> vCoins;
884 vCoins.reserve(mapWallet.size());
885 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
886 vCoins.push_back(&(*it).second);
887 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
889 BOOST_FOREACH(const CWalletTx* pcoin, vCoins)
891 if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
894 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
897 int nDepth = pcoin->GetDepthInMainChain();
898 if (nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs))
901 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
903 if (pcoin->IsSpent(i) || !IsMine(pcoin->vout[i]))
906 int64 n = pcoin->vout[i].nValue;
911 pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin,i));
913 if (n == nTargetValue)
915 setCoinsRet.insert(coin.second);
916 nValueRet += coin.first;
919 else if (n < nTargetValue + CENT)
921 vValue.push_back(coin);
924 else if (n < coinLowestLarger.first)
926 coinLowestLarger = coin;
932 if (nTotalLower == nTargetValue || nTotalLower == nTargetValue + CENT)
934 for (unsigned int i = 0; i < vValue.size(); ++i)
936 setCoinsRet.insert(vValue[i].second);
937 nValueRet += vValue[i].first;
942 if (nTotalLower < nTargetValue + (coinLowestLarger.second.first ? CENT : 0))
944 if (coinLowestLarger.second.first == NULL)
946 setCoinsRet.insert(coinLowestLarger.second);
947 nValueRet += coinLowestLarger.first;
951 if (nTotalLower >= nTargetValue + CENT)
952 nTargetValue += CENT;
954 // Solve subset sum by stochastic approximation
955 sort(vValue.rbegin(), vValue.rend());
956 vector<char> vfIncluded;
957 vector<char> vfBest(vValue.size(), true);
958 int64 nBest = nTotalLower;
960 for (int nRep = 0; nRep < 1000 && nBest != nTargetValue; nRep++)
962 vfIncluded.assign(vValue.size(), false);
964 bool fReachedTarget = false;
965 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
967 for (unsigned int i = 0; i < vValue.size(); i++)
969 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
971 nTotal += vValue[i].first;
972 vfIncluded[i] = true;
973 if (nTotal >= nTargetValue)
975 fReachedTarget = true;
981 nTotal -= vValue[i].first;
982 vfIncluded[i] = false;
989 // If the next larger is still closer, return it
990 if (coinLowestLarger.second.first && coinLowestLarger.first - nTargetValue <= nBest - nTargetValue)
992 setCoinsRet.insert(coinLowestLarger.second);
993 nValueRet += coinLowestLarger.first;
996 for (unsigned int i = 0; i < vValue.size(); i++)
999 setCoinsRet.insert(vValue[i].second);
1000 nValueRet += vValue[i].first;
1004 printf("SelectCoins() best subset: ");
1005 for (unsigned int i = 0; i < vValue.size(); i++)
1007 printf("%s ", FormatMoney(vValue[i].first).c_str());
1008 printf("total %s\n", FormatMoney(nBest).c_str());
1014 bool CWallet::SelectCoins(int64 nTargetValue, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
1016 return (SelectCoinsMinConf(nTargetValue, 1, 6, setCoinsRet, nValueRet) ||
1017 SelectCoinsMinConf(nTargetValue, 1, 1, setCoinsRet, nValueRet) ||
1018 SelectCoinsMinConf(nTargetValue, 0, 1, setCoinsRet, nValueRet));
1024 bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
1027 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1033 if (vecSend.empty() || nValue < 0)
1036 wtxNew.BindWallet(this);
1038 CRITICAL_BLOCK(cs_main)
1039 CRITICAL_BLOCK(cs_wallet)
1041 // txdb must be opened before the mapWallet lock
1044 nFeeRet = nTransactionFee;
1048 wtxNew.vout.clear();
1049 wtxNew.fFromMe = true;
1051 int64 nTotalValue = nValue + nFeeRet;
1052 double dPriority = 0;
1053 // vouts to the payees
1054 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1055 wtxNew.vout.push_back(CTxOut(s.second, s.first));
1057 // Choose coins to use
1058 set<pair<const CWalletTx*,unsigned int> > setCoins;
1060 if (!SelectCoins(nTotalValue, setCoins, nValueIn))
1062 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1064 int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
1065 dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
1068 int64 nChange = nValueIn - nValue - nFeeRet;
1069 // if sub-cent change is required, the fee must be raised to at least MIN_TX_FEE
1070 // or until nChange becomes zero
1071 // NOTE: this depends on the exact behaviour of GetMinFee
1072 if (nFeeRet < MIN_TX_FEE && nChange > 0 && nChange < CENT)
1074 int64 nMoveToFee = min(nChange, MIN_TX_FEE - nFeeRet);
1075 nChange -= nMoveToFee;
1076 nFeeRet += nMoveToFee;
1081 // Note: We use a new key here to keep it from being obvious which side is the change.
1082 // The drawback is that by not reusing a previous key, the change may be lost if a
1083 // backup is restored, if the backup doesn't have the new private key for the change.
1084 // If we reused the old key, it would be possible to add code to look for and
1085 // rediscover unknown transactions that were written with keys of ours to recover
1086 // post-backup change.
1088 // Reserve a new key pair from key pool
1089 vector<unsigned char> vchPubKey = reservekey.GetReservedKey();
1090 // assert(mapKeys.count(vchPubKey));
1092 // Fill a vout to ourself
1093 // TODO: pass in scriptChange instead of reservekey so
1094 // change transaction isn't always pay-to-bitcoin-address
1095 CScript scriptChange;
1096 scriptChange.SetBitcoinAddress(vchPubKey);
1098 // Insert change txn at random position:
1099 vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
1100 wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
1103 reservekey.ReturnKey();
1106 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1107 wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
1111 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1112 if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
1116 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK);
1117 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1119 dPriority /= nBytes;
1121 // Check that enough fee is included
1122 int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
1123 bool fAllowFree = CTransaction::AllowFree(dPriority);
1124 int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND);
1125 if (nFeeRet < max(nPayFee, nMinFee))
1127 nFeeRet = max(nPayFee, nMinFee);
1131 // Fill vtxPrev by copying from previous transactions vtxPrev
1132 wtxNew.AddSupportingTransactions(txdb);
1133 wtxNew.fTimeReceivedIsTxTime = true;
1142 bool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
1144 vector< pair<CScript, int64> > vecSend;
1145 vecSend.push_back(make_pair(scriptPubKey, nValue));
1146 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet);
1149 // Call after CreateTransaction unless you want to abort
1150 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
1152 CRITICAL_BLOCK(cs_main)
1153 CRITICAL_BLOCK(cs_wallet)
1155 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
1157 // This is only to keep the database open to defeat the auto-flush for the
1158 // duration of this scope. This is the only place where this optimization
1159 // maybe makes sense; please don't do it anywhere else.
1160 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
1162 // Take key pair from key pool so it won't be used again
1163 reservekey.KeepKey();
1165 // Add tx to wallet, because if it has change it's also ours,
1166 // otherwise just for transaction history.
1167 AddToWallet(wtxNew);
1169 // Mark old coins as spent
1170 set<CWalletTx*> setCoins;
1171 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
1173 CWalletTx &coin = mapWallet[txin.prevout.hash];
1174 coin.BindWallet(this);
1175 coin.MarkSpent(txin.prevout.n);
1177 vWalletUpdated.push_back(coin.GetHash());
1184 // Track how many getdata requests our transaction gets
1185 mapRequestCount[wtxNew.GetHash()] = 0;
1188 if (!wtxNew.AcceptToMemoryPool())
1190 // This must not fail. The transaction has already been signed and recorded.
1191 printf("CommitTransaction() : Error: Transaction not valid");
1194 wtxNew.RelayWalletTransaction();
1203 string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1205 CReserveKey reservekey(this);
1210 string strError = _("Error: Wallet locked, unable to create transaction ");
1211 printf("SendMoney() : %s", strError.c_str());
1214 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
1217 if (nValue + nFeeRequired > GetBalance())
1218 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());
1220 strError = _("Error: Transaction creation failed ");
1221 printf("SendMoney() : %s", strError.c_str());
1225 if (fAskFee && !ThreadSafeAskFee(nFeeRequired, _("Sending..."), NULL))
1228 if (!CommitTransaction(wtxNew, reservekey))
1229 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.");
1237 string CWallet::SendMoneyToBitcoinAddress(const CBitcoinAddress& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1241 return _("Invalid amount");
1242 if (nValue + nTransactionFee > GetBalance())
1243 return _("Insufficient funds");
1245 // Parse bitcoin address
1246 CScript scriptPubKey;
1247 scriptPubKey.SetBitcoinAddress(address);
1249 return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
1255 int CWallet::LoadWallet(bool& fFirstRunRet)
1259 fFirstRunRet = false;
1260 int nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
1261 if (nLoadWalletRet == DB_NEED_REWRITE)
1263 if (CDB::Rewrite(strWalletFile, "\x04pool"))
1266 // Note: can't top-up keypool here, because wallet is locked.
1267 // User will be prompted to unlock wallet the next operation
1268 // the requires a new key.
1270 nLoadWalletRet = DB_NEED_REWRITE;
1273 if (nLoadWalletRet != DB_LOAD_OK)
1274 return nLoadWalletRet;
1275 fFirstRunRet = vchDefaultKey.empty();
1277 CreateThread(ThreadFlushWalletDB, &strWalletFile);
1282 bool CWallet::SetAddressBookName(const CBitcoinAddress& address, const string& strName)
1284 mapAddressBook[address] = strName;
1287 return CWalletDB(strWalletFile).WriteName(address.ToString(), strName);
1290 bool CWallet::DelAddressBookName(const CBitcoinAddress& address)
1292 mapAddressBook.erase(address);
1295 return CWalletDB(strWalletFile).EraseName(address.ToString());
1299 void CWallet::PrintWallet(const CBlock& block)
1301 CRITICAL_BLOCK(cs_wallet)
1303 if (mapWallet.count(block.vtx[0].GetHash()))
1305 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
1306 printf(" mine: %d %d %d", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
1312 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
1314 CRITICAL_BLOCK(cs_wallet)
1316 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
1317 if (mi != mapWallet.end())
1326 bool CWallet::SetDefaultKey(const std::vector<unsigned char> &vchPubKey)
1330 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
1333 vchDefaultKey = vchPubKey;
1337 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
1339 if (!pwallet->fFileBacked)
1341 strWalletFileOut = pwallet->strWalletFile;
1346 // Mark old keypool keys as used,
1347 // and generate all new keys
1349 bool CWallet::NewKeyPool()
1351 CRITICAL_BLOCK(cs_wallet)
1353 CWalletDB walletdb(strWalletFile);
1354 BOOST_FOREACH(int64 nIndex, setKeyPool)
1355 walletdb.ErasePool(nIndex);
1361 int64 nKeys = max(GetArg("-keypool", 100), (int64)0);
1362 for (int i = 0; i < nKeys; i++)
1365 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
1366 setKeyPool.insert(nIndex);
1368 printf("CWallet::NewKeyPool wrote %"PRI64d" new keys\n", nKeys);
1373 bool CWallet::TopUpKeyPool()
1375 CRITICAL_BLOCK(cs_wallet)
1380 CWalletDB walletdb(strWalletFile);
1383 int64 nTargetSize = max(GetArg("-keypool", 100), (int64)0);
1384 while (setKeyPool.size() < nTargetSize+1)
1387 if (!setKeyPool.empty())
1388 nEnd = *(--setKeyPool.end()) + 1;
1389 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
1390 throw runtime_error("TopUpKeyPool() : writing generated key failed");
1391 setKeyPool.insert(nEnd);
1392 printf("keypool added key %"PRI64d", size=%d\n", nEnd, setKeyPool.size());
1398 void CWallet::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool)
1401 keypool.vchPubKey.clear();
1402 CRITICAL_BLOCK(cs_wallet)
1407 // Get the oldest key
1408 if(setKeyPool.empty())
1411 CWalletDB walletdb(strWalletFile);
1413 nIndex = *(setKeyPool.begin());
1414 setKeyPool.erase(setKeyPool.begin());
1415 if (!walletdb.ReadPool(nIndex, keypool))
1416 throw runtime_error("ReserveKeyFromKeyPool() : read failed");
1417 if (!HaveKey(Hash160(keypool.vchPubKey)))
1418 throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
1419 assert(!keypool.vchPubKey.empty());
1420 printf("keypool reserve %"PRI64d"\n", nIndex);
1424 int64 CWallet::AddReserveKey(const CKeyPool& keypool)
1426 CRITICAL_BLOCK(cs_main)
1427 CRITICAL_BLOCK(cs_wallet)
1429 CWalletDB walletdb(strWalletFile);
1431 int64 nIndex = 1 + *(--setKeyPool.end());
1432 if (!walletdb.WritePool(nIndex, keypool))
1433 throw runtime_error("AddReserveKey() : writing added key failed");
1434 setKeyPool.insert(nIndex);
1440 void CWallet::KeepKey(int64 nIndex)
1442 // Remove from key pool
1445 CWalletDB walletdb(strWalletFile);
1446 walletdb.ErasePool(nIndex);
1448 printf("keypool keep %"PRI64d"\n", nIndex);
1451 void CWallet::ReturnKey(int64 nIndex)
1453 // Return to key pool
1454 CRITICAL_BLOCK(cs_wallet)
1455 setKeyPool.insert(nIndex);
1456 printf("keypool return %"PRI64d"\n", nIndex);
1459 bool CWallet::GetKeyFromPool(vector<unsigned char>& result, bool fAllowReuse)
1463 CRITICAL_BLOCK(cs_wallet)
1465 ReserveKeyFromKeyPool(nIndex, keypool);
1468 if (fAllowReuse && !vchDefaultKey.empty())
1470 result = vchDefaultKey;
1473 if (IsLocked()) return false;
1474 result = GenerateNewKey();
1478 result = keypool.vchPubKey;
1483 int64 CWallet::GetOldestKeyPoolTime()
1487 ReserveKeyFromKeyPool(nIndex, keypool);
1491 return keypool.nTime;
1494 vector<unsigned char> CReserveKey::GetReservedKey()
1499 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
1501 vchPubKey = keypool.vchPubKey;
1504 printf("CReserveKey::GetReservedKey(): Warning: using default key instead of a new key, top up your keypool.");
1505 vchPubKey = pwallet->vchDefaultKey;
1508 assert(!vchPubKey.empty());
1512 void CReserveKey::KeepKey()
1515 pwallet->KeepKey(nIndex);
1520 void CReserveKey::ReturnKey()
1523 pwallet->ReturnKey(nIndex);
1528 void CWallet::GetAllReserveAddresses(set<CBitcoinAddress>& setAddress)
1532 CWalletDB walletdb(strWalletFile);
1534 CRITICAL_BLOCK(cs_main)
1535 CRITICAL_BLOCK(cs_wallet)
1536 BOOST_FOREACH(const int64& id, setKeyPool)
1539 if (!walletdb.ReadPool(id, keypool))
1540 throw runtime_error("GetAllReserveKeyHashes() : read failed");
1541 CBitcoinAddress address(keypool.vchPubKey);
1542 assert(!keypool.vchPubKey.empty());
1543 if (!HaveKey(address))
1544 throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
1545 setAddress.insert(address);