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.
10 #include "ui_interface.h"
13 #include "coincontrol.h"
14 #include <boost/algorithm/string/replace.hpp>
15 #include <openssl/bio.h>
20 extern int64_t nReserveBalance;
22 //////////////////////////////////////////////////////////////////////////////
27 struct CompareValueOnly
29 bool operator()(const pair<int64_t, pair<const CWalletTx*, unsigned int> >& t1,
30 const pair<int64_t, pair<const CWalletTx*, unsigned int> >& t2) const
32 return t1.first < t2.first;
36 CPubKey CWallet::GenerateNewKey()
38 bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
42 key.MakeNewKey(fCompressed);
44 // Compressed public keys were introduced in version 0.6.0
46 SetMinVersion(FEATURE_COMPRPUBKEY);
48 CPubKey pubkey = key.GetPubKey();
50 // Create new metadata
51 int64_t nCreationTime = GetTime();
52 mapKeyMetadata[CBitcoinAddress(pubkey.GetID())] = CKeyMetadata(nCreationTime);
53 if (!nTimeFirstKey || nCreationTime < nTimeFirstKey)
54 nTimeFirstKey = nCreationTime;
57 throw std::runtime_error("CWallet::GenerateNewKey() : AddKey failed");
58 return key.GetPubKey();
61 CMalleableKeyView CWallet::GenerateNewMalleableKey()
65 // Compressed public keys were introduced in version 0.6.0
66 SetMinVersion(FEATURE_MALLKEY);
70 const CMalleableKeyView &keyView(mKey);
72 // Create new metadata
73 int64_t nCreationTime = GetTime();
74 mapKeyMetadata[CBitcoinAddress(keyView.GetMalleablePubKey())] = CKeyMetadata(nCreationTime);
75 if (!nTimeFirstKey || nCreationTime < nTimeFirstKey)
76 nTimeFirstKey = nCreationTime;
79 throw std::runtime_error("CWallet::GenerateNewMalleableKey() : AddKey failed");
80 return CMalleableKeyView(mKey);
83 bool CWallet::AddKey(const CKey& key)
85 CPubKey pubkey = key.GetPubKey();
86 if (!CCryptoKeyStore::AddKey(key))
91 return CWalletDB(strWalletFile).WriteKey(pubkey, key.GetPrivKey(), mapKeyMetadata[CBitcoinAddress(pubkey.GetID())]);
95 bool CWallet::AddKey(const CMalleableKey& mKey)
97 CMalleableKeyView keyView = CMalleableKeyView(mKey);
98 CSecret vchSecretH = mKey.GetSecretH();
99 if (!CCryptoKeyStore::AddMalleableKey(keyView, vchSecretH))
104 return CWalletDB(strWalletFile).WriteMalleableKey(keyView, vchSecretH, mapKeyMetadata[CBitcoinAddress(keyView.GetMalleablePubKey())]);
108 bool CWallet::AddCryptedMalleableKey(const CMalleableKeyView& keyView, const std::vector<unsigned char> &vchCryptedSecretH)
110 if (!CCryptoKeyStore::AddCryptedMalleableKey(keyView, vchCryptedSecretH))
118 CBitcoinAddress addr(keyView.GetMalleablePubKey());
119 if (pwalletdbEncryption)
120 return pwalletdbEncryption->WriteCryptedMalleableKey(keyView, vchCryptedSecretH, mapKeyMetadata[addr]);
122 return CWalletDB(strWalletFile).WriteCryptedMalleableKey(keyView, vchCryptedSecretH, mapKeyMetadata[addr]);
128 bool CWallet::AddCryptedKey(const CPubKey &vchPubKey, const vector<unsigned char> &vchCryptedSecret)
130 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
133 // check if we need to remove from watch-only
135 script.SetDestination(vchPubKey.GetID());
136 if (HaveWatchOnly(script))
137 RemoveWatchOnly(script);
143 CBitcoinAddress addr(vchPubKey.GetID());
144 if (pwalletdbEncryption)
145 return pwalletdbEncryption->WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[addr]);
147 return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[addr]);
152 bool CWallet::LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &meta)
154 if (meta.nCreateTime && (!nTimeFirstKey || meta.nCreateTime < nTimeFirstKey))
155 nTimeFirstKey = meta.nCreateTime;
157 mapKeyMetadata[CBitcoinAddress(pubkey.GetID())] = meta;
161 bool CWallet::LoadKeyMetadata(const CMalleableKeyView &keyView, const CKeyMetadata &metadata)
163 if (metadata.nCreateTime && (!nTimeFirstKey || metadata.nCreateTime < nTimeFirstKey))
164 nTimeFirstKey = metadata.nCreateTime;
166 mapKeyMetadata[CBitcoinAddress(keyView.GetMalleablePubKey())] = metadata;
170 bool CWallet::AddCScript(const CScript& redeemScript)
172 if (!CCryptoKeyStore::AddCScript(redeemScript))
176 return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript);
179 bool CWallet::LoadCScript(const CScript& redeemScript)
181 /* A sanity check was added in commit 5ed0a2b to avoid adding redeemScripts
182 * that never can be redeemed. However, old wallets may still contain
183 * these. Do not add them to the wallet and warn. */
184 if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
186 std::string strAddr = CBitcoinAddress(redeemScript.GetID()).ToString();
187 printf("LoadCScript() : Warning: This wallet contains a redeemScript of size %" PRIszu " which exceeds maximum size %i thus can never be redeemed. Do not use address %s.\n",
188 redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr.c_str());
192 return CCryptoKeyStore::AddCScript(redeemScript);
196 bool CWallet::AddWatchOnly(const CScript &dest)
198 if (!CCryptoKeyStore::AddWatchOnly(dest))
200 nTimeFirstKey = 1; // No birthday information for watch-only keys.
201 NotifyWatchonlyChanged(true);
204 return CWalletDB(strWalletFile).WriteWatchOnly(dest);
207 bool CWallet::RemoveWatchOnly(const CScript &dest)
210 if (!CCryptoKeyStore::RemoveWatchOnly(dest))
212 if (!HaveWatchOnly())
213 NotifyWatchonlyChanged(false);
215 if (!CWalletDB(strWalletFile).EraseWatchOnly(dest))
221 bool CWallet::LoadWatchOnly(const CScript &dest)
223 return CCryptoKeyStore::AddWatchOnly(dest);
226 // ppcoin: optional setting to unlock wallet for block minting only;
227 // serves to disable the trivial sendmoney when OS account compromised
228 bool fWalletUnlockMintOnly = false;
230 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
236 CKeyingMaterial vMasterKey;
240 BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
242 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
244 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
246 if (CCryptoKeyStore::Unlock(vMasterKey))
253 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
255 bool fWasLocked = IsLocked();
262 CKeyingMaterial vMasterKey;
263 BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
265 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
267 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
269 if (CCryptoKeyStore::Unlock(vMasterKey))
271 int64_t nStartTime = GetTimeMillis();
272 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
273 double nFirstMultiplier = 1e2 / (GetTimeMillis() - nStartTime);
274 pMasterKey.second.nDeriveIterations = (uint32_t)(pMasterKey.second.nDeriveIterations *nFirstMultiplier);
276 nStartTime = GetTimeMillis();
277 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
278 double nSecondMultiplier = 1e2 / (GetTimeMillis() - nStartTime);
279 pMasterKey.second.nDeriveIterations = (uint32_t)((pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * nSecondMultiplier) / 2);
281 if (pMasterKey.second.nDeriveIterations < 25000)
282 pMasterKey.second.nDeriveIterations = 25000;
284 printf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
286 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
288 if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
290 CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
301 void CWallet::SetBestChain(const CBlockLocator& loc)
303 CWalletDB walletdb(strWalletFile);
304 walletdb.WriteBestBlock(loc);
307 // This class implements an addrIncoming entry that causes pre-0.4
308 // clients to crash on startup if reading a private-key-encrypted wallet.
309 class CCorruptAddress
314 if (nType & SER_DISK)
319 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
321 if (nWalletVersion >= nVersion)
324 // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
325 if (fExplicit && nVersion > nWalletMaxVersion)
326 nVersion = FEATURE_LATEST;
328 nWalletVersion = nVersion;
330 if (nVersion > nWalletMaxVersion)
331 nWalletMaxVersion = nVersion;
335 CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile);
336 if (nWalletVersion > 40000)
337 pwalletdb->WriteMinVersion(nWalletVersion);
345 bool CWallet::SetMaxVersion(int nVersion)
347 // cannot downgrade below current version
348 if (nWalletVersion > nVersion)
351 nWalletMaxVersion = nVersion;
356 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
361 CKeyingMaterial vMasterKey;
362 RandAddSeedPerfmon();
364 vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
365 RAND_bytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
367 CMasterKey kMasterKey;
369 RandAddSeedPerfmon();
370 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
371 RAND_bytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
374 int64_t nStartTime = GetTimeMillis();
375 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
376 int64_t nDivider = GetTimeMillis() - nStartTime;
377 kMasterKey.nDeriveIterations = (uint32_t)(25e5 / (double)(nDivider));
379 nStartTime = GetTimeMillis();
380 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
381 double nMultiplier = 1e2 / (GetTimeMillis() - nStartTime);
382 kMasterKey.nDeriveIterations = (uint32_t)((kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * nMultiplier) / 2);
384 if (kMasterKey.nDeriveIterations < 25000)
385 kMasterKey.nDeriveIterations = 25000;
387 printf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
389 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
391 if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
396 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
399 pwalletdbEncryption = new CWalletDB(strWalletFile);
400 if (!pwalletdbEncryption->TxnBegin())
402 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
405 if (!EncryptKeys(vMasterKey))
408 pwalletdbEncryption->TxnAbort();
409 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.
412 // Encryption was introduced in version 0.4.0
413 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
417 if (!pwalletdbEncryption->TxnCommit())
418 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.
420 delete pwalletdbEncryption;
421 pwalletdbEncryption = NULL;
425 Unlock(strWalletPassphrase);
429 // Need to completely rewrite the wallet file; if we don't, bdb might keep
430 // bits of the unencrypted private key in slack space in the database file.
431 CDB::Rewrite(strWalletFile);
434 NotifyStatusChanged(this);
439 bool CWallet::DecryptWallet(const SecureString& strWalletPassphrase)
445 CKeyingMaterial vMasterKey;
449 BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
451 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
453 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
455 if (!CCryptoKeyStore::Unlock(vMasterKey))
461 pwalletdbDecryption = new CWalletDB(strWalletFile);
462 if (!pwalletdbDecryption->TxnBegin())
466 if (!DecryptKeys(vMasterKey))
469 pwalletdbDecryption->TxnAbort();
470 exit(1); //We now probably have half of our keys decrypted in memory, and half not...die and let the user reload their encrypted wallet.
475 // Overwrite crypted keys
476 KeyMap::const_iterator mi = mapKeys.begin();
477 while (mi != mapKeys.end())
480 key.SetSecret((*mi).second.first, (*mi).second.second);
481 pwalletdbDecryption->EraseCryptedKey(key.GetPubKey());
482 pwalletdbDecryption->WriteKey(key.GetPubKey(), key.GetPrivKey(), mapKeyMetadata[CBitcoinAddress(mi->first)]);
486 MalleableKeyMap::const_iterator mi2 = mapMalleableKeys.begin();
487 while (mi2 != mapMalleableKeys.end())
489 const CSecret &vchSecretH = mi2->second;
490 const CMalleableKeyView &keyView = mi2->first;
491 pwalletdbDecryption->EraseCryptedMalleableKey(keyView);
492 pwalletdbDecryption->WriteMalleableKey(keyView, vchSecretH, mapKeyMetadata[CBitcoinAddress(keyView.GetMalleablePubKey())]);
497 MasterKeyMap::const_iterator mk = mapMasterKeys.begin();
498 while (mk != mapMasterKeys.end())
500 pwalletdbDecryption->EraseMasterKey((*mk).first);
504 if (!pwalletdbDecryption->TxnCommit())
505 exit(1); //We now have keys decrypted in memory, but no on disk...die to avoid confusion and let the user reload their encrypted wallet.
507 delete pwalletdbDecryption;
508 pwalletdbDecryption = NULL;
511 // Need to completely rewrite the wallet file; if we don't, bdb might keep
512 // encrypted private keys in the database file which can be a reason of consistency issues.
513 CDB::Rewrite(strWalletFile);
515 NotifyStatusChanged(this);
520 bool CWallet::GetPEM(const CKeyID &keyID, const std::string &fileName, const SecureString &strPassKey) const
522 BIO *pemOut = BIO_new_file(fileName.c_str(), "w");
524 return error("GetPEM() : failed to create file %s\n", fileName.c_str());
526 if (!GetKey(keyID, key))
527 return error("GetPEM() : failed to get key for address=%s\n", CBitcoinAddress(keyID).ToString().c_str());
528 bool result = key.WritePEM(pemOut, strPassKey);
533 int64_t CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
535 int64_t nRet = nOrderPosNext++;
537 pwalletdb->WriteOrderPosNext(nOrderPosNext);
539 CWalletDB(strWalletFile).WriteOrderPosNext(nOrderPosNext);
544 CWallet::TxItems CWallet::OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount)
546 CWalletDB walletdb(strWalletFile);
548 // First: get all CWalletTx and CAccountingEntry into a sorted-by-order multimap.
551 // Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry
552 // would make this much faster for applications that do this a lot.
553 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
555 CWalletTx* wtx = &((*it).second);
556 txOrdered.insert(make_pair(wtx->nOrderPos, TxPair(wtx, (CAccountingEntry*)0)));
559 walletdb.ListAccountCreditDebit(strAccount, acentries);
560 BOOST_FOREACH(CAccountingEntry& entry, acentries)
562 txOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
568 void CWallet::WalletUpdateSpent(const CTransaction &tx, bool fBlock)
570 // Anytime a signature is successfully verified, it's proof the outpoint is spent.
571 // Update the wallet spent flag if it doesn't know due to wallet.dat being
572 // restored from backup or the user making copies of wallet.dat.
575 BOOST_FOREACH(const CTxIn& txin, tx.vin)
577 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
578 if (mi != mapWallet.end())
580 CWalletTx& wtx = (*mi).second;
581 if (txin.prevout.n >= wtx.vout.size())
582 printf("WalletUpdateSpent: bad wtx %s\n", wtx.GetHash().ToString().c_str());
583 else if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n]))
585 printf("WalletUpdateSpent found spent coin %snvc %s\n", FormatMoney(wtx.GetCredit(MINE_ALL)).c_str(), wtx.GetHash().ToString().c_str());
586 wtx.MarkSpent(txin.prevout.n);
588 NotifyTransactionChanged(this, txin.prevout.hash, CT_UPDATED);
589 vMintingWalletUpdated.push_back(txin.prevout.hash);
596 uint256 hash = tx.GetHash();
597 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hash);
598 CWalletTx& wtx = (*mi).second;
600 BOOST_FOREACH(const CTxOut& txout, tx.vout)
604 wtx.MarkUnspent(&txout - &tx.vout[0]);
606 NotifyTransactionChanged(this, hash, CT_UPDATED);
607 vMintingWalletUpdated.push_back(hash);
615 void CWallet::MarkDirty()
619 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
620 item.second.MarkDirty();
624 bool CWallet::AddToWallet(const CWalletTx& wtxIn)
626 uint256 hash = wtxIn.GetHash();
629 // Inserts only if not already there, returns tx inserted or tx found
630 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
631 CWalletTx& wtx = (*ret.first).second;
632 wtx.BindWallet(this);
633 bool fInsertedNew = ret.second;
636 wtx.nTimeReceived = GetAdjustedTime();
637 wtx.nOrderPos = IncOrderPosNext();
639 wtx.nTimeSmart = wtx.nTimeReceived;
640 if (wtxIn.hashBlock != 0)
642 if (mapBlockIndex.count(wtxIn.hashBlock))
644 unsigned int latestNow = wtx.nTimeReceived;
645 unsigned int latestEntry = 0;
647 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
648 int64_t latestTolerated = latestNow + 300;
649 std::list<CAccountingEntry> acentries;
650 TxItems txOrdered = OrderedTxItems(acentries);
651 for (TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
653 CWalletTx *const pwtx = (*it).second.first;
656 CAccountingEntry *const pacentry = (*it).second.second;
660 nSmartTime = pwtx->nTimeSmart;
662 nSmartTime = pwtx->nTimeReceived;
665 nSmartTime = pacentry->nTime;
666 if (nSmartTime <= latestTolerated)
668 latestEntry = nSmartTime;
669 if (nSmartTime > latestNow)
670 latestNow = nSmartTime;
676 unsigned int& blocktime = mapBlockIndex[wtxIn.hashBlock]->nTime;
677 wtx.nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
680 printf("AddToWallet() : found %s in block %s not in index\n",
681 wtxIn.GetHash().ToString().substr(0,10).c_str(),
682 wtxIn.hashBlock.ToString().c_str());
686 bool fUpdated = false;
690 if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
692 wtx.hashBlock = wtxIn.hashBlock;
695 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
697 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
698 wtx.nIndex = wtxIn.nIndex;
701 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
703 wtx.fFromMe = wtxIn.fFromMe;
706 fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);
710 printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
713 if (fInsertedNew || fUpdated)
714 if (!wtx.WriteToDisk())
717 // If default receiving address gets used, replace it with a new one
718 CScript scriptDefaultKey;
719 scriptDefaultKey.SetDestination(vchDefaultKey.GetID());
720 BOOST_FOREACH(const CTxOut& txout, wtx.vout)
722 if (txout.scriptPubKey == scriptDefaultKey)
724 CPubKey newDefaultKey;
725 if (GetKeyFromPool(newDefaultKey, false))
727 SetDefaultKey(newDefaultKey);
728 SetAddressBookName(vchDefaultKey.GetID(), "");
733 // since AddToWallet is called directly for self-originating transactions, check for consumption of own coins
734 WalletUpdateSpent(wtx, (wtxIn.hashBlock != 0));
736 // Notify UI of new or updated transaction
737 NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
738 vMintingWalletUpdated.push_back(hash);
739 // notify an external script when a wallet transaction comes in or is updated
740 std::string strCmd = GetArg("-walletnotify", "");
742 if ( !strCmd.empty())
744 boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
745 boost::thread t(runCommand, strCmd); // thread runs free
752 // Add a transaction to the wallet, or update it.
753 // pblock is optional, but should be provided if the transaction is known to be in a block.
754 // If fUpdate is true, existing transactions will be updated.
755 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fFindBlock)
757 uint256 hash = tx.GetHash();
760 bool fExisted = mapWallet.count(hash) != 0;
761 if (fExisted && !fUpdate) return false;
762 if (fExisted || IsMine(tx) || IsFromMe(tx))
764 CWalletTx wtx(this,tx);
765 // Get merkle branch if transaction was found in a block
767 wtx.SetMerkleBranch(pblock);
768 return AddToWallet(wtx);
771 WalletUpdateSpent(tx);
776 bool CWallet::EraseFromWallet(uint256 hash)
782 if (mapWallet.erase(hash))
783 CWalletDB(strWalletFile).EraseTx(hash);
789 isminetype CWallet::IsMine(const CTxIn &txin) const
793 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
794 if (mi != mapWallet.end())
796 const CWalletTx& prev = (*mi).second;
797 if (txin.prevout.n < prev.vout.size())
798 return IsMine(prev.vout[txin.prevout.n]);
804 int64_t CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
808 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
809 if (mi != mapWallet.end())
811 const CWalletTx& prev = (*mi).second;
812 if (txin.prevout.n < prev.vout.size())
813 if (IsMine(prev.vout[txin.prevout.n]) & filter)
814 return prev.vout[txin.prevout.n].nValue;
820 bool CWallet::IsChange(const CTxOut& txout) const
822 // TODO: fix handling of 'change' outputs. The assumption is that any
823 // payment to a script that is ours, but isn't in the address book
824 // is change. That assumption is likely to break when we implement multisignature
825 // wallets that return change back into a multi-signature-protected address;
826 // a better way of identifying which outputs are 'the send' and which are
827 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
828 // which output, if any, was change).
829 if (::IsMine(*this, txout.scriptPubKey))
831 CTxDestination address;
832 if (!ExtractDestination(txout.scriptPubKey, address))
836 if (!mapAddressBook.count(address))
842 int64_t CWalletTx::GetTxTime() const
847 int CWalletTx::GetRequestCount() const
849 // Returns -1 if it wasn't being tracked
852 LOCK(pwallet->cs_wallet);
853 if (IsCoinBase() || IsCoinStake())
858 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
859 if (mi != pwallet->mapRequestCount.end())
860 nRequests = (*mi).second;
865 // Did anyone request this transaction?
866 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
867 if (mi != pwallet->mapRequestCount.end())
869 nRequests = (*mi).second;
871 // How about the block it's in?
872 if (nRequests == 0 && hashBlock != 0)
874 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
875 if (mi != pwallet->mapRequestCount.end())
876 nRequests = (*mi).second;
878 nRequests = 1; // If it's in someone else's block it must have got out
886 void CWalletTx::GetAmounts(int64_t& nGeneratedImmature, int64_t& nGeneratedMature, list<pair<CBitcoinAddress, int64_t> >& listReceived,
887 list<pair<CBitcoinAddress, int64_t> >& listSent, int64_t& nFee, string& strSentAccount, const isminefilter& filter) const
889 nGeneratedImmature = nGeneratedMature = nFee = 0;
890 listReceived.clear();
892 strSentAccount = strFromAccount;
894 if (IsCoinBase() || IsCoinStake())
896 if (GetBlocksToMaturity() > 0)
897 nGeneratedImmature = pwallet->GetCredit(*this, filter);
899 nGeneratedMature = GetCredit(filter);
904 int64_t nDebit = GetDebit(filter);
905 if (nDebit > 0) // debit>0 means we signed/sent this transaction
907 int64_t nValueOut = GetValueOut();
908 nFee = nDebit - nValueOut;
912 BOOST_FOREACH(const CTxOut& txout, vout)
914 isminetype fIsMine = pwallet->IsMine(txout);
915 // Only need to handle txouts if AT LEAST one of these is true:
916 // 1) they debit from us (sent)
917 // 2) the output is to us (received)
920 // Don't report 'change' txouts
921 if (pwallet->IsChange(txout))
924 else if (!(fIsMine & filter))
927 // In either case, we need to get the destination address
928 CBitcoinAddress address;
929 if (!ExtractAddress(*pwallet, txout.scriptPubKey, address))
931 printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
932 this->GetHash().ToString().c_str());
933 address = CBitcoinAddress();
936 // If we are debited by the transaction, add the output as a "sent" entry
938 listSent.push_back(make_pair(address, txout.nValue));
940 // If we are receiving the output, add it as a "received" entry
941 if (fIsMine & filter)
942 listReceived.push_back(make_pair(address, txout.nValue));
947 void CWalletTx::GetAccountAmounts(const string& strAccount, int64_t& nGenerated, int64_t& nReceived,
948 int64_t& nSent, int64_t& nFee, const isminefilter& filter) const
950 nGenerated = nReceived = nSent = nFee = 0;
952 int64_t allGeneratedImmature, allGeneratedMature, allFee;
953 allGeneratedImmature = allGeneratedMature = allFee = 0;
954 string strSentAccount;
955 list<pair<CBitcoinAddress, int64_t> > listReceived;
956 list<pair<CBitcoinAddress, int64_t> > listSent;
957 GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount, filter);
959 if (strAccount.empty())
960 nGenerated = allGeneratedMature;
961 if (strAccount == strSentAccount)
963 BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress,int64_t)& s, listSent)
968 LOCK(pwallet->cs_wallet);
969 BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress,int64_t)& r, listReceived)
971 if (pwallet->mapAddressBook.count(r.first))
973 map<CBitcoinAddress, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);
974 if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)
975 nReceived += r.second;
977 else if (strAccount.empty())
979 nReceived += r.second;
985 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
989 const int COPY_DEPTH = 3;
990 if (SetMerkleBranch() < COPY_DEPTH)
992 vector<uint256> vWorkQueue;
993 BOOST_FOREACH(const CTxIn& txin, vin)
994 vWorkQueue.push_back(txin.prevout.hash);
996 // This critsect is OK because txdb is already open
998 LOCK(pwallet->cs_wallet);
999 map<uint256, const CMerkleTx*> mapWalletPrev;
1000 set<uint256> setAlreadyDone;
1001 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
1003 uint256 hash = vWorkQueue[i];
1004 if (setAlreadyDone.count(hash))
1006 setAlreadyDone.insert(hash);
1009 map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
1010 if (mi != pwallet->mapWallet.end())
1013 BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev)
1014 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
1016 else if (mapWalletPrev.count(hash))
1018 tx = *mapWalletPrev[hash];
1020 else if (!fClient && txdb.ReadDiskTx(hash, tx))
1026 printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
1030 int nDepth = tx.SetMerkleBranch();
1031 vtxPrev.push_back(tx);
1033 if (nDepth < COPY_DEPTH)
1035 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1036 vWorkQueue.push_back(txin.prevout.hash);
1042 reverse(vtxPrev.begin(), vtxPrev.end());
1045 bool CWalletTx::WriteToDisk()
1047 return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
1050 // Scan the block chain (starting in pindexStart) for transactions
1051 // from or to us. If fUpdate is true, found transactions that already
1052 // exist in the wallet will be updated.
1053 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
1057 CBlockIndex* pindex = pindexStart;
1063 block.ReadFromDisk(pindex, true);
1064 BOOST_FOREACH(CTransaction& tx, block.vtx)
1066 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
1069 pindex = pindex->pnext;
1075 int CWallet::ScanForWalletTransaction(const uint256& hashTx)
1078 tx.ReadFromDisk(COutPoint(hashTx, 0));
1079 if (AddToWalletIfInvolvingMe(tx, NULL, true, true))
1084 void CWallet::ReacceptWalletTransactions()
1087 bool fRepeat = true;
1092 vector<CDiskTxPos> vMissingTx;
1093 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1095 CWalletTx& wtx = item.second;
1096 if ((wtx.IsCoinBase() && wtx.IsSpent(0)) || (wtx.IsCoinStake() && wtx.IsSpent(1)))
1100 bool fUpdated = false;
1101 if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
1103 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
1104 if (txindex.vSpent.size() != wtx.vout.size())
1106 printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %" PRIszu " != wtx.vout.size() %" PRIszu "\n", txindex.vSpent.size(), wtx.vout.size());
1109 for (unsigned int i = 0; i < txindex.vSpent.size(); i++)
1113 if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i]))
1117 vMissingTx.push_back(txindex.vSpent[i]);
1122 printf("ReacceptWalletTransactions found spent coin %snvc %s\n", FormatMoney(wtx.GetCredit(MINE_ALL)).c_str(), wtx.GetHash().ToString().c_str());
1129 // Re-accept any txes of ours that aren't already in a block
1130 if (!(wtx.IsCoinBase() || wtx.IsCoinStake()))
1131 wtx.AcceptWalletTransaction(txdb, false);
1134 if (!vMissingTx.empty())
1136 // TODO: optimize this to scan just part of the block chain?
1137 if (ScanForWalletTransactions(pindexGenesisBlock))
1138 fRepeat = true; // Found missing transactions: re-do re-accept.
1143 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
1145 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
1147 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
1149 uint256 hash = tx.GetHash();
1150 if (!txdb.ContainsTx(hash))
1151 RelayTransaction((CTransaction)tx, hash);
1154 if (!(IsCoinBase() || IsCoinStake()))
1156 uint256 hash = GetHash();
1157 if (!txdb.ContainsTx(hash))
1159 printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
1160 RelayTransaction((CTransaction)*this, hash);
1165 void CWalletTx::RelayWalletTransaction()
1168 RelayWalletTransaction(txdb);
1171 void CWallet::ResendWalletTransactions(bool fForceResend)
1173 if (!fForceResend) {
1174 // Do this infrequently and randomly to avoid giving away
1175 // that these are our transactions.
1176 static int64_t nNextTime = GetRand(GetTime() + 30 * 60);
1177 if (GetTime() < nNextTime)
1179 bool fFirst = (nNextTime == 0);
1180 nNextTime = GetTime() + GetRand(30 * 60);
1184 // Only do it if there's been a new block since last time
1185 static int64_t nLastTime = 0;
1186 if (nTimeBestReceived < nLastTime)
1188 nLastTime = GetTime();
1191 // Rebroadcast any of our txes that aren't in a block yet
1192 printf("ResendWalletTransactions()\n");
1196 // Sort them in chronological order
1197 multimap<unsigned int, CWalletTx*> mapSorted;
1198 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1200 CWalletTx& wtx = item.second;
1201 // Don't rebroadcast until it's had plenty of time that
1202 // it should have gotten in already by now.
1203 if (fForceResend || nTimeBestReceived - (int64_t)wtx.nTimeReceived > 5 * 60)
1204 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
1206 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
1208 CWalletTx& wtx = *item.second;
1209 if (wtx.CheckTransaction())
1210 wtx.RelayWalletTransaction(txdb);
1212 printf("ResendWalletTransactions() : CheckTransaction failed for transaction %s\n", wtx.GetHash().ToString().c_str());
1222 //////////////////////////////////////////////////////////////////////////////
1228 int64_t CWallet::GetBalance() const
1233 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1235 const CWalletTx* pcoin = &(*it).second;
1236 if (pcoin->IsTrusted())
1237 nTotal += pcoin->GetAvailableCredit();
1244 int64_t CWallet::GetWatchOnlyBalance() const
1249 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1251 const CWalletTx* pcoin = &(*it).second;
1252 if (pcoin->IsTrusted())
1253 nTotal += pcoin->GetAvailableWatchCredit();
1260 int64_t CWallet::GetUnconfirmedBalance() const
1265 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1267 const CWalletTx* pcoin = &(*it).second;
1268 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
1269 nTotal += pcoin->GetAvailableCredit();
1275 int64_t CWallet::GetUnconfirmedWatchOnlyBalance() const
1280 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1282 const CWalletTx* pcoin = &(*it).second;
1283 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
1284 nTotal += pcoin->GetAvailableWatchCredit();
1290 int64_t CWallet::GetImmatureBalance() const
1295 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1297 const CWalletTx* pcoin = &(*it).second;
1298 nTotal += pcoin->GetImmatureCredit();
1304 int64_t CWallet::GetImmatureWatchOnlyBalance() const
1309 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1311 const CWalletTx* pcoin = &(*it).second;
1312 nTotal += pcoin->GetImmatureWatchOnlyCredit();
1318 // populate vCoins with vector of spendable COutputs
1319 void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl) const
1325 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1327 const CWalletTx* pcoin = &(*it).second;
1329 if (!pcoin->IsFinal())
1332 if (fOnlyConfirmed && !pcoin->IsTrusted())
1335 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
1338 if(pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0)
1341 for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
1342 isminetype mine = IsMine(pcoin->vout[i]);
1343 if (!(pcoin->IsSpent(i)) && mine != MINE_NO &&
1344 pcoin->vout[i].nValue >= nMinimumInputValue &&
1345 (!coinControl || !coinControl->HasSelected() || coinControl->IsSelected((*it).first, i)))
1347 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain(), mine == MINE_SPENDABLE));
1354 void CWallet::AvailableCoinsMinConf(vector<COutput>& vCoins, int nConf, int64_t nMinValue, int64_t nMaxValue) const
1360 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1362 const CWalletTx* pcoin = &(*it).second;
1364 if (!pcoin->IsFinal())
1367 if(pcoin->GetDepthInMainChain() < nConf)
1370 for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
1371 isminetype mine = IsMine(pcoin->vout[i]);
1373 // ignore coin if it was already spent or we don't own it
1374 if (pcoin->IsSpent(i) || mine == MINE_NO)
1377 // if coin value is between required limits then add new item to vector
1378 if (pcoin->vout[i].nValue >= nMinValue && pcoin->vout[i].nValue < nMaxValue)
1379 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain(), mine == MINE_SPENDABLE));
1385 static void ApproximateBestSubset(vector<pair<int64_t, pair<const CWalletTx*,unsigned int> > >vValue, int64_t nTotalLower, int64_t nTargetValue,
1386 vector<char>& vfBest, int64_t& nBest, int iterations = 1000)
1388 vector<char> vfIncluded;
1390 vfBest.assign(vValue.size(), true);
1391 nBest = nTotalLower;
1393 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
1395 vfIncluded.assign(vValue.size(), false);
1397 bool fReachedTarget = false;
1398 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
1400 for (unsigned int i = 0; i < vValue.size(); i++)
1402 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
1404 nTotal += vValue[i].first;
1405 vfIncluded[i] = true;
1406 if (nTotal >= nTargetValue)
1408 fReachedTarget = true;
1412 vfBest = vfIncluded;
1414 nTotal -= vValue[i].first;
1415 vfIncluded[i] = false;
1423 int64_t CWallet::GetStake() const
1427 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1429 const CWalletTx* pcoin = &(*it).second;
1430 if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1431 nTotal += CWallet::GetCredit(*pcoin, MINE_ALL);
1436 int64_t CWallet::GetWatchOnlyStake() const
1440 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1442 const CWalletTx* pcoin = &(*it).second;
1443 if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1444 nTotal += CWallet::GetCredit(*pcoin, MINE_WATCH_ONLY);
1449 int64_t CWallet::GetNewMint() const
1453 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1455 const CWalletTx* pcoin = &(*it).second;
1456 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1457 nTotal += CWallet::GetCredit(*pcoin, MINE_ALL);
1462 int64_t CWallet::GetWatchOnlyNewMint() const
1466 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1468 const CWalletTx* pcoin = &(*it).second;
1469 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1470 nTotal += CWallet::GetCredit(*pcoin, MINE_WATCH_ONLY);
1475 bool CWallet::SelectCoinsMinConf(int64_t nTargetValue, unsigned int nSpendTime, int nConfMine, int nConfTheirs, vector<COutput> vCoins, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64_t& nValueRet) const
1477 setCoinsRet.clear();
1480 // List of values less than target
1481 pair<int64_t, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
1482 coinLowestLarger.first = std::numeric_limits<int64_t>::max();
1483 coinLowestLarger.second.first = NULL;
1484 vector<pair<int64_t, pair<const CWalletTx*,unsigned int> > > vValue;
1485 int64_t nTotalLower = 0;
1487 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
1489 BOOST_FOREACH(const COutput &output, vCoins)
1491 if (!output.fSpendable)
1494 const CWalletTx *pcoin = output.tx;
1496 if (output.nDepth < (pcoin->IsFromMe(MINE_ALL) ? nConfMine : nConfTheirs))
1501 // Follow the timestamp rules
1502 if (pcoin->nTime > nSpendTime)
1505 int64_t n = pcoin->vout[i].nValue;
1507 pair<int64_t,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1509 if (n == nTargetValue)
1511 setCoinsRet.insert(coin.second);
1512 nValueRet += coin.first;
1515 else if (n < nTargetValue + CENT)
1517 vValue.push_back(coin);
1520 else if (n < coinLowestLarger.first)
1522 coinLowestLarger = coin;
1526 if (nTotalLower == nTargetValue)
1528 for (unsigned int i = 0; i < vValue.size(); ++i)
1530 setCoinsRet.insert(vValue[i].second);
1531 nValueRet += vValue[i].first;
1536 if (nTotalLower < nTargetValue)
1538 if (coinLowestLarger.second.first == NULL)
1540 setCoinsRet.insert(coinLowestLarger.second);
1541 nValueRet += coinLowestLarger.first;
1545 // Solve subset sum by stochastic approximation
1546 sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
1547 vector<char> vfBest;
1550 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);
1551 if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT)
1552 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000);
1554 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
1555 // or the next bigger coin is closer), return the bigger coin
1556 if (coinLowestLarger.second.first &&
1557 ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest))
1559 setCoinsRet.insert(coinLowestLarger.second);
1560 nValueRet += coinLowestLarger.first;
1563 for (unsigned int i = 0; i < vValue.size(); i++)
1566 setCoinsRet.insert(vValue[i].second);
1567 nValueRet += vValue[i].first;
1570 if (fDebug && GetBoolArg("-printpriority"))
1573 printf("SelectCoins() best subset: ");
1574 for (unsigned int i = 0; i < vValue.size(); i++)
1576 printf("%s ", FormatMoney(vValue[i].first).c_str());
1577 printf("total %s\n", FormatMoney(nBest).c_str());
1584 bool CWallet::SelectCoins(int64_t nTargetValue, unsigned int nSpendTime, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64_t& nValueRet, const CCoinControl* coinControl) const
1586 vector<COutput> vCoins;
1587 AvailableCoins(vCoins, true, coinControl);
1589 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
1590 if (coinControl && coinControl->HasSelected())
1592 BOOST_FOREACH(const COutput& out, vCoins)
1596 nValueRet += out.tx->vout[out.i].nValue;
1597 setCoinsRet.insert(make_pair(out.tx, out.i));
1599 return (nValueRet >= nTargetValue);
1602 return (SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 6, vCoins, setCoinsRet, nValueRet) ||
1603 SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 1, vCoins, setCoinsRet, nValueRet) ||
1604 SelectCoinsMinConf(nTargetValue, nSpendTime, 0, 1, vCoins, setCoinsRet, nValueRet));
1607 // Select some coins without random shuffle or best subset approximation
1608 bool CWallet::SelectCoinsSimple(int64_t nTargetValue, int64_t nMinValue, int64_t nMaxValue, unsigned int nSpendTime, int nMinConf, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64_t& nValueRet) const
1610 vector<COutput> vCoins;
1611 AvailableCoinsMinConf(vCoins, nMinConf, nMinValue, nMaxValue);
1613 setCoinsRet.clear();
1616 BOOST_FOREACH(COutput output, vCoins)
1618 if(!output.fSpendable)
1620 const CWalletTx *pcoin = output.tx;
1623 // Ignore immature coins
1624 if (pcoin->GetBlocksToMaturity() > 0)
1627 // Stop if we've chosen enough inputs
1628 if (nValueRet >= nTargetValue)
1631 // Follow the timestamp rules
1632 if (pcoin->nTime > nSpendTime)
1635 int64_t n = pcoin->vout[i].nValue;
1637 pair<int64_t,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1639 if (n >= nTargetValue)
1641 // If input value is greater or equal to target then simply insert
1642 // it into the current subset and exit
1643 setCoinsRet.insert(coin.second);
1644 nValueRet += coin.first;
1647 else if (n < nTargetValue + CENT)
1649 setCoinsRet.insert(coin.second);
1650 nValueRet += coin.first;
1657 bool CWallet::CreateTransaction(const vector<pair<CScript, int64_t> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl* coinControl)
1660 BOOST_FOREACH (const PAIRTYPE(CScript, int64_t)& s, vecSend)
1666 if (vecSend.empty() || nValue < 0)
1669 wtxNew.BindWallet(this);
1672 LOCK2(cs_main, cs_wallet);
1673 // txdb must be opened before the mapWallet lock
1676 nFeeRet = nTransactionFee;
1680 wtxNew.vout.clear();
1681 wtxNew.fFromMe = true;
1683 int64_t nTotalValue = nValue + nFeeRet;
1684 double dPriority = 0;
1685 // vouts to the payees
1686 BOOST_FOREACH (const PAIRTYPE(CScript, int64_t)& s, vecSend)
1687 wtxNew.vout.push_back(CTxOut(s.second, s.first));
1689 // Choose coins to use
1690 set<pair<const CWalletTx*,unsigned int> > setCoins;
1691 int64_t nValueIn = 0;
1692 if (!SelectCoins(nTotalValue, wtxNew.nTime, setCoins, nValueIn, coinControl))
1694 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1696 int64_t nCredit = pcoin.first->vout[pcoin.second].nValue;
1697 dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
1700 int64_t nChange = nValueIn - nValue - nFeeRet;
1703 // Fill a vout to ourself
1704 // TODO: pass in scriptChange instead of reservekey so
1705 // change transaction isn't always pay-to-bitcoin-address
1706 CScript scriptChange;
1708 // coin control: send change to custom address
1709 if (coinControl && coinControl->destChange.IsValid())
1710 scriptChange.SetAddress(coinControl->destChange);
1712 // no coin control: send change to newly generated address
1715 // Note: We use a new key here to keep it from being obvious which side is the change.
1716 // The drawback is that by not reusing a previous key, the change may be lost if a
1717 // backup is restored, if the backup doesn't have the new private key for the change.
1718 // If we reused the old key, it would be possible to add code to look for and
1719 // rediscover unknown transactions that were written with keys of ours to recover
1720 // post-backup change.
1722 // Reserve a new key pair from key pool
1723 CPubKey vchPubKey = reservekey.GetReservedKey();
1725 scriptChange.SetDestination(vchPubKey.GetID());
1728 // Insert change txn at random position:
1729 vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
1730 wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
1733 reservekey.ReturnKey();
1736 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1737 wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
1741 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1742 if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
1746 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
1747 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1749 dPriority /= nBytes;
1751 // Check that enough fee is included
1752 bool fAllowFree = CTransaction::AllowFree(dPriority);
1753 int64_t nPayFee = nTransactionFee * (1 + (int64_t)nBytes / 1000);
1754 int64_t nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
1756 if (nFeeRet < max(nPayFee, nMinFee))
1758 nFeeRet = max(nPayFee, nMinFee);
1762 // Fill vtxPrev by copying from previous transactions vtxPrev
1763 wtxNew.AddSupportingTransactions(txdb);
1764 wtxNew.fTimeReceivedIsTxTime = true;
1773 bool CWallet::CreateTransaction(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl* coinControl)
1775 vector< pair<CScript, int64_t> > vecSend;
1776 vecSend.push_back(make_pair(scriptPubKey, nValue));
1777 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, coinControl);
1780 void CWallet::GetStakeWeightFromValue(const int64_t& nTime, const int64_t& nValue, uint64_t& nWeight)
1782 int64_t nTimeWeight = GetWeight(nTime, GetTime());
1784 // If time weight is lower or equal to zero then weight is zero.
1785 if (nTimeWeight <= 0)
1791 CBigNum bnCoinDayWeight = CBigNum(nValue) * nTimeWeight / COIN / nOneDay;
1792 nWeight = bnCoinDayWeight.getuint64();
1795 bool CWallet::MergeCoins(const int64_t& nAmount, const int64_t& nMinValue, const int64_t& nOutputValue, list<uint256>& listMerged)
1797 int64_t nBalance = GetBalance();
1799 if (nAmount > nBalance)
1803 int64_t nValueIn = 0;
1804 set<pair<const CWalletTx*,unsigned int> > setCoins;
1806 // Simple coins selection - no randomization
1807 if (!SelectCoinsSimple(nAmount, nMinValue, nOutputValue, GetTime(), 1, setCoins, nValueIn))
1810 if (setCoins.empty())
1814 vector<const CWalletTx*> vwtxPrev;
1816 // Reserve a new key pair from key pool
1817 CReserveKey reservekey(this);
1818 CPubKey vchPubKey = reservekey.GetReservedKey();
1821 CScript scriptOutput;
1822 scriptOutput.SetDestination(vchPubKey.GetID());
1825 wtxNew.vout.push_back(CTxOut(0, scriptOutput));
1828 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1830 int64_t nCredit = pcoin.first->vout[pcoin.second].nValue;
1832 // Add current coin to inputs list and add its credit to transaction output
1833 wtxNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1834 wtxNew.vout[0].nValue += nCredit;
1835 vwtxPrev.push_back(pcoin.first);
1838 // Replaced with estimation for performance purposes
1840 for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
1841 const CWalletTx *txin = vwtxPrev[i];
1843 // Sign scripts to get actual transaction size for fee calculation
1844 if (!SignSignature(*this, *txin, wtxNew, i))
1849 // Assuming that average scriptsig size is 110 bytes
1850 int64_t nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION) + wtxNew.vin.size() * 110;
1851 dWeight += (double)nCredit * pcoin.first->GetDepthInMainChain();
1853 double dFinalPriority = dWeight /= nBytes;
1854 bool fAllowFree = CTransaction::AllowFree(dFinalPriority);
1856 // Get actual transaction fee according to its estimated size and priority
1857 int64_t nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
1859 // Prepare transaction for commit if sum is enough ot its size is too big
1860 if (nBytes >= MAX_BLOCK_SIZE_GEN/6 || wtxNew.vout[0].nValue >= nOutputValue)
1862 wtxNew.vout[0].nValue -= nMinFee; // Set actual fee
1864 for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
1865 const CWalletTx *txin = vwtxPrev[i];
1868 if (!SignSignature(*this, *txin, wtxNew, i))
1872 // Try to commit, return false on failure
1873 if (!CommitTransaction(wtxNew, reservekey))
1876 listMerged.push_back(wtxNew.GetHash()); // Add to hashes list
1878 dWeight = 0; // Reset all temporary values
1881 wtxNew.vout.push_back(CTxOut(0, scriptOutput));
1885 // Create transactions if there are some unhandled coins left
1886 if (wtxNew.vout[0].nValue > 0) {
1887 int64_t nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION) + wtxNew.vin.size() * 110;
1889 double dFinalPriority = dWeight /= nBytes;
1890 bool fAllowFree = CTransaction::AllowFree(dFinalPriority);
1892 // Get actual transaction fee according to its size and priority
1893 int64_t nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
1895 wtxNew.vout[0].nValue -= nMinFee; // Set actual fee
1897 if (wtxNew.vout[0].nValue <= 0)
1900 for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
1901 const CWalletTx *txin = vwtxPrev[i];
1903 // Sign all scripts again
1904 if (!SignSignature(*this, *txin, wtxNew, i))
1908 // Try to commit, return false on failure
1909 if (!CommitTransaction(wtxNew, reservekey))
1912 listMerged.push_back(wtxNew.GetHash()); // Add to hashes list
1918 bool CWallet::CreateCoinStake(uint256 &hashTx, uint32_t nOut, uint32_t nGenerationTime, uint32_t nBits, CTransaction &txNew, CKey& key)
1921 if (!GetTransaction(hashTx, wtx))
1922 return error("Transaction %s is not found\n", hashTx.GetHex().c_str());
1924 vector<valtype> vSolutions;
1925 txnouttype whichType;
1926 CScript scriptPubKeyOut;
1927 CScript scriptPubKeyKernel = wtx.vout[nOut].scriptPubKey;
1928 if (!Solver(scriptPubKeyKernel, whichType, vSolutions))
1929 return error("CreateCoinStake : failed to parse kernel\n");
1931 if (fDebug && GetBoolArg("-printcoinstake"))
1932 printf("CreateCoinStake : parsed kernel type=%d\n", whichType);
1934 if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH)
1935 return error("CreateCoinStake : no support for kernel type=%d\n", whichType);
1937 if (whichType == TX_PUBKEYHASH) // pay to address type
1939 // convert to pay to public key type
1940 if (!GetKey(uint160(vSolutions[0]), key))
1941 return error("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1943 scriptPubKeyOut << key.GetPubKey() << OP_CHECKSIG;
1945 if (whichType == TX_PUBKEY)
1947 valtype& vchPubKey = vSolutions[0];
1948 if (!GetKey(Hash160(vchPubKey), key))
1949 return error("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1950 if (key.GetPubKey() != vchPubKey)
1951 return error("CreateCoinStake : invalid key for kernel type=%d\n", whichType); // keys mismatch
1952 scriptPubKeyOut = scriptPubKeyKernel;
1955 // The following combine threshold is important to security
1956 // Should not be adjusted if you don't understand the consequences
1957 int64_t nCombineThreshold = GetProofOfWorkReward(GetLastBlockIndex(pindexBest, false)->nBits) / 3;
1959 int64_t nBalance = GetBalance();
1960 int64_t nCredit = wtx.vout[nOut].nValue;
1965 // List of constake dependencies
1966 vector<const CWalletTx*> vwtxPrev;
1967 vwtxPrev.push_back(&wtx);
1969 // Set generation time, and kernel input
1970 txNew.nTime = nGenerationTime;
1971 txNew.vin.push_back(CTxIn(hashTx, nOut));
1973 // Mark coin stake transaction with empty vout[0]
1974 CScript scriptEmpty;
1975 scriptEmpty.clear();
1976 txNew.vout.push_back(CTxOut(0, scriptEmpty));
1978 if (fDebug && GetBoolArg("-printcoinstake"))
1979 printf("CreateCoinStake : added kernel type=%d\n", whichType);
1981 int64_t nValueIn = 0;
1983 if (!SelectCoinsSimple(nBalance - nReserveBalance, MIN_TX_FEE, MAX_MONEY, nGenerationTime, nCoinbaseMaturity * 10, setCoins, nValueIn))
1986 if (setCoins.empty())
1989 bool fDontSplitCoins = false;
1990 if (GetWeight((int64_t)wtx.nTime, (int64_t)nGenerationTime) == nStakeMaxAge)
1992 // Only one output for old kernel inputs
1993 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
1995 // Iterate through set of (wtx*, nout) in order to find some additional inputs for our new coinstake transaction.
1997 // * Value is higher than 0.01 NVC;
1998 // * Only add inputs of the same key/address as kernel;
1999 // * Input hash and kernel parent hash should be different.
2000 for(CoinsSet::iterator pcoin = setCoins.begin(); pcoin != setCoins.end(); pcoin++)
2002 // Stop adding more inputs if already too many inputs
2003 if (txNew.vin.size() >= 100)
2005 // Stop adding more inputs if value is already pretty significant
2006 if (nCredit > nCombineThreshold)
2008 // Stop adding inputs if reached reserve limit
2009 if (nCredit + pcoin->first->vout[pcoin->second].nValue > nBalance - nReserveBalance)
2012 int64_t nTimeWeight = GetWeight((int64_t)pcoin->first->nTime, (int64_t)nGenerationTime);
2014 // Do not add input that is still too young
2015 if (nTimeWeight < nStakeMaxAge)
2017 // Do not add input if key/address is not the same as kernel
2018 if (pcoin->first->vout[pcoin->second].scriptPubKey != scriptPubKeyKernel && pcoin->first->vout[pcoin->second].scriptPubKey != txNew.vout[1].scriptPubKey)
2020 // Do not add input if parents are the same
2021 if (pcoin->first->GetHash() != txNew.vin[0].prevout.hash)
2023 // Do not add additional significant input
2024 if (pcoin->first->vout[pcoin->second].nValue > nCombineThreshold)
2027 txNew.vin.push_back(CTxIn(pcoin->first->GetHash(), pcoin->second));
2028 nCredit += pcoin->first->vout[pcoin->second].nValue;
2029 vwtxPrev.push_back(pcoin->first);
2032 fDontSplitCoins = true;
2036 int64_t nSplitThreshold = GetArg("-splitthreshold", nCombineThreshold);
2038 if (fDebug && GetBoolArg("-printcoinstake"))
2039 printf("CreateCoinStake : nSplitThreshold=%" PRId64 "\n", nSplitThreshold);
2041 if (nCredit > nSplitThreshold)
2043 // Split stake input if credit is lower than combine threshold and maximum weight isn't reached yet
2044 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
2045 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
2047 if (fDebug && GetBoolArg("-printcoinstake"))
2048 printf("CreateCoinStake : splitting coinstake\n");
2052 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
2053 fDontSplitCoins = true;
2057 // Calculate coin age reward
2060 if (!txNew.GetCoinAge(txdb, nCoinAge))
2061 return error("CreateCoinStake : failed to calculate coin age\n");
2062 nCredit += GetProofOfStakeReward(nCoinAge, nBits, nGenerationTime);
2064 int64_t nMinFee = 0;
2067 // Set output amount
2068 if (fDontSplitCoins)
2069 txNew.vout[1].nValue = nCredit - nMinFee;
2072 txNew.vout[1].nValue = ((nCredit - nMinFee) / 2 / CENT) * CENT;
2073 txNew.vout[2].nValue = nCredit - nMinFee - txNew.vout[1].nValue;
2078 BOOST_FOREACH(const CWalletTx* pcoin, vwtxPrev)
2080 if (!SignSignature(*this, *pcoin, txNew, nIn++))
2081 return error("CreateCoinStake : failed to sign coinstake\n");
2085 unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION);
2086 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
2087 return error("CreateCoinStake : exceeded coinstake size limit\n");
2089 // Check enough fee is paid
2090 if (nMinFee < txNew.GetMinFee(1, false, GMF_BLOCK, nBytes) - CENT)
2092 nMinFee = txNew.GetMinFee(1, false, GMF_BLOCK, nBytes) - CENT;
2093 continue; // try signing again
2097 if (fDebug && GetBoolArg("-printfee"))
2098 printf("CreateCoinStake : fee for coinstake %s\n", FormatMoney(nMinFee).c_str());
2103 // Successfully created coinstake
2107 // Call after CreateTransaction unless you want to abort
2108 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
2111 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
2113 // Track how many getdata requests our transaction gets
2114 mapRequestCount[wtxNew.GetHash()] = 0;
2116 // Try to broadcast before saving
2117 if (!wtxNew.AcceptToMemoryPool())
2119 // This must not fail. The transaction has already been signed.
2120 printf("CommitTransaction() : Error: Transaction not valid");
2124 wtxNew.RelayWalletTransaction();
2127 LOCK2(cs_main, cs_wallet);
2129 // This is only to keep the database open to defeat the auto-flush for the
2130 // duration of this scope. This is the only place where this optimization
2131 // maybe makes sense; please don't do it anywhere else.
2132 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
2134 // Take key pair from key pool so it won't be used again
2135 reservekey.KeepKey();
2137 // Add tx to wallet, because if it has change it's also ours,
2138 // otherwise just for transaction history.
2139 AddToWallet(wtxNew);
2141 // Mark old coins as spent
2142 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
2144 CWalletTx &coin = mapWallet[txin.prevout.hash];
2145 coin.BindWallet(this);
2146 coin.MarkSpent(txin.prevout.n);
2148 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
2149 vMintingWalletUpdated.push_back(coin.GetHash());
2162 string CWallet::SendMoney(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, bool fAskFee)
2166 return _("Invalid amount");
2167 if (nValue + nTransactionFee > GetBalance())
2168 return _("Insufficient funds");
2170 CReserveKey reservekey(this);
2171 int64_t nFeeRequired;
2175 string strError = _("Error: Wallet locked, unable to create transaction ");
2176 printf("SendMoney() : %s", strError.c_str());
2179 if (fWalletUnlockMintOnly)
2181 string strError = _("Error: Wallet unlocked for block minting only, unable to create transaction.");
2182 printf("SendMoney() : %s", strError.c_str());
2185 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
2188 if (nValue + nFeeRequired > GetBalance())
2189 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());
2191 strError = _("Error: Transaction creation failed ");
2192 printf("SendMoney() : %s", strError.c_str());
2196 if (fAskFee && !uiInterface.ThreadSafeAskFee(nFeeRequired, _("Sending...")))
2199 if (!CommitTransaction(wtxNew, reservekey))
2200 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.");
2205 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
2209 fFirstRunRet = false;
2210 DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
2211 if (nLoadWalletRet == DB_NEED_REWRITE)
2213 if (CDB::Rewrite(strWalletFile, "\x04pool"))
2216 // Note: can't top-up keypool here, because wallet is locked.
2217 // User will be prompted to unlock wallet the next operation
2218 // the requires a new key.
2222 if (nLoadWalletRet != DB_LOAD_OK)
2223 return nLoadWalletRet;
2224 fFirstRunRet = !vchDefaultKey.IsValid();
2226 NewThread(ThreadFlushWalletDB, &strWalletFile);
2230 DBErrors CWallet::ZapWalletTx()
2234 DBErrors nZapWalletTxRet = CWalletDB(strWalletFile,"cr+").ZapWalletTx(this);
2235 if (nZapWalletTxRet == DB_NEED_REWRITE)
2237 if (CDB::Rewrite(strWalletFile, "\x04pool"))
2241 // Note: can't top-up keypool here, because wallet is locked.
2242 // User will be prompted to unlock wallet the next operation
2243 // the requires a new key.
2247 if (nZapWalletTxRet != DB_LOAD_OK)
2248 return nZapWalletTxRet;
2253 bool CWallet::SetAddressBookName(const CTxDestination& address, const string& strName)
2255 return SetAddressBookName(CBitcoinAddress(address), strName);
2258 bool CWallet::SetAddressBookName(const CBitcoinAddress& address, const string& strName)
2260 std::map<CBitcoinAddress, string>::iterator mi = mapAddressBook.find(address);
2261 mapAddressBook[address] = strName;
2262 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != MINE_NO, (mi == mapAddressBook.end()) ? CT_NEW : CT_UPDATED);
2265 return CWalletDB(strWalletFile).WriteName(address.ToString(), strName);
2268 bool CWallet::DelAddressBookName(const CBitcoinAddress& address)
2270 mapAddressBook.erase(address);
2271 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != MINE_NO, CT_DELETED);
2274 return CWalletDB(strWalletFile).EraseName(address.ToString());
2278 void CWallet::PrintWallet(const CBlock& block)
2282 if (block.IsProofOfStake() && mapWallet.count(block.vtx[1].GetHash()))
2284 CWalletTx& wtx = mapWallet[block.vtx[1].GetHash()];
2285 printf(" PoS: %d %d %" PRId64 "", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit(MINE_ALL));
2287 else if (mapWallet.count(block.vtx[0].GetHash()))
2289 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
2290 printf(" PoW: %d %d %" PRId64 "", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit(MINE_ALL));
2296 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
2300 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
2301 if (mi != mapWallet.end())
2310 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
2314 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
2317 vchDefaultKey = vchPubKey;
2321 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
2323 if (!pwallet->fFileBacked)
2325 strWalletFileOut = pwallet->strWalletFile;
2330 // Mark old keypool keys as used,
2331 // and generate all new keys
2333 bool CWallet::NewKeyPool(unsigned int nSize)
2337 CWalletDB walletdb(strWalletFile);
2338 BOOST_FOREACH(int64_t nIndex, setKeyPool)
2339 walletdb.ErasePool(nIndex);
2349 nKeys = max<uint64_t>(GetArg("-keypool", 100), 0);
2351 for (uint64_t i = 0; i < nKeys; i++)
2353 uint64_t nIndex = i+1;
2354 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
2355 setKeyPool.insert(nIndex);
2357 printf("CWallet::NewKeyPool wrote %" PRIu64 " new keys\n", nKeys);
2362 bool CWallet::TopUpKeyPool(unsigned int nSize)
2370 CWalletDB walletdb(strWalletFile);
2373 uint64_t nTargetSize;
2375 nTargetSize = nSize;
2377 nTargetSize = max<uint64_t>(GetArg("-keypool", 100), 0);
2379 while (setKeyPool.size() < (nTargetSize + 1))
2382 if (!setKeyPool.empty())
2383 nEnd = *(--setKeyPool.end()) + 1;
2384 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
2385 throw runtime_error("TopUpKeyPool() : writing generated key failed");
2386 setKeyPool.insert(nEnd);
2387 printf("keypool added key %" PRIu64 ", size=%" PRIszu "\n", nEnd, setKeyPool.size());
2393 void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool)
2396 keypool.vchPubKey = CPubKey();
2403 // Get the oldest key
2404 if(setKeyPool.empty())
2407 CWalletDB walletdb(strWalletFile);
2409 nIndex = *(setKeyPool.begin());
2410 setKeyPool.erase(setKeyPool.begin());
2411 if (!walletdb.ReadPool(nIndex, keypool))
2412 throw runtime_error("ReserveKeyFromKeyPool() : read failed");
2413 if (!HaveKey(keypool.vchPubKey.GetID()))
2414 throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
2415 assert(keypool.vchPubKey.IsValid());
2416 if (fDebug && GetBoolArg("-printkeypool"))
2417 printf("keypool reserve %" PRId64 "\n", nIndex);
2421 int64_t CWallet::AddReserveKey(const CKeyPool& keypool)
2424 LOCK2(cs_main, cs_wallet);
2425 CWalletDB walletdb(strWalletFile);
2427 int64_t nIndex = 1 + *(--setKeyPool.end());
2428 if (!walletdb.WritePool(nIndex, keypool))
2429 throw runtime_error("AddReserveKey() : writing added key failed");
2430 setKeyPool.insert(nIndex);
2436 void CWallet::KeepKey(int64_t nIndex)
2438 // Remove from key pool
2441 CWalletDB walletdb(strWalletFile);
2442 walletdb.ErasePool(nIndex);
2445 printf("keypool keep %" PRId64 "\n", nIndex);
2448 void CWallet::ReturnKey(int64_t nIndex)
2450 // Return to key pool
2453 setKeyPool.insert(nIndex);
2456 printf("keypool return %" PRId64 "\n", nIndex);
2459 bool CWallet::GetKeyFromPool(CPubKey& result, bool fAllowReuse)
2465 ReserveKeyFromKeyPool(nIndex, keypool);
2468 if (fAllowReuse && vchDefaultKey.IsValid())
2470 result = vchDefaultKey;
2473 if (IsLocked()) return false;
2474 result = GenerateNewKey();
2478 result = keypool.vchPubKey;
2483 int64_t CWallet::GetOldestKeyPoolTime()
2487 ReserveKeyFromKeyPool(nIndex, keypool);
2491 return keypool.nTime;
2494 std::map<CBitcoinAddress, int64_t> CWallet::GetAddressBalances()
2496 map<CBitcoinAddress, int64_t> balances;
2500 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2502 CWalletTx *pcoin = &walletEntry.second;
2504 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
2507 if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0)
2510 int nDepth = pcoin->GetDepthInMainChain();
2511 if (nDepth < (pcoin->IsFromMe(MINE_ALL) ? 0 : 1))
2514 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2516 CBitcoinAddress addr;
2517 if (!IsMine(pcoin->vout[i]))
2519 if(!ExtractAddress(*this, pcoin->vout[i].scriptPubKey, addr))
2522 int64_t n = pcoin->IsSpent(i) ? 0 : pcoin->vout[i].nValue;
2524 if (!balances.count(addr))
2526 balances[addr] += n;
2534 set< set<CBitcoinAddress> > CWallet::GetAddressGroupings()
2536 set< set<CBitcoinAddress> > groupings;
2537 set<CBitcoinAddress> grouping;
2539 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2541 CWalletTx *pcoin = &walletEntry.second;
2543 if (pcoin->vin.size() > 0 && IsMine(pcoin->vin[0]))
2545 // group all input addresses with each other
2546 BOOST_FOREACH(CTxIn txin, pcoin->vin)
2548 CBitcoinAddress address;
2549 if(!ExtractAddress(*this, mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
2551 grouping.insert(address);
2554 // group change with input addresses
2555 BOOST_FOREACH(CTxOut txout, pcoin->vout)
2556 if (IsChange(txout))
2558 CWalletTx tx = mapWallet[pcoin->vin[0].prevout.hash];
2559 CBitcoinAddress txoutAddr;
2560 if(!ExtractAddress(*this, txout.scriptPubKey, txoutAddr))
2562 grouping.insert(txoutAddr);
2564 groupings.insert(grouping);
2568 // group lone addrs by themselves
2569 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2570 if (IsMine(pcoin->vout[i]))
2572 CBitcoinAddress address;
2573 if(!ExtractAddress(*this, pcoin->vout[i].scriptPubKey, address))
2575 grouping.insert(address);
2576 groupings.insert(grouping);
2581 set< set<CBitcoinAddress>* > uniqueGroupings; // a set of pointers to groups of addresses
2582 map< CBitcoinAddress, set<CBitcoinAddress>* > setmap; // map addresses to the unique group containing it
2583 BOOST_FOREACH(set<CBitcoinAddress> grouping, groupings)
2585 // make a set of all the groups hit by this new group
2586 set< set<CBitcoinAddress>* > hits;
2587 map< CBitcoinAddress, set<CBitcoinAddress>* >::iterator it;
2588 BOOST_FOREACH(CBitcoinAddress address, grouping)
2589 if ((it = setmap.find(address)) != setmap.end())
2590 hits.insert((*it).second);
2592 // merge all hit groups into a new single group and delete old groups
2593 set<CBitcoinAddress>* merged = new set<CBitcoinAddress>(grouping);
2594 BOOST_FOREACH(set<CBitcoinAddress>* hit, hits)
2596 merged->insert(hit->begin(), hit->end());
2597 uniqueGroupings.erase(hit);
2600 uniqueGroupings.insert(merged);
2603 BOOST_FOREACH(CBitcoinAddress element, *merged)
2604 setmap[element] = merged;
2607 set< set<CBitcoinAddress> > ret;
2608 BOOST_FOREACH(set<CBitcoinAddress>* uniqueGrouping, uniqueGroupings)
2610 ret.insert(*uniqueGrouping);
2611 delete uniqueGrouping;
2617 // ppcoin: check 'spent' consistency between wallet and txindex
2618 // ppcoin: fix wallet spent state according to txindex
2619 void CWallet::FixSpentCoins(int& nMismatchFound, int64_t& nBalanceInQuestion, bool fCheckOnly)
2622 nBalanceInQuestion = 0;
2625 vector<CWalletTx*> vCoins;
2626 vCoins.reserve(mapWallet.size());
2627 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2628 vCoins.push_back(&(*it).second);
2631 BOOST_FOREACH(CWalletTx* pcoin, vCoins)
2633 // Find the corresponding transaction index
2635 if (!txdb.ReadTxIndex(pcoin->GetHash(), txindex))
2637 for (unsigned int n=0; n < pcoin->vout.size(); n++)
2639 if (IsMine(pcoin->vout[n]) && pcoin->IsSpent(n) && (txindex.vSpent.size() <= n || txindex.vSpent[n].IsNull()))
2641 printf("FixSpentCoins found lost coin %sppc %s[%u], %s\n",
2642 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2644 nBalanceInQuestion += pcoin->vout[n].nValue;
2647 pcoin->MarkUnspent(n);
2648 pcoin->WriteToDisk();
2651 else if (IsMine(pcoin->vout[n]) && !pcoin->IsSpent(n) && (txindex.vSpent.size() > n && !txindex.vSpent[n].IsNull()))
2653 printf("FixSpentCoins found spent coin %sppc %s[%u], %s\n",
2654 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2656 nBalanceInQuestion += pcoin->vout[n].nValue;
2659 pcoin->MarkSpent(n);
2660 pcoin->WriteToDisk();
2666 if(IsMine((CTransaction)*pcoin) && (pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetDepthInMainChain() == 0)
2668 printf("FixSpentCoins %s tx %s\n", fCheckOnly ? "found" : "removed", pcoin->GetHash().ToString().c_str());
2671 EraseFromWallet(pcoin->GetHash());
2677 // ppcoin: disable transaction (only for coinstake)
2678 void CWallet::DisableTransaction(const CTransaction &tx)
2680 if (!tx.IsCoinStake() || !IsFromMe(tx))
2681 return; // only disconnecting coinstake requires marking input unspent
2684 BOOST_FOREACH(const CTxIn& txin, tx.vin)
2686 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
2687 if (mi != mapWallet.end())
2689 CWalletTx& prev = (*mi).second;
2690 if (txin.prevout.n < prev.vout.size() && IsMine(prev.vout[txin.prevout.n]))
2692 prev.MarkUnspent(txin.prevout.n);
2699 CPubKey CReserveKey::GetReservedKey()
2704 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
2706 vchPubKey = keypool.vchPubKey;
2709 printf("CReserveKey::GetReservedKey(): Warning: Using default key instead of a new key, top up your keypool!");
2710 vchPubKey = pwallet->vchDefaultKey;
2713 assert(vchPubKey.IsValid());
2717 void CReserveKey::KeepKey()
2720 pwallet->KeepKey(nIndex);
2722 vchPubKey = CPubKey();
2725 void CReserveKey::ReturnKey()
2728 pwallet->ReturnKey(nIndex);
2730 vchPubKey = CPubKey();
2733 void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
2737 CWalletDB walletdb(strWalletFile);
2739 LOCK2(cs_main, cs_wallet);
2740 BOOST_FOREACH(const int64_t& id, setKeyPool)
2743 if (!walletdb.ReadPool(id, keypool))
2744 throw runtime_error("GetAllReserveKeyHashes() : read failed");
2745 assert(keypool.vchPubKey.IsValid());
2746 CKeyID keyID = keypool.vchPubKey.GetID();
2747 if (!HaveKey(keyID))
2748 throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
2749 setAddress.insert(keyID);
2753 void CWallet::UpdatedTransaction(const uint256 &hashTx)
2757 // Only notify UI if this transaction is in this wallet
2758 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
2759 if (mi != mapWallet.end())
2761 NotifyTransactionChanged(this, hashTx, CT_UPDATED);
2762 vMintingWalletUpdated.push_back(hashTx);
2767 void CWallet::GetAddresses(std::map<CBitcoinAddress, int64_t> &mapAddresses) const {
2768 mapAddresses.clear();
2770 // get birth times for keys with metadata
2771 for (std::map<CBitcoinAddress, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++) {
2772 mapAddresses[it->first] = it->second.nCreateTime ? it->second.nCreateTime : 0;
2775 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
2776 // iterate over all wallet transactions...
2777 const CWalletTx &wtx = (*it).second;
2778 if (wtx.hashBlock == 0)
2779 continue; // skip unconfirmed transactions
2781 for(std::vector<CTxOut>::const_iterator it2 = wtx.vout.begin(); it2 != wtx.vout.end(); it2++) {
2782 const CTxOut &out = (*it2);
2783 // iterate over all their outputs
2784 CBitcoinAddress addressRet;
2785 if (ExtractAddress(*this, out.scriptPubKey, addressRet)) {
2786 if (mapAddresses.find(addressRet) != mapAddresses.end() && (mapAddresses[addressRet] == 0 || mapAddresses[addressRet] > wtx.nTime))
2787 mapAddresses[addressRet] = wtx.nTime;
2790 // multisig output affects more than one key
2791 std::vector<CKeyID> vAffected;
2792 ::ExtractAffectedKeys(*this, out.scriptPubKey, vAffected);
2794 for(std::vector<CKeyID>::const_iterator it3 = vAffected.begin(); it3 != vAffected.end(); it3++) {
2795 CBitcoinAddress addrAffected(*it3);
2796 if (mapAddresses.find(addrAffected) != mapAddresses.end() && (mapAddresses[addrAffected] == 0 || mapAddresses[addrAffected] > wtx.nTime))
2797 mapAddresses[addrAffected] = wtx.nTime;
2805 void CWallet::ClearOrphans()
2807 list<uint256> orphans;
2810 for(map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2812 const CWalletTx *wtx = &(*it).second;
2813 if((wtx->IsCoinBase() || wtx->IsCoinStake()) && !wtx->IsInMainChain())
2815 orphans.push_back(wtx->GetHash());
2819 for(list<uint256>::const_iterator it = orphans.begin(); it != orphans.end(); ++it)
2820 EraseFromWallet(*it);