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()
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 pwalletdbEncryption->TxnBegin();
238 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
241 if (!EncryptKeys(vMasterKey))
244 pwalletdbEncryption->TxnAbort();
245 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.
248 // Encryption was introduced in version 0.4.0
249 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
253 if (!pwalletdbEncryption->TxnCommit())
254 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.
256 delete pwalletdbEncryption;
257 pwalletdbEncryption = NULL;
261 Unlock(strWalletPassphrase);
265 // Need to completely rewrite the wallet file; if we don't, bdb might keep
266 // bits of the unencrypted private key in slack space in the database file.
267 CDB::Rewrite(strWalletFile);
273 void CWallet::WalletUpdateSpent(const CTransaction &tx)
275 // Anytime a signature is successfully verified, it's proof the outpoint is spent.
276 // Update the wallet spent flag if it doesn't know due to wallet.dat being
277 // restored from backup or the user making copies of wallet.dat.
278 CRITICAL_BLOCK(cs_wallet)
280 BOOST_FOREACH(const CTxIn& txin, tx.vin)
282 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
283 if (mi != mapWallet.end())
285 CWalletTx& wtx = (*mi).second;
286 if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n]))
288 printf("WalletUpdateSpent found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
289 wtx.MarkSpent(txin.prevout.n);
291 vWalletUpdated.push_back(txin.prevout.hash);
298 void CWallet::MarkDirty()
300 CRITICAL_BLOCK(cs_wallet)
302 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
303 item.second.MarkDirty();
307 bool CWallet::AddToWallet(const CWalletTx& wtxIn)
309 uint256 hash = wtxIn.GetHash();
310 CRITICAL_BLOCK(cs_wallet)
312 // Inserts only if not already there, returns tx inserted or tx found
313 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
314 CWalletTx& wtx = (*ret.first).second;
315 wtx.BindWallet(this);
316 bool fInsertedNew = ret.second;
318 wtx.nTimeReceived = GetAdjustedTime();
320 bool fUpdated = false;
324 if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
326 wtx.hashBlock = wtxIn.hashBlock;
329 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
331 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
332 wtx.nIndex = wtxIn.nIndex;
335 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
337 wtx.fFromMe = wtxIn.fFromMe;
340 fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);
344 printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
347 if (fInsertedNew || fUpdated)
348 if (!wtx.WriteToDisk())
351 // If default receiving address gets used, replace it with a new one
352 CScript scriptDefaultKey;
353 scriptDefaultKey.SetBitcoinAddress(vchDefaultKey);
354 BOOST_FOREACH(const CTxOut& txout, wtx.vout)
356 if (txout.scriptPubKey == scriptDefaultKey)
358 std::vector<unsigned char> newDefaultKey;
359 if (GetKeyFromPool(newDefaultKey, false))
361 SetDefaultKey(newDefaultKey);
362 SetAddressBookName(CBitcoinAddress(vchDefaultKey), "");
368 vWalletUpdated.push_back(hash);
370 // since AddToWallet is called directly for self-originating transactions, check for consumption of own coins
371 WalletUpdateSpent(wtx);
379 // Add a transaction to the wallet, or update it.
380 // pblock is optional, but should be provided if the transaction is known to be in a block.
381 // If fUpdate is true, existing transactions will be updated.
382 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fFindBlock)
384 uint256 hash = tx.GetHash();
385 CRITICAL_BLOCK(cs_wallet)
387 bool fExisted = mapWallet.count(hash);
388 if (fExisted && !fUpdate) return false;
389 if (fExisted || IsMine(tx) || IsFromMe(tx))
391 CWalletTx wtx(this,tx);
392 // Get merkle branch if transaction was found in a block
394 wtx.SetMerkleBranch(pblock);
395 return AddToWallet(wtx);
398 WalletUpdateSpent(tx);
403 bool CWallet::EraseFromWallet(uint256 hash)
407 CRITICAL_BLOCK(cs_wallet)
409 if (mapWallet.erase(hash))
410 CWalletDB(strWalletFile).EraseTx(hash);
416 bool CWallet::IsMine(const CTxIn &txin) const
418 CRITICAL_BLOCK(cs_wallet)
420 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
421 if (mi != mapWallet.end())
423 const CWalletTx& prev = (*mi).second;
424 if (txin.prevout.n < prev.vout.size())
425 if (IsMine(prev.vout[txin.prevout.n]))
432 int64 CWallet::GetDebit(const CTxIn &txin) const
434 CRITICAL_BLOCK(cs_wallet)
436 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
437 if (mi != mapWallet.end())
439 const CWalletTx& prev = (*mi).second;
440 if (txin.prevout.n < prev.vout.size())
441 if (IsMine(prev.vout[txin.prevout.n]))
442 return prev.vout[txin.prevout.n].nValue;
448 bool CWallet::IsChange(const CTxOut& txout) const
450 CBitcoinAddress address;
452 // TODO: fix handling of 'change' outputs. The assumption is that any
453 // payment to a TX_PUBKEYHASH that is mine but isn't in the address book
454 // is change. That assumption is likely to break when we implement multisignature
455 // wallets that return change back into a multi-signature-protected address;
456 // a better way of identifying which outputs are 'the send' and which are
457 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
458 // which output, if any, was change).
459 if (ExtractAddress(txout.scriptPubKey, address) && HaveKey(address))
460 CRITICAL_BLOCK(cs_wallet)
461 if (!mapAddressBook.count(address))
466 int64 CWalletTx::GetTxTime() const
468 return nTimeReceived;
471 int CWalletTx::GetRequestCount() const
473 // Returns -1 if it wasn't being tracked
475 CRITICAL_BLOCK(pwallet->cs_wallet)
482 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
483 if (mi != pwallet->mapRequestCount.end())
484 nRequests = (*mi).second;
489 // Did anyone request this transaction?
490 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
491 if (mi != pwallet->mapRequestCount.end())
493 nRequests = (*mi).second;
495 // How about the block it's in?
496 if (nRequests == 0 && hashBlock != 0)
498 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
499 if (mi != pwallet->mapRequestCount.end())
500 nRequests = (*mi).second;
502 nRequests = 1; // If it's in someone else's block it must have got out
510 void CWalletTx::GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, list<pair<CBitcoinAddress, int64> >& listReceived,
511 list<pair<CBitcoinAddress, int64> >& listSent, int64& nFee, string& strSentAccount) const
513 nGeneratedImmature = nGeneratedMature = nFee = 0;
514 listReceived.clear();
516 strSentAccount = strFromAccount;
520 if (GetBlocksToMaturity() > 0)
521 nGeneratedImmature = pwallet->GetCredit(*this);
523 nGeneratedMature = GetCredit();
528 int64 nDebit = GetDebit();
529 if (nDebit > 0) // debit>0 means we signed/sent this transaction
531 int64 nValueOut = GetValueOut();
532 nFee = nDebit - nValueOut;
536 BOOST_FOREACH(const CTxOut& txout, vout)
538 CBitcoinAddress address;
539 vector<unsigned char> vchPubKey;
540 if (!ExtractAddress(txout.scriptPubKey, address))
542 printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
543 this->GetHash().ToString().c_str());
544 address = " unknown ";
547 // Don't report 'change' txouts
548 if (nDebit > 0 && pwallet->IsChange(txout))
552 listSent.push_back(make_pair(address, txout.nValue));
554 if (pwallet->IsMine(txout))
555 listReceived.push_back(make_pair(address, txout.nValue));
560 void CWalletTx::GetAccountAmounts(const string& strAccount, int64& nGenerated, int64& nReceived,
561 int64& nSent, int64& nFee) const
563 nGenerated = nReceived = nSent = nFee = 0;
565 int64 allGeneratedImmature, allGeneratedMature, allFee;
566 allGeneratedImmature = allGeneratedMature = allFee = 0;
567 string strSentAccount;
568 list<pair<CBitcoinAddress, int64> > listReceived;
569 list<pair<CBitcoinAddress, int64> > listSent;
570 GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount);
572 if (strAccount == "")
573 nGenerated = allGeneratedMature;
574 if (strAccount == strSentAccount)
576 BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress,int64)& s, listSent)
580 CRITICAL_BLOCK(pwallet->cs_wallet)
582 BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress,int64)& r, listReceived)
584 if (pwallet->mapAddressBook.count(r.first))
586 map<CBitcoinAddress, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);
587 if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)
588 nReceived += r.second;
590 else if (strAccount.empty())
592 nReceived += r.second;
598 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
602 const int COPY_DEPTH = 3;
603 if (SetMerkleBranch() < COPY_DEPTH)
605 vector<uint256> vWorkQueue;
606 BOOST_FOREACH(const CTxIn& txin, vin)
607 vWorkQueue.push_back(txin.prevout.hash);
609 // This critsect is OK because txdb is already open
610 CRITICAL_BLOCK(pwallet->cs_wallet)
612 map<uint256, const CMerkleTx*> mapWalletPrev;
613 set<uint256> setAlreadyDone;
614 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
616 uint256 hash = vWorkQueue[i];
617 if (setAlreadyDone.count(hash))
619 setAlreadyDone.insert(hash);
622 map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
623 if (mi != pwallet->mapWallet.end())
626 BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev)
627 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
629 else if (mapWalletPrev.count(hash))
631 tx = *mapWalletPrev[hash];
633 else if (!fClient && txdb.ReadDiskTx(hash, tx))
639 printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
643 int nDepth = tx.SetMerkleBranch();
644 vtxPrev.push_back(tx);
646 if (nDepth < COPY_DEPTH)
648 BOOST_FOREACH(const CTxIn& txin, tx.vin)
649 vWorkQueue.push_back(txin.prevout.hash);
655 reverse(vtxPrev.begin(), vtxPrev.end());
658 bool CWalletTx::WriteToDisk()
660 return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
663 // Scan the block chain (starting in pindexStart) for transactions
664 // from or to us. If fUpdate is true, found transactions that already
665 // exist in the wallet will be updated.
666 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
670 CBlockIndex* pindex = pindexStart;
671 CRITICAL_BLOCK(cs_wallet)
676 block.ReadFromDisk(pindex, true);
677 BOOST_FOREACH(CTransaction& tx, block.vtx)
679 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
682 pindex = pindex->pnext;
688 int CWallet::ScanForWalletTransaction(const uint256& hashTx)
691 tx.ReadFromDisk(COutPoint(hashTx, 0));
692 if (AddToWalletIfInvolvingMe(tx, NULL, true, true))
697 void CWallet::ReacceptWalletTransactions()
701 while (fRepeat) CRITICAL_BLOCK(cs_wallet)
704 vector<CDiskTxPos> vMissingTx;
705 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
707 CWalletTx& wtx = item.second;
708 if (wtx.IsCoinBase() && wtx.IsSpent(0))
712 bool fUpdated = false;
713 if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
715 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
716 if (txindex.vSpent.size() != wtx.vout.size())
718 printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %d != wtx.vout.size() %d\n", txindex.vSpent.size(), wtx.vout.size());
721 for (unsigned int i = 0; i < txindex.vSpent.size(); i++)
725 if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i]))
729 vMissingTx.push_back(txindex.vSpent[i]);
734 printf("ReacceptWalletTransactions found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
741 // Reaccept any txes of ours that aren't already in a block
742 if (!wtx.IsCoinBase())
743 wtx.AcceptWalletTransaction(txdb, false);
746 if (!vMissingTx.empty())
748 // TODO: optimize this to scan just part of the block chain?
749 if (ScanForWalletTransactions(pindexGenesisBlock))
750 fRepeat = true; // Found missing transactions: re-do Reaccept.
755 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
757 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
759 if (!tx.IsCoinBase())
761 uint256 hash = tx.GetHash();
762 if (!txdb.ContainsTx(hash))
763 RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx);
768 uint256 hash = GetHash();
769 if (!txdb.ContainsTx(hash))
771 printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
772 RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this);
777 void CWalletTx::RelayWalletTransaction()
780 RelayWalletTransaction(txdb);
783 void CWallet::ResendWalletTransactions()
785 // Do this infrequently and randomly to avoid giving away
786 // that these are our transactions.
787 static int64 nNextTime;
788 if (GetTime() < nNextTime)
790 bool fFirst = (nNextTime == 0);
791 nNextTime = GetTime() + GetRand(30 * 60);
795 // Only do it if there's been a new block since last time
796 static int64 nLastTime;
797 if (nTimeBestReceived < nLastTime)
799 nLastTime = GetTime();
801 // Rebroadcast any of our txes that aren't in a block yet
802 printf("ResendWalletTransactions()\n");
804 CRITICAL_BLOCK(cs_wallet)
806 // Sort them in chronological order
807 multimap<unsigned int, CWalletTx*> mapSorted;
808 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
810 CWalletTx& wtx = item.second;
811 // Don't rebroadcast until it's had plenty of time that
812 // it should have gotten in already by now.
813 if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
814 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
816 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
818 CWalletTx& wtx = *item.second;
819 wtx.RelayWalletTransaction(txdb);
829 //////////////////////////////////////////////////////////////////////////////
835 int64 CWallet::GetBalance() const
838 CRITICAL_BLOCK(cs_wallet)
840 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
842 const CWalletTx* pcoin = &(*it).second;
843 if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
845 nTotal += pcoin->GetAvailableCredit();
852 int64 CWallet::GetUnconfirmedBalance() const
855 CRITICAL_BLOCK(cs_wallet)
857 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
859 const CWalletTx* pcoin = &(*it).second;
860 if (pcoin->IsFinal() && pcoin->IsConfirmed())
862 nTotal += pcoin->GetAvailableCredit();
868 bool CWallet::SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
873 // List of values less than target
874 pair<int64, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
875 coinLowestLarger.first = std::numeric_limits<int64>::max();
876 coinLowestLarger.second.first = NULL;
877 vector<pair<int64, pair<const CWalletTx*,unsigned int> > > vValue;
878 int64 nTotalLower = 0;
880 CRITICAL_BLOCK(cs_wallet)
882 vector<const CWalletTx*> vCoins;
883 vCoins.reserve(mapWallet.size());
884 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
885 vCoins.push_back(&(*it).second);
886 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
888 BOOST_FOREACH(const CWalletTx* pcoin, vCoins)
890 if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
893 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
896 int nDepth = pcoin->GetDepthInMainChain();
897 if (nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs))
900 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
902 if (pcoin->IsSpent(i) || !IsMine(pcoin->vout[i]))
905 int64 n = pcoin->vout[i].nValue;
910 pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin,i));
912 if (n == nTargetValue)
914 setCoinsRet.insert(coin.second);
915 nValueRet += coin.first;
918 else if (n < nTargetValue + CENT)
920 vValue.push_back(coin);
923 else if (n < coinLowestLarger.first)
925 coinLowestLarger = coin;
931 if (nTotalLower == nTargetValue || nTotalLower == nTargetValue + CENT)
933 for (unsigned int i = 0; i < vValue.size(); ++i)
935 setCoinsRet.insert(vValue[i].second);
936 nValueRet += vValue[i].first;
941 if (nTotalLower < nTargetValue + (coinLowestLarger.second.first ? CENT : 0))
943 if (coinLowestLarger.second.first == NULL)
945 setCoinsRet.insert(coinLowestLarger.second);
946 nValueRet += coinLowestLarger.first;
950 if (nTotalLower >= nTargetValue + CENT)
951 nTargetValue += CENT;
953 // Solve subset sum by stochastic approximation
954 sort(vValue.rbegin(), vValue.rend());
955 vector<char> vfIncluded;
956 vector<char> vfBest(vValue.size(), true);
957 int64 nBest = nTotalLower;
959 for (int nRep = 0; nRep < 1000 && nBest != nTargetValue; nRep++)
961 vfIncluded.assign(vValue.size(), false);
963 bool fReachedTarget = false;
964 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
966 for (unsigned int i = 0; i < vValue.size(); i++)
968 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
970 nTotal += vValue[i].first;
971 vfIncluded[i] = true;
972 if (nTotal >= nTargetValue)
974 fReachedTarget = true;
980 nTotal -= vValue[i].first;
981 vfIncluded[i] = false;
988 // If the next larger is still closer, return it
989 if (coinLowestLarger.second.first && coinLowestLarger.first - nTargetValue <= nBest - nTargetValue)
991 setCoinsRet.insert(coinLowestLarger.second);
992 nValueRet += coinLowestLarger.first;
995 for (unsigned int i = 0; i < vValue.size(); i++)
998 setCoinsRet.insert(vValue[i].second);
999 nValueRet += vValue[i].first;
1003 printf("SelectCoins() best subset: ");
1004 for (unsigned int i = 0; i < vValue.size(); i++)
1006 printf("%s ", FormatMoney(vValue[i].first).c_str());
1007 printf("total %s\n", FormatMoney(nBest).c_str());
1013 bool CWallet::SelectCoins(int64 nTargetValue, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
1015 return (SelectCoinsMinConf(nTargetValue, 1, 6, setCoinsRet, nValueRet) ||
1016 SelectCoinsMinConf(nTargetValue, 1, 1, setCoinsRet, nValueRet) ||
1017 SelectCoinsMinConf(nTargetValue, 0, 1, setCoinsRet, nValueRet));
1023 bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
1026 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1032 if (vecSend.empty() || nValue < 0)
1035 wtxNew.BindWallet(this);
1037 CRITICAL_BLOCK(cs_main)
1038 CRITICAL_BLOCK(cs_wallet)
1040 // txdb must be opened before the mapWallet lock
1043 nFeeRet = nTransactionFee;
1047 wtxNew.vout.clear();
1048 wtxNew.fFromMe = true;
1050 int64 nTotalValue = nValue + nFeeRet;
1051 double dPriority = 0;
1052 // vouts to the payees
1053 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1054 wtxNew.vout.push_back(CTxOut(s.second, s.first));
1056 // Choose coins to use
1057 set<pair<const CWalletTx*,unsigned int> > setCoins;
1059 if (!SelectCoins(nTotalValue, setCoins, nValueIn))
1061 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1063 int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
1064 dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
1067 int64 nChange = nValueIn - nValue - nFeeRet;
1068 // if sub-cent change is required, the fee must be raised to at least MIN_TX_FEE
1069 // or until nChange becomes zero
1070 // NOTE: this depends on the exact behaviour of GetMinFee
1071 if (nFeeRet < MIN_TX_FEE && nChange > 0 && nChange < CENT)
1073 int64 nMoveToFee = min(nChange, MIN_TX_FEE - nFeeRet);
1074 nChange -= nMoveToFee;
1075 nFeeRet += nMoveToFee;
1080 // Note: We use a new key here to keep it from being obvious which side is the change.
1081 // The drawback is that by not reusing a previous key, the change may be lost if a
1082 // backup is restored, if the backup doesn't have the new private key for the change.
1083 // If we reused the old key, it would be possible to add code to look for and
1084 // rediscover unknown transactions that were written with keys of ours to recover
1085 // post-backup change.
1087 // Reserve a new key pair from key pool
1088 vector<unsigned char> vchPubKey = reservekey.GetReservedKey();
1089 // assert(mapKeys.count(vchPubKey));
1091 // Fill a vout to ourself
1092 // TODO: pass in scriptChange instead of reservekey so
1093 // change transaction isn't always pay-to-bitcoin-address
1094 CScript scriptChange;
1095 scriptChange.SetBitcoinAddress(vchPubKey);
1097 // Insert change txn at random position:
1098 vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
1099 wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
1102 reservekey.ReturnKey();
1105 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1106 wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
1110 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1111 if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
1115 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK);
1116 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1118 dPriority /= nBytes;
1120 // Check that enough fee is included
1121 int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
1122 bool fAllowFree = CTransaction::AllowFree(dPriority);
1123 int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND);
1124 if (nFeeRet < max(nPayFee, nMinFee))
1126 nFeeRet = max(nPayFee, nMinFee);
1130 // Fill vtxPrev by copying from previous transactions vtxPrev
1131 wtxNew.AddSupportingTransactions(txdb);
1132 wtxNew.fTimeReceivedIsTxTime = true;
1141 bool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
1143 vector< pair<CScript, int64> > vecSend;
1144 vecSend.push_back(make_pair(scriptPubKey, nValue));
1145 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet);
1148 // Call after CreateTransaction unless you want to abort
1149 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
1151 CRITICAL_BLOCK(cs_main)
1152 CRITICAL_BLOCK(cs_wallet)
1154 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
1156 // This is only to keep the database open to defeat the auto-flush for the
1157 // duration of this scope. This is the only place where this optimization
1158 // maybe makes sense; please don't do it anywhere else.
1159 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
1161 // Take key pair from key pool so it won't be used again
1162 reservekey.KeepKey();
1164 // Add tx to wallet, because if it has change it's also ours,
1165 // otherwise just for transaction history.
1166 AddToWallet(wtxNew);
1168 // Mark old coins as spent
1169 set<CWalletTx*> setCoins;
1170 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
1172 CWalletTx &coin = mapWallet[txin.prevout.hash];
1173 coin.BindWallet(this);
1174 coin.MarkSpent(txin.prevout.n);
1176 vWalletUpdated.push_back(coin.GetHash());
1183 // Track how many getdata requests our transaction gets
1184 mapRequestCount[wtxNew.GetHash()] = 0;
1187 if (!wtxNew.AcceptToMemoryPool())
1189 // This must not fail. The transaction has already been signed and recorded.
1190 printf("CommitTransaction() : Error: Transaction not valid");
1193 wtxNew.RelayWalletTransaction();
1202 string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1204 CReserveKey reservekey(this);
1209 string strError = _("Error: Wallet locked, unable to create transaction ");
1210 printf("SendMoney() : %s", strError.c_str());
1213 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
1216 if (nValue + nFeeRequired > GetBalance())
1217 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());
1219 strError = _("Error: Transaction creation failed ");
1220 printf("SendMoney() : %s", strError.c_str());
1224 if (fAskFee && !ThreadSafeAskFee(nFeeRequired, _("Sending..."), NULL))
1227 if (!CommitTransaction(wtxNew, reservekey))
1228 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.");
1236 string CWallet::SendMoneyToBitcoinAddress(const CBitcoinAddress& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1240 return _("Invalid amount");
1241 if (nValue + nTransactionFee > GetBalance())
1242 return _("Insufficient funds");
1244 // Parse bitcoin address
1245 CScript scriptPubKey;
1246 scriptPubKey.SetBitcoinAddress(address);
1248 return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
1254 int CWallet::LoadWallet(bool& fFirstRunRet)
1258 fFirstRunRet = false;
1259 int nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
1260 if (nLoadWalletRet == DB_NEED_REWRITE)
1262 if (CDB::Rewrite(strWalletFile, "\x04pool"))
1265 // Note: can't top-up keypool here, because wallet is locked.
1266 // User will be prompted to unlock wallet the next operation
1267 // the requires a new key.
1269 nLoadWalletRet = DB_NEED_REWRITE;
1272 if (nLoadWalletRet != DB_LOAD_OK)
1273 return nLoadWalletRet;
1274 fFirstRunRet = vchDefaultKey.empty();
1276 CreateThread(ThreadFlushWalletDB, &strWalletFile);
1281 bool CWallet::SetAddressBookName(const CBitcoinAddress& address, const string& strName)
1283 mapAddressBook[address] = strName;
1286 return CWalletDB(strWalletFile).WriteName(address.ToString(), strName);
1289 bool CWallet::DelAddressBookName(const CBitcoinAddress& address)
1291 mapAddressBook.erase(address);
1294 return CWalletDB(strWalletFile).EraseName(address.ToString());
1298 void CWallet::PrintWallet(const CBlock& block)
1300 CRITICAL_BLOCK(cs_wallet)
1302 if (mapWallet.count(block.vtx[0].GetHash()))
1304 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
1305 printf(" mine: %d %d %d", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
1311 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
1313 CRITICAL_BLOCK(cs_wallet)
1315 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
1316 if (mi != mapWallet.end())
1325 bool CWallet::SetDefaultKey(const std::vector<unsigned char> &vchPubKey)
1329 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
1332 vchDefaultKey = vchPubKey;
1336 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
1338 if (!pwallet->fFileBacked)
1340 strWalletFileOut = pwallet->strWalletFile;
1345 // Mark old keypool keys as used,
1346 // and generate all new keys
1348 bool CWallet::NewKeyPool()
1350 CRITICAL_BLOCK(cs_wallet)
1352 CWalletDB walletdb(strWalletFile);
1353 BOOST_FOREACH(int64 nIndex, setKeyPool)
1354 walletdb.ErasePool(nIndex);
1360 int64 nKeys = max(GetArg("-keypool", 100), (int64)0);
1361 for (int i = 0; i < nKeys; i++)
1364 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
1365 setKeyPool.insert(nIndex);
1367 printf("CWallet::NewKeyPool wrote %"PRI64d" new keys\n", nKeys);
1372 bool CWallet::TopUpKeyPool()
1374 CRITICAL_BLOCK(cs_wallet)
1379 CWalletDB walletdb(strWalletFile);
1382 int64 nTargetSize = max(GetArg("-keypool", 100), (int64)0);
1383 while (setKeyPool.size() < nTargetSize+1)
1386 if (!setKeyPool.empty())
1387 nEnd = *(--setKeyPool.end()) + 1;
1388 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
1389 throw runtime_error("TopUpKeyPool() : writing generated key failed");
1390 setKeyPool.insert(nEnd);
1391 printf("keypool added key %"PRI64d", size=%d\n", nEnd, setKeyPool.size());
1397 void CWallet::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool)
1400 keypool.vchPubKey.clear();
1401 CRITICAL_BLOCK(cs_wallet)
1406 // Get the oldest key
1407 if(setKeyPool.empty())
1410 CWalletDB walletdb(strWalletFile);
1412 nIndex = *(setKeyPool.begin());
1413 setKeyPool.erase(setKeyPool.begin());
1414 if (!walletdb.ReadPool(nIndex, keypool))
1415 throw runtime_error("ReserveKeyFromKeyPool() : read failed");
1416 if (!HaveKey(Hash160(keypool.vchPubKey)))
1417 throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
1418 assert(!keypool.vchPubKey.empty());
1419 printf("keypool reserve %"PRI64d"\n", nIndex);
1423 int64 CWallet::AddReserveKey(const CKeyPool& keypool)
1425 CRITICAL_BLOCK(cs_main)
1426 CRITICAL_BLOCK(cs_wallet)
1428 CWalletDB walletdb(strWalletFile);
1430 int64 nIndex = 1 + *(--setKeyPool.end());
1431 if (!walletdb.WritePool(nIndex, keypool))
1432 throw runtime_error("AddReserveKey() : writing added key failed");
1433 setKeyPool.insert(nIndex);
1439 void CWallet::KeepKey(int64 nIndex)
1441 // Remove from key pool
1444 CWalletDB walletdb(strWalletFile);
1445 walletdb.ErasePool(nIndex);
1447 printf("keypool keep %"PRI64d"\n", nIndex);
1450 void CWallet::ReturnKey(int64 nIndex)
1452 // Return to key pool
1453 CRITICAL_BLOCK(cs_wallet)
1454 setKeyPool.insert(nIndex);
1455 printf("keypool return %"PRI64d"\n", nIndex);
1458 bool CWallet::GetKeyFromPool(vector<unsigned char>& result, bool fAllowReuse)
1462 CRITICAL_BLOCK(cs_wallet)
1464 ReserveKeyFromKeyPool(nIndex, keypool);
1467 if (fAllowReuse && !vchDefaultKey.empty())
1469 result = vchDefaultKey;
1472 if (IsLocked()) return false;
1473 result = GenerateNewKey();
1477 result = keypool.vchPubKey;
1482 int64 CWallet::GetOldestKeyPoolTime()
1486 ReserveKeyFromKeyPool(nIndex, keypool);
1490 return keypool.nTime;
1493 vector<unsigned char> CReserveKey::GetReservedKey()
1498 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
1500 vchPubKey = keypool.vchPubKey;
1503 printf("CReserveKey::GetReservedKey(): Warning: using default key instead of a new key, top up your keypool.");
1504 vchPubKey = pwallet->vchDefaultKey;
1507 assert(!vchPubKey.empty());
1511 void CReserveKey::KeepKey()
1514 pwallet->KeepKey(nIndex);
1519 void CReserveKey::ReturnKey()
1522 pwallet->ReturnKey(nIndex);
1527 void CWallet::GetAllReserveAddresses(set<CBitcoinAddress>& setAddress)
1531 CWalletDB walletdb(strWalletFile);
1533 CRITICAL_BLOCK(cs_main)
1534 CRITICAL_BLOCK(cs_wallet)
1535 BOOST_FOREACH(const int64& id, setKeyPool)
1538 if (!walletdb.ReadPool(id, keypool))
1539 throw runtime_error("GetAllReserveKeyHashes() : read failed");
1540 CBitcoinAddress address(keypool.vchPubKey);
1541 assert(!keypool.vchPubKey.empty());
1542 if (!HaveKey(address))
1543 throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
1544 setAddress.insert(address);