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 (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)
647 BOOST_FOREACH(const CTxIn& txin, tx.vin)
648 vWorkQueue.push_back(txin.prevout.hash);
653 reverse(vtxPrev.begin(), vtxPrev.end());
656 bool CWalletTx::WriteToDisk()
658 return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
661 // Scan the block chain (starting in pindexStart) for transactions
662 // from or to us. If fUpdate is true, found transactions that already
663 // exist in the wallet will be updated.
664 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
668 CBlockIndex* pindex = pindexStart;
669 CRITICAL_BLOCK(cs_wallet)
674 block.ReadFromDisk(pindex, true);
675 BOOST_FOREACH(CTransaction& tx, block.vtx)
677 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
680 pindex = pindex->pnext;
686 int CWallet::ScanForWalletTransaction(const uint256& hashTx)
689 tx.ReadFromDisk(COutPoint(hashTx, 0));
690 if (AddToWalletIfInvolvingMe(tx, NULL, true, true))
695 void CWallet::ReacceptWalletTransactions()
699 while (fRepeat) CRITICAL_BLOCK(cs_wallet)
702 vector<CDiskTxPos> vMissingTx;
703 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
705 CWalletTx& wtx = item.second;
706 if (wtx.IsCoinBase() && wtx.IsSpent(0))
710 bool fUpdated = false;
711 if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
713 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
714 if (txindex.vSpent.size() != wtx.vout.size())
716 printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %d != wtx.vout.size() %d\n", txindex.vSpent.size(), wtx.vout.size());
719 for (int i = 0; i < txindex.vSpent.size(); i++)
723 if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i]))
727 vMissingTx.push_back(txindex.vSpent[i]);
732 printf("ReacceptWalletTransactions found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
739 // Reaccept any txes of ours that aren't already in a block
740 if (!wtx.IsCoinBase())
741 wtx.AcceptWalletTransaction(txdb, false);
744 if (!vMissingTx.empty())
746 // TODO: optimize this to scan just part of the block chain?
747 if (ScanForWalletTransactions(pindexGenesisBlock))
748 fRepeat = true; // Found missing transactions: re-do Reaccept.
753 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
755 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
757 if (!tx.IsCoinBase())
759 uint256 hash = tx.GetHash();
760 if (!txdb.ContainsTx(hash))
761 RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx);
766 uint256 hash = GetHash();
767 if (!txdb.ContainsTx(hash))
769 printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
770 RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this);
775 void CWalletTx::RelayWalletTransaction()
778 RelayWalletTransaction(txdb);
781 void CWallet::ResendWalletTransactions()
783 // Do this infrequently and randomly to avoid giving away
784 // that these are our transactions.
785 static int64 nNextTime;
786 if (GetTime() < nNextTime)
788 bool fFirst = (nNextTime == 0);
789 nNextTime = GetTime() + GetRand(30 * 60);
793 // Only do it if there's been a new block since last time
794 static int64 nLastTime;
795 if (nTimeBestReceived < nLastTime)
797 nLastTime = GetTime();
799 // Rebroadcast any of our txes that aren't in a block yet
800 printf("ResendWalletTransactions()\n");
802 CRITICAL_BLOCK(cs_wallet)
804 // Sort them in chronological order
805 multimap<unsigned int, CWalletTx*> mapSorted;
806 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
808 CWalletTx& wtx = item.second;
809 // Don't rebroadcast until it's had plenty of time that
810 // it should have gotten in already by now.
811 if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
812 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
814 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
816 CWalletTx& wtx = *item.second;
817 wtx.RelayWalletTransaction(txdb);
827 //////////////////////////////////////////////////////////////////////////////
833 int64 CWallet::GetBalance() const
836 CRITICAL_BLOCK(cs_wallet)
838 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
840 const CWalletTx* pcoin = &(*it).second;
841 if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
843 nTotal += pcoin->GetAvailableCredit();
850 int64 CWallet::GetUnconfirmedBalance() const
853 CRITICAL_BLOCK(cs_wallet)
855 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
857 const CWalletTx* pcoin = &(*it).second;
858 if (pcoin->IsFinal() && pcoin->IsConfirmed())
860 nTotal += pcoin->GetAvailableCredit();
866 bool CWallet::SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
871 // List of values less than target
872 pair<int64, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
873 coinLowestLarger.first = std::numeric_limits<int64>::max();
874 coinLowestLarger.second.first = NULL;
875 vector<pair<int64, pair<const CWalletTx*,unsigned int> > > vValue;
876 int64 nTotalLower = 0;
878 CRITICAL_BLOCK(cs_wallet)
880 vector<const CWalletTx*> vCoins;
881 vCoins.reserve(mapWallet.size());
882 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
883 vCoins.push_back(&(*it).second);
884 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
886 BOOST_FOREACH(const CWalletTx* pcoin, vCoins)
888 if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
891 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
894 int nDepth = pcoin->GetDepthInMainChain();
895 if (nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs))
898 for (int i = 0; i < pcoin->vout.size(); i++)
900 if (pcoin->IsSpent(i) || !IsMine(pcoin->vout[i]))
903 int64 n = pcoin->vout[i].nValue;
908 pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin,i));
910 if (n == nTargetValue)
912 setCoinsRet.insert(coin.second);
913 nValueRet += coin.first;
916 else if (n < nTargetValue + CENT)
918 vValue.push_back(coin);
921 else if (n < coinLowestLarger.first)
923 coinLowestLarger = coin;
929 if (nTotalLower == nTargetValue || nTotalLower == nTargetValue + CENT)
931 for (int i = 0; i < vValue.size(); ++i)
933 setCoinsRet.insert(vValue[i].second);
934 nValueRet += vValue[i].first;
939 if (nTotalLower < nTargetValue + (coinLowestLarger.second.first ? CENT : 0))
941 if (coinLowestLarger.second.first == NULL)
943 setCoinsRet.insert(coinLowestLarger.second);
944 nValueRet += coinLowestLarger.first;
948 if (nTotalLower >= nTargetValue + CENT)
949 nTargetValue += CENT;
951 // Solve subset sum by stochastic approximation
952 sort(vValue.rbegin(), vValue.rend());
953 vector<char> vfIncluded;
954 vector<char> vfBest(vValue.size(), true);
955 int64 nBest = nTotalLower;
957 for (int nRep = 0; nRep < 1000 && nBest != nTargetValue; nRep++)
959 vfIncluded.assign(vValue.size(), false);
961 bool fReachedTarget = false;
962 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
964 for (int i = 0; i < vValue.size(); i++)
966 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
968 nTotal += vValue[i].first;
969 vfIncluded[i] = true;
970 if (nTotal >= nTargetValue)
972 fReachedTarget = true;
978 nTotal -= vValue[i].first;
979 vfIncluded[i] = false;
986 // If the next larger is still closer, return it
987 if (coinLowestLarger.second.first && coinLowestLarger.first - nTargetValue <= nBest - nTargetValue)
989 setCoinsRet.insert(coinLowestLarger.second);
990 nValueRet += coinLowestLarger.first;
993 for (int i = 0; i < vValue.size(); i++)
996 setCoinsRet.insert(vValue[i].second);
997 nValueRet += vValue[i].first;
1001 printf("SelectCoins() best subset: ");
1002 for (int i = 0; i < vValue.size(); i++)
1004 printf("%s ", FormatMoney(vValue[i].first).c_str());
1005 printf("total %s\n", FormatMoney(nBest).c_str());
1011 bool CWallet::SelectCoins(int64 nTargetValue, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
1013 return (SelectCoinsMinConf(nTargetValue, 1, 6, setCoinsRet, nValueRet) ||
1014 SelectCoinsMinConf(nTargetValue, 1, 1, setCoinsRet, nValueRet) ||
1015 SelectCoinsMinConf(nTargetValue, 0, 1, setCoinsRet, nValueRet));
1021 bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
1024 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1030 if (vecSend.empty() || nValue < 0)
1033 wtxNew.BindWallet(this);
1035 CRITICAL_BLOCK(cs_main)
1036 CRITICAL_BLOCK(cs_wallet)
1038 // txdb must be opened before the mapWallet lock
1041 nFeeRet = nTransactionFee;
1045 wtxNew.vout.clear();
1046 wtxNew.fFromMe = true;
1048 int64 nTotalValue = nValue + nFeeRet;
1049 double dPriority = 0;
1050 // vouts to the payees
1051 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1052 wtxNew.vout.push_back(CTxOut(s.second, s.first));
1054 // Choose coins to use
1055 set<pair<const CWalletTx*,unsigned int> > setCoins;
1057 if (!SelectCoins(nTotalValue, setCoins, nValueIn))
1059 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1061 int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
1062 dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
1065 int64 nChange = nValueIn - nValue - nFeeRet;
1066 // if sub-cent change is required, the fee must be raised to at least MIN_TX_FEE
1067 // or until nChange becomes zero
1068 // NOTE: this depends on the exact behaviour of GetMinFee
1069 if (nFeeRet < MIN_TX_FEE && nChange > 0 && nChange < CENT)
1071 int64 nMoveToFee = min(nChange, MIN_TX_FEE - nFeeRet);
1072 nChange -= nMoveToFee;
1073 nFeeRet += nMoveToFee;
1078 // Note: We use a new key here to keep it from being obvious which side is the change.
1079 // The drawback is that by not reusing a previous key, the change may be lost if a
1080 // backup is restored, if the backup doesn't have the new private key for the change.
1081 // If we reused the old key, it would be possible to add code to look for and
1082 // rediscover unknown transactions that were written with keys of ours to recover
1083 // post-backup change.
1085 // Reserve a new key pair from key pool
1086 vector<unsigned char> vchPubKey = reservekey.GetReservedKey();
1087 // assert(mapKeys.count(vchPubKey));
1089 // Fill a vout to ourself
1090 // TODO: pass in scriptChange instead of reservekey so
1091 // change transaction isn't always pay-to-bitcoin-address
1092 CScript scriptChange;
1093 scriptChange.SetBitcoinAddress(vchPubKey);
1095 // Insert change txn at random position:
1096 vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
1097 wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
1100 reservekey.ReturnKey();
1103 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1104 wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
1108 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1109 if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
1113 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK);
1114 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1116 dPriority /= nBytes;
1118 // Check that enough fee is included
1119 int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
1120 bool fAllowFree = CTransaction::AllowFree(dPriority);
1121 int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND);
1122 if (nFeeRet < max(nPayFee, nMinFee))
1124 nFeeRet = max(nPayFee, nMinFee);
1128 // Fill vtxPrev by copying from previous transactions vtxPrev
1129 wtxNew.AddSupportingTransactions(txdb);
1130 wtxNew.fTimeReceivedIsTxTime = true;
1139 bool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
1141 vector< pair<CScript, int64> > vecSend;
1142 vecSend.push_back(make_pair(scriptPubKey, nValue));
1143 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet);
1146 // Call after CreateTransaction unless you want to abort
1147 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
1149 CRITICAL_BLOCK(cs_main)
1150 CRITICAL_BLOCK(cs_wallet)
1152 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
1154 // This is only to keep the database open to defeat the auto-flush for the
1155 // duration of this scope. This is the only place where this optimization
1156 // maybe makes sense; please don't do it anywhere else.
1157 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
1159 // Take key pair from key pool so it won't be used again
1160 reservekey.KeepKey();
1162 // Add tx to wallet, because if it has change it's also ours,
1163 // otherwise just for transaction history.
1164 AddToWallet(wtxNew);
1166 // Mark old coins as spent
1167 set<CWalletTx*> setCoins;
1168 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
1170 CWalletTx &coin = mapWallet[txin.prevout.hash];
1171 coin.BindWallet(this);
1172 coin.MarkSpent(txin.prevout.n);
1174 vWalletUpdated.push_back(coin.GetHash());
1181 // Track how many getdata requests our transaction gets
1182 mapRequestCount[wtxNew.GetHash()] = 0;
1185 if (!wtxNew.AcceptToMemoryPool())
1187 // This must not fail. The transaction has already been signed and recorded.
1188 printf("CommitTransaction() : Error: Transaction not valid");
1191 wtxNew.RelayWalletTransaction();
1200 string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1202 CReserveKey reservekey(this);
1207 string strError = _("Error: Wallet locked, unable to create transaction ");
1208 printf("SendMoney() : %s", strError.c_str());
1211 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
1214 if (nValue + nFeeRequired > GetBalance())
1215 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());
1217 strError = _("Error: Transaction creation failed ");
1218 printf("SendMoney() : %s", strError.c_str());
1222 if (fAskFee && !ThreadSafeAskFee(nFeeRequired, _("Sending..."), NULL))
1225 if (!CommitTransaction(wtxNew, reservekey))
1226 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.");
1234 string CWallet::SendMoneyToBitcoinAddress(const CBitcoinAddress& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1238 return _("Invalid amount");
1239 if (nValue + nTransactionFee > GetBalance())
1240 return _("Insufficient funds");
1242 // Parse bitcoin address
1243 CScript scriptPubKey;
1244 scriptPubKey.SetBitcoinAddress(address);
1246 return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
1252 int CWallet::LoadWallet(bool& fFirstRunRet)
1256 fFirstRunRet = false;
1257 int nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
1258 if (nLoadWalletRet == DB_NEED_REWRITE)
1260 if (CDB::Rewrite(strWalletFile, "\x04pool"))
1263 // Note: can't top-up keypool here, because wallet is locked.
1264 // User will be prompted to unlock wallet the next operation
1265 // the requires a new key.
1267 nLoadWalletRet = DB_NEED_REWRITE;
1270 if (nLoadWalletRet != DB_LOAD_OK)
1271 return nLoadWalletRet;
1272 fFirstRunRet = vchDefaultKey.empty();
1274 CreateThread(ThreadFlushWalletDB, &strWalletFile);
1279 bool CWallet::SetAddressBookName(const CBitcoinAddress& address, const string& strName)
1281 mapAddressBook[address] = strName;
1284 return CWalletDB(strWalletFile).WriteName(address.ToString(), strName);
1287 bool CWallet::DelAddressBookName(const CBitcoinAddress& address)
1289 mapAddressBook.erase(address);
1292 return CWalletDB(strWalletFile).EraseName(address.ToString());
1296 void CWallet::PrintWallet(const CBlock& block)
1298 CRITICAL_BLOCK(cs_wallet)
1300 if (mapWallet.count(block.vtx[0].GetHash()))
1302 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
1303 printf(" mine: %d %d %d", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
1309 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
1311 CRITICAL_BLOCK(cs_wallet)
1313 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
1314 if (mi != mapWallet.end())
1323 bool CWallet::SetDefaultKey(const std::vector<unsigned char> &vchPubKey)
1327 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
1330 vchDefaultKey = vchPubKey;
1334 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
1336 if (!pwallet->fFileBacked)
1338 strWalletFileOut = pwallet->strWalletFile;
1343 // Mark old keypool keys as used,
1344 // and generate all new keys
1346 bool CWallet::NewKeyPool()
1348 CRITICAL_BLOCK(cs_wallet)
1350 CWalletDB walletdb(strWalletFile);
1351 BOOST_FOREACH(int64 nIndex, setKeyPool)
1352 walletdb.ErasePool(nIndex);
1358 int64 nKeys = max(GetArg("-keypool", 100), (int64)0);
1359 for (int i = 0; i < nKeys; i++)
1362 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
1363 setKeyPool.insert(nIndex);
1365 printf("CWallet::NewKeyPool wrote %"PRI64d" new keys\n", nKeys);
1370 bool CWallet::TopUpKeyPool()
1372 CRITICAL_BLOCK(cs_wallet)
1377 CWalletDB walletdb(strWalletFile);
1380 int64 nTargetSize = max(GetArg("-keypool", 100), (int64)0);
1381 while (setKeyPool.size() < nTargetSize+1)
1384 if (!setKeyPool.empty())
1385 nEnd = *(--setKeyPool.end()) + 1;
1386 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
1387 throw runtime_error("TopUpKeyPool() : writing generated key failed");
1388 setKeyPool.insert(nEnd);
1389 printf("keypool added key %"PRI64d", size=%d\n", nEnd, setKeyPool.size());
1395 void CWallet::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool)
1398 keypool.vchPubKey.clear();
1399 CRITICAL_BLOCK(cs_wallet)
1404 // Get the oldest key
1405 if(setKeyPool.empty())
1408 CWalletDB walletdb(strWalletFile);
1410 nIndex = *(setKeyPool.begin());
1411 setKeyPool.erase(setKeyPool.begin());
1412 if (!walletdb.ReadPool(nIndex, keypool))
1413 throw runtime_error("ReserveKeyFromKeyPool() : read failed");
1414 if (!HaveKey(Hash160(keypool.vchPubKey)))
1415 throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
1416 assert(!keypool.vchPubKey.empty());
1417 printf("keypool reserve %"PRI64d"\n", nIndex);
1421 int64 CWallet::AddReserveKey(const CKeyPool& keypool)
1423 CRITICAL_BLOCK(cs_main)
1424 CRITICAL_BLOCK(cs_wallet)
1426 CWalletDB walletdb(strWalletFile);
1428 int64 nIndex = 1 + *(--setKeyPool.end());
1429 if (!walletdb.WritePool(nIndex, keypool))
1430 throw runtime_error("AddReserveKey() : writing added key failed");
1431 setKeyPool.insert(nIndex);
1437 void CWallet::KeepKey(int64 nIndex)
1439 // Remove from key pool
1442 CWalletDB walletdb(strWalletFile);
1443 walletdb.ErasePool(nIndex);
1445 printf("keypool keep %"PRI64d"\n", nIndex);
1448 void CWallet::ReturnKey(int64 nIndex)
1450 // Return to key pool
1451 CRITICAL_BLOCK(cs_wallet)
1452 setKeyPool.insert(nIndex);
1453 printf("keypool return %"PRI64d"\n", nIndex);
1456 bool CWallet::GetKeyFromPool(vector<unsigned char>& result, bool fAllowReuse)
1460 CRITICAL_BLOCK(cs_wallet)
1462 ReserveKeyFromKeyPool(nIndex, keypool);
1465 if (fAllowReuse && !vchDefaultKey.empty())
1467 result = vchDefaultKey;
1470 if (IsLocked()) return false;
1471 result = GenerateNewKey();
1475 result = keypool.vchPubKey;
1480 int64 CWallet::GetOldestKeyPoolTime()
1484 ReserveKeyFromKeyPool(nIndex, keypool);
1488 return keypool.nTime;
1491 vector<unsigned char> CReserveKey::GetReservedKey()
1496 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
1498 vchPubKey = keypool.vchPubKey;
1501 printf("CReserveKey::GetReservedKey(): Warning: using default key instead of a new key, top up your keypool.");
1502 vchPubKey = pwallet->vchDefaultKey;
1505 assert(!vchPubKey.empty());
1509 void CReserveKey::KeepKey()
1512 pwallet->KeepKey(nIndex);
1517 void CReserveKey::ReturnKey()
1520 pwallet->ReturnKey(nIndex);
1525 void CWallet::GetAllReserveAddresses(set<CBitcoinAddress>& setAddress)
1529 CWalletDB walletdb(strWalletFile);
1531 CRITICAL_BLOCK(cs_main)
1532 CRITICAL_BLOCK(cs_wallet)
1533 BOOST_FOREACH(const int64& id, setKeyPool)
1536 if (!walletdb.ReadPool(id, keypool))
1537 throw runtime_error("GetAllReserveKeyHashes() : read failed");
1538 CBitcoinAddress address(keypool.vchPubKey);
1539 assert(!keypool.vchPubKey.empty());
1540 if (!HaveKey(address))
1541 throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
1542 setAddress.insert(address);