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>
19 extern int64_t nReserveBalance;
21 //////////////////////////////////////////////////////////////////////////////
26 struct CompareValueOnly
28 bool operator()(const pair<int64_t, pair<const CWalletTx*, unsigned int> >& t1,
29 const pair<int64_t, pair<const CWalletTx*, unsigned int> >& t2) const
31 return t1.first < t2.first;
35 CPubKey CWallet::GenerateNewKey()
37 bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
41 key.MakeNewKey(fCompressed);
43 // Compressed public keys were introduced in version 0.6.0
45 SetMinVersion(FEATURE_COMPRPUBKEY);
47 CPubKey pubkey = key.GetPubKey();
49 // Create new metadata
50 int64_t nCreationTime = GetTime();
51 mapKeyMetadata[CBitcoinAddress(pubkey.GetID())] = CKeyMetadata(nCreationTime);
52 if (!nTimeFirstKey || nCreationTime < nTimeFirstKey)
53 nTimeFirstKey = nCreationTime;
56 throw std::runtime_error("CWallet::GenerateNewKey() : AddKey failed");
57 return key.GetPubKey();
60 CMalleableKeyView CWallet::GenerateNewMalleableKey()
64 // Compressed public keys were introduced in version 0.6.0
65 SetMinVersion(FEATURE_MALLKEY);
69 const CMalleableKeyView &keyView(mKey);
71 // Create new metadata
72 int64_t nCreationTime = GetTime();
73 mapKeyMetadata[CBitcoinAddress(keyView.GetMalleablePubKey())] = CKeyMetadata(nCreationTime);
74 if (!nTimeFirstKey || nCreationTime < nTimeFirstKey)
75 nTimeFirstKey = nCreationTime;
78 throw std::runtime_error("CWallet::GenerateNewMalleableKey() : AddKey failed");
79 return CMalleableKeyView(mKey);
82 bool CWallet::AddKey(const CKey& key)
84 CPubKey pubkey = key.GetPubKey();
85 if (!CCryptoKeyStore::AddKey(key))
90 return CWalletDB(strWalletFile).WriteKey(pubkey, key.GetPrivKey(), mapKeyMetadata[CBitcoinAddress(pubkey.GetID())]);
94 bool CWallet::AddKey(const CMalleableKey& mKey)
96 CMalleableKeyView keyView = CMalleableKeyView(mKey);
97 CSecret vchSecretH = mKey.GetSecretH();
98 if (!CCryptoKeyStore::AddMalleableKey(keyView, vchSecretH))
103 return CWalletDB(strWalletFile).WriteMalleableKey(keyView, vchSecretH, mapKeyMetadata[CBitcoinAddress(keyView.GetMalleablePubKey())]);
107 bool CWallet::AddCryptedMalleableKey(const CMalleableKeyView& keyView, const std::vector<unsigned char> &vchCryptedSecretH)
109 if (!CCryptoKeyStore::AddCryptedMalleableKey(keyView, vchCryptedSecretH))
117 CBitcoinAddress addr(keyView.GetMalleablePubKey());
118 if (pwalletdbEncryption)
119 return pwalletdbEncryption->WriteCryptedMalleableKey(keyView, vchCryptedSecretH, mapKeyMetadata[addr]);
121 return CWalletDB(strWalletFile).WriteCryptedMalleableKey(keyView, vchCryptedSecretH, mapKeyMetadata[addr]);
127 bool CWallet::AddCryptedKey(const CPubKey &vchPubKey, const vector<unsigned char> &vchCryptedSecret)
129 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
132 // check if we need to remove from watch-only
134 script.SetDestination(vchPubKey.GetID());
135 if (HaveWatchOnly(script))
136 RemoveWatchOnly(script);
142 CBitcoinAddress addr(vchPubKey.GetID());
143 if (pwalletdbEncryption)
144 return pwalletdbEncryption->WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[addr]);
146 return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[addr]);
151 bool CWallet::LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &meta)
153 if (meta.nCreateTime && (!nTimeFirstKey || meta.nCreateTime < nTimeFirstKey))
154 nTimeFirstKey = meta.nCreateTime;
156 mapKeyMetadata[CBitcoinAddress(pubkey.GetID())] = meta;
160 bool CWallet::LoadKeyMetadata(const CMalleableKeyView &keyView, const CKeyMetadata &metadata)
162 if (metadata.nCreateTime && (!nTimeFirstKey || metadata.nCreateTime < nTimeFirstKey))
163 nTimeFirstKey = metadata.nCreateTime;
165 mapKeyMetadata[CBitcoinAddress(keyView.GetMalleablePubKey())] = metadata;
169 bool CWallet::AddCScript(const CScript& redeemScript)
171 if (!CCryptoKeyStore::AddCScript(redeemScript))
175 return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript);
178 bool CWallet::LoadCScript(const CScript& redeemScript)
180 /* A sanity check was added in commit 5ed0a2b to avoid adding redeemScripts
181 * that never can be redeemed. However, old wallets may still contain
182 * these. Do not add them to the wallet and warn. */
183 if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
185 std::string strAddr = CBitcoinAddress(redeemScript.GetID()).ToString();
186 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",
187 redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr.c_str());
191 return CCryptoKeyStore::AddCScript(redeemScript);
195 bool CWallet::AddWatchOnly(const CScript &dest)
197 if (!CCryptoKeyStore::AddWatchOnly(dest))
199 nTimeFirstKey = 1; // No birthday information for watch-only keys.
200 NotifyWatchonlyChanged(true);
203 return CWalletDB(strWalletFile).WriteWatchOnly(dest);
206 bool CWallet::RemoveWatchOnly(const CScript &dest)
209 if (!CCryptoKeyStore::RemoveWatchOnly(dest))
211 if (!HaveWatchOnly())
212 NotifyWatchonlyChanged(false);
214 if (!CWalletDB(strWalletFile).EraseWatchOnly(dest))
220 bool CWallet::LoadWatchOnly(const CScript &dest)
222 return CCryptoKeyStore::AddWatchOnly(dest);
225 // ppcoin: optional setting to unlock wallet for block minting only;
226 // serves to disable the trivial sendmoney when OS account compromised
227 bool fWalletUnlockMintOnly = false;
229 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
235 CKeyingMaterial vMasterKey;
239 BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
241 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
243 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
245 if (CCryptoKeyStore::Unlock(vMasterKey))
252 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
254 bool fWasLocked = IsLocked();
261 CKeyingMaterial vMasterKey;
262 BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
264 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
266 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
268 if (CCryptoKeyStore::Unlock(vMasterKey))
270 int64_t nStartTime = GetTimeMillis();
271 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
272 double nFirstMultiplier = 1e2 / (GetTimeMillis() - nStartTime);
273 pMasterKey.second.nDeriveIterations = (uint32_t)(pMasterKey.second.nDeriveIterations *nFirstMultiplier);
275 nStartTime = GetTimeMillis();
276 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
277 double nSecondMultiplier = 1e2 / (GetTimeMillis() - nStartTime);
278 pMasterKey.second.nDeriveIterations = (uint32_t)((pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * nSecondMultiplier) / 2);
280 if (pMasterKey.second.nDeriveIterations < 25000)
281 pMasterKey.second.nDeriveIterations = 25000;
283 printf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
285 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
287 if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
289 CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
300 void CWallet::SetBestChain(const CBlockLocator& loc)
302 CWalletDB walletdb(strWalletFile);
303 walletdb.WriteBestBlock(loc);
306 // This class implements an addrIncoming entry that causes pre-0.4
307 // clients to crash on startup if reading a private-key-encrypted wallet.
308 class CCorruptAddress
313 if (nType & SER_DISK)
318 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
320 if (nWalletVersion >= nVersion)
323 // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
324 if (fExplicit && nVersion > nWalletMaxVersion)
325 nVersion = FEATURE_LATEST;
327 nWalletVersion = nVersion;
329 if (nVersion > nWalletMaxVersion)
330 nWalletMaxVersion = nVersion;
334 CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile);
335 if (nWalletVersion > 40000)
336 pwalletdb->WriteMinVersion(nWalletVersion);
344 bool CWallet::SetMaxVersion(int nVersion)
346 // cannot downgrade below current version
347 if (nWalletVersion > nVersion)
350 nWalletMaxVersion = nVersion;
355 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
360 CKeyingMaterial vMasterKey;
361 RandAddSeedPerfmon();
363 vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
364 RAND_bytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
366 CMasterKey kMasterKey;
368 RandAddSeedPerfmon();
369 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
370 RAND_bytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
373 int64_t nStartTime = GetTimeMillis();
374 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
375 int64_t nDivider = GetTimeMillis() - nStartTime;
376 kMasterKey.nDeriveIterations = (uint32_t)(25e5 / (double)(nDivider));
378 nStartTime = GetTimeMillis();
379 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
380 double nMultiplier = 1e2 / (GetTimeMillis() - nStartTime);
381 kMasterKey.nDeriveIterations = (uint32_t)((kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * nMultiplier) / 2);
383 if (kMasterKey.nDeriveIterations < 25000)
384 kMasterKey.nDeriveIterations = 25000;
386 printf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
388 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
390 if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
395 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
398 pwalletdbEncryption = new CWalletDB(strWalletFile);
399 if (!pwalletdbEncryption->TxnBegin())
401 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
404 if (!EncryptKeys(vMasterKey))
407 pwalletdbEncryption->TxnAbort();
408 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.
411 // Encryption was introduced in version 0.4.0
412 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
416 if (!pwalletdbEncryption->TxnCommit())
417 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.
419 delete pwalletdbEncryption;
420 pwalletdbEncryption = NULL;
424 Unlock(strWalletPassphrase);
428 // Need to completely rewrite the wallet file; if we don't, bdb might keep
429 // bits of the unencrypted private key in slack space in the database file.
430 CDB::Rewrite(strWalletFile);
433 NotifyStatusChanged(this);
438 bool CWallet::DecryptWallet(const SecureString& strWalletPassphrase)
444 CKeyingMaterial vMasterKey;
448 BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
450 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
452 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
454 if (!CCryptoKeyStore::Unlock(vMasterKey))
460 pwalletdbDecryption = new CWalletDB(strWalletFile);
461 if (!pwalletdbDecryption->TxnBegin())
465 if (!DecryptKeys(vMasterKey))
468 pwalletdbDecryption->TxnAbort();
469 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.
474 // Overwrite crypted keys
475 KeyMap::const_iterator mi = mapKeys.begin();
476 while (mi != mapKeys.end())
479 key.SetSecret((*mi).second.first, (*mi).second.second);
480 pwalletdbDecryption->EraseCryptedKey(key.GetPubKey());
481 pwalletdbDecryption->WriteKey(key.GetPubKey(), key.GetPrivKey(), mapKeyMetadata[CBitcoinAddress(mi->first)]);
485 MalleableKeyMap::const_iterator mi2 = mapMalleableKeys.begin();
486 while (mi2 != mapMalleableKeys.end())
488 const CSecret &vchSecretH = mi2->second;
489 const CMalleableKeyView &keyView = mi2->first;
490 pwalletdbDecryption->EraseCryptedMalleableKey(keyView);
491 pwalletdbDecryption->WriteMalleableKey(keyView, vchSecretH, mapKeyMetadata[CBitcoinAddress(keyView.GetMalleablePubKey())]);
496 MasterKeyMap::const_iterator mk = mapMasterKeys.begin();
497 while (mk != mapMasterKeys.end())
499 pwalletdbDecryption->EraseMasterKey((*mk).first);
503 if (!pwalletdbDecryption->TxnCommit())
504 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.
506 delete pwalletdbDecryption;
507 pwalletdbDecryption = NULL;
510 // Need to completely rewrite the wallet file; if we don't, bdb might keep
511 // encrypted private keys in the database file which can be a reason of consistency issues.
512 CDB::Rewrite(strWalletFile);
514 NotifyStatusChanged(this);
519 int64_t CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
521 int64_t nRet = nOrderPosNext++;
523 pwalletdb->WriteOrderPosNext(nOrderPosNext);
525 CWalletDB(strWalletFile).WriteOrderPosNext(nOrderPosNext);
530 CWallet::TxItems CWallet::OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount)
532 CWalletDB walletdb(strWalletFile);
534 // First: get all CWalletTx and CAccountingEntry into a sorted-by-order multimap.
537 // Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry
538 // would make this much faster for applications that do this a lot.
539 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
541 CWalletTx* wtx = &((*it).second);
542 txOrdered.insert(make_pair(wtx->nOrderPos, TxPair(wtx, (CAccountingEntry*)0)));
545 walletdb.ListAccountCreditDebit(strAccount, acentries);
546 BOOST_FOREACH(CAccountingEntry& entry, acentries)
548 txOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
554 void CWallet::WalletUpdateSpent(const CTransaction &tx, bool fBlock)
556 // Anytime a signature is successfully verified, it's proof the outpoint is spent.
557 // Update the wallet spent flag if it doesn't know due to wallet.dat being
558 // restored from backup or the user making copies of wallet.dat.
561 BOOST_FOREACH(const CTxIn& txin, tx.vin)
563 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
564 if (mi != mapWallet.end())
566 CWalletTx& wtx = (*mi).second;
567 if (txin.prevout.n >= wtx.vout.size())
568 printf("WalletUpdateSpent: bad wtx %s\n", wtx.GetHash().ToString().c_str());
569 else if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n]))
571 printf("WalletUpdateSpent found spent coin %snvc %s\n", FormatMoney(wtx.GetCredit(MINE_ALL)).c_str(), wtx.GetHash().ToString().c_str());
572 wtx.MarkSpent(txin.prevout.n);
574 NotifyTransactionChanged(this, txin.prevout.hash, CT_UPDATED);
575 vMintingWalletUpdated.push_back(txin.prevout.hash);
582 uint256 hash = tx.GetHash();
583 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hash);
584 CWalletTx& wtx = (*mi).second;
586 BOOST_FOREACH(const CTxOut& txout, tx.vout)
590 wtx.MarkUnspent(&txout - &tx.vout[0]);
592 NotifyTransactionChanged(this, hash, CT_UPDATED);
593 vMintingWalletUpdated.push_back(hash);
601 void CWallet::MarkDirty()
605 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
606 item.second.MarkDirty();
610 bool CWallet::AddToWallet(const CWalletTx& wtxIn)
612 uint256 hash = wtxIn.GetHash();
615 // Inserts only if not already there, returns tx inserted or tx found
616 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
617 CWalletTx& wtx = (*ret.first).second;
618 wtx.BindWallet(this);
619 bool fInsertedNew = ret.second;
622 wtx.nTimeReceived = GetAdjustedTime();
623 wtx.nOrderPos = IncOrderPosNext();
625 wtx.nTimeSmart = wtx.nTimeReceived;
626 if (wtxIn.hashBlock != 0)
628 if (mapBlockIndex.count(wtxIn.hashBlock))
630 unsigned int latestNow = wtx.nTimeReceived;
631 unsigned int latestEntry = 0;
633 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
634 int64_t latestTolerated = latestNow + 300;
635 std::list<CAccountingEntry> acentries;
636 TxItems txOrdered = OrderedTxItems(acentries);
637 for (TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
639 CWalletTx *const pwtx = (*it).second.first;
642 CAccountingEntry *const pacentry = (*it).second.second;
646 nSmartTime = pwtx->nTimeSmart;
648 nSmartTime = pwtx->nTimeReceived;
651 nSmartTime = pacentry->nTime;
652 if (nSmartTime <= latestTolerated)
654 latestEntry = nSmartTime;
655 if (nSmartTime > latestNow)
656 latestNow = nSmartTime;
662 unsigned int& blocktime = mapBlockIndex[wtxIn.hashBlock]->nTime;
663 wtx.nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
666 printf("AddToWallet() : found %s in block %s not in index\n",
667 wtxIn.GetHash().ToString().substr(0,10).c_str(),
668 wtxIn.hashBlock.ToString().c_str());
672 bool fUpdated = false;
676 if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
678 wtx.hashBlock = wtxIn.hashBlock;
681 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
683 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
684 wtx.nIndex = wtxIn.nIndex;
687 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
689 wtx.fFromMe = wtxIn.fFromMe;
692 fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);
696 printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
699 if (fInsertedNew || fUpdated)
700 if (!wtx.WriteToDisk())
703 // If default receiving address gets used, replace it with a new one
704 CScript scriptDefaultKey;
705 scriptDefaultKey.SetDestination(vchDefaultKey.GetID());
706 BOOST_FOREACH(const CTxOut& txout, wtx.vout)
708 if (txout.scriptPubKey == scriptDefaultKey)
710 CPubKey newDefaultKey;
711 if (GetKeyFromPool(newDefaultKey, false))
713 SetDefaultKey(newDefaultKey);
714 SetAddressBookName(vchDefaultKey.GetID(), "");
719 // since AddToWallet is called directly for self-originating transactions, check for consumption of own coins
720 WalletUpdateSpent(wtx, (wtxIn.hashBlock != 0));
722 // Notify UI of new or updated transaction
723 NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
724 vMintingWalletUpdated.push_back(hash);
725 // notify an external script when a wallet transaction comes in or is updated
726 std::string strCmd = GetArg("-walletnotify", "");
728 if ( !strCmd.empty())
730 boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
731 boost::thread t(runCommand, strCmd); // thread runs free
738 // Add a transaction to the wallet, or update it.
739 // pblock is optional, but should be provided if the transaction is known to be in a block.
740 // If fUpdate is true, existing transactions will be updated.
741 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fFindBlock)
743 uint256 hash = tx.GetHash();
746 bool fExisted = mapWallet.count(hash) != 0;
747 if (fExisted && !fUpdate) return false;
748 if (fExisted || IsMine(tx) || IsFromMe(tx))
750 CWalletTx wtx(this,tx);
751 // Get merkle branch if transaction was found in a block
753 wtx.SetMerkleBranch(pblock);
754 return AddToWallet(wtx);
757 WalletUpdateSpent(tx);
762 bool CWallet::EraseFromWallet(uint256 hash)
768 if (mapWallet.erase(hash))
769 CWalletDB(strWalletFile).EraseTx(hash);
775 isminetype CWallet::IsMine(const CTxIn &txin) const
779 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
780 if (mi != mapWallet.end())
782 const CWalletTx& prev = (*mi).second;
783 if (txin.prevout.n < prev.vout.size())
784 return IsMine(prev.vout[txin.prevout.n]);
790 int64_t CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
794 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
795 if (mi != mapWallet.end())
797 const CWalletTx& prev = (*mi).second;
798 if (txin.prevout.n < prev.vout.size())
799 if (IsMine(prev.vout[txin.prevout.n]) & filter)
800 return prev.vout[txin.prevout.n].nValue;
806 bool CWallet::IsChange(const CTxOut& txout) const
808 // TODO: fix handling of 'change' outputs. The assumption is that any
809 // payment to a script that is ours, but isn't in the address book
810 // is change. That assumption is likely to break when we implement multisignature
811 // wallets that return change back into a multi-signature-protected address;
812 // a better way of identifying which outputs are 'the send' and which are
813 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
814 // which output, if any, was change).
815 if (::IsMine(*this, txout.scriptPubKey))
817 CTxDestination address;
818 if (!ExtractDestination(txout.scriptPubKey, address))
822 if (!mapAddressBook.count(address))
828 int64_t CWalletTx::GetTxTime() const
833 int CWalletTx::GetRequestCount() const
835 // Returns -1 if it wasn't being tracked
838 LOCK(pwallet->cs_wallet);
839 if (IsCoinBase() || IsCoinStake())
844 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
845 if (mi != pwallet->mapRequestCount.end())
846 nRequests = (*mi).second;
851 // Did anyone request this transaction?
852 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
853 if (mi != pwallet->mapRequestCount.end())
855 nRequests = (*mi).second;
857 // How about the block it's in?
858 if (nRequests == 0 && hashBlock != 0)
860 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
861 if (mi != pwallet->mapRequestCount.end())
862 nRequests = (*mi).second;
864 nRequests = 1; // If it's in someone else's block it must have got out
872 void CWalletTx::GetAmounts(int64_t& nGeneratedImmature, int64_t& nGeneratedMature, list<pair<CBitcoinAddress, int64_t> >& listReceived,
873 list<pair<CBitcoinAddress, int64_t> >& listSent, int64_t& nFee, string& strSentAccount, const isminefilter& filter) const
875 nGeneratedImmature = nGeneratedMature = nFee = 0;
876 listReceived.clear();
878 strSentAccount = strFromAccount;
880 if (IsCoinBase() || IsCoinStake())
882 if (GetBlocksToMaturity() > 0)
883 nGeneratedImmature = pwallet->GetCredit(*this, filter);
885 nGeneratedMature = GetCredit(filter);
890 int64_t nDebit = GetDebit(filter);
891 if (nDebit > 0) // debit>0 means we signed/sent this transaction
893 int64_t nValueOut = GetValueOut();
894 nFee = nDebit - nValueOut;
898 BOOST_FOREACH(const CTxOut& txout, vout)
900 isminetype fIsMine = pwallet->IsMine(txout);
901 // Only need to handle txouts if AT LEAST one of these is true:
902 // 1) they debit from us (sent)
903 // 2) the output is to us (received)
906 // Don't report 'change' txouts
907 if (pwallet->IsChange(txout))
910 else if (!(fIsMine & filter))
913 // In either case, we need to get the destination address
914 CBitcoinAddress address;
915 if (!ExtractAddress(*pwallet, txout.scriptPubKey, address))
917 printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
918 this->GetHash().ToString().c_str());
919 address = CBitcoinAddress();
922 // If we are debited by the transaction, add the output as a "sent" entry
924 listSent.push_back(make_pair(address, txout.nValue));
926 // If we are receiving the output, add it as a "received" entry
927 if (fIsMine & filter)
928 listReceived.push_back(make_pair(address, txout.nValue));
933 void CWalletTx::GetAccountAmounts(const string& strAccount, int64_t& nGenerated, int64_t& nReceived,
934 int64_t& nSent, int64_t& nFee, const isminefilter& filter) const
936 nGenerated = nReceived = nSent = nFee = 0;
938 int64_t allGeneratedImmature, allGeneratedMature, allFee;
939 allGeneratedImmature = allGeneratedMature = allFee = 0;
940 string strSentAccount;
941 list<pair<CBitcoinAddress, int64_t> > listReceived;
942 list<pair<CBitcoinAddress, int64_t> > listSent;
943 GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount, filter);
945 if (strAccount == "")
946 nGenerated = allGeneratedMature;
947 if (strAccount == strSentAccount)
949 BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress,int64_t)& s, listSent)
954 LOCK(pwallet->cs_wallet);
955 BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress,int64_t)& r, listReceived)
957 if (pwallet->mapAddressBook.count(r.first))
959 map<CBitcoinAddress, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);
960 if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)
961 nReceived += r.second;
963 else if (strAccount.empty())
965 nReceived += r.second;
971 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
975 const int COPY_DEPTH = 3;
976 if (SetMerkleBranch() < COPY_DEPTH)
978 vector<uint256> vWorkQueue;
979 BOOST_FOREACH(const CTxIn& txin, vin)
980 vWorkQueue.push_back(txin.prevout.hash);
982 // This critsect is OK because txdb is already open
984 LOCK(pwallet->cs_wallet);
985 map<uint256, const CMerkleTx*> mapWalletPrev;
986 set<uint256> setAlreadyDone;
987 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
989 uint256 hash = vWorkQueue[i];
990 if (setAlreadyDone.count(hash))
992 setAlreadyDone.insert(hash);
995 map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
996 if (mi != pwallet->mapWallet.end())
999 BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev)
1000 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
1002 else if (mapWalletPrev.count(hash))
1004 tx = *mapWalletPrev[hash];
1006 else if (!fClient && txdb.ReadDiskTx(hash, tx))
1012 printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
1016 int nDepth = tx.SetMerkleBranch();
1017 vtxPrev.push_back(tx);
1019 if (nDepth < COPY_DEPTH)
1021 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1022 vWorkQueue.push_back(txin.prevout.hash);
1028 reverse(vtxPrev.begin(), vtxPrev.end());
1031 bool CWalletTx::WriteToDisk()
1033 return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
1036 // Scan the block chain (starting in pindexStart) for transactions
1037 // from or to us. If fUpdate is true, found transactions that already
1038 // exist in the wallet will be updated.
1039 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
1043 CBlockIndex* pindex = pindexStart;
1049 block.ReadFromDisk(pindex, true);
1050 BOOST_FOREACH(CTransaction& tx, block.vtx)
1052 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
1055 pindex = pindex->pnext;
1061 int CWallet::ScanForWalletTransaction(const uint256& hashTx)
1064 tx.ReadFromDisk(COutPoint(hashTx, 0));
1065 if (AddToWalletIfInvolvingMe(tx, NULL, true, true))
1070 void CWallet::ReacceptWalletTransactions()
1073 bool fRepeat = true;
1078 vector<CDiskTxPos> vMissingTx;
1079 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1081 CWalletTx& wtx = item.second;
1082 if ((wtx.IsCoinBase() && wtx.IsSpent(0)) || (wtx.IsCoinStake() && wtx.IsSpent(1)))
1086 bool fUpdated = false;
1087 if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
1089 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
1090 if (txindex.vSpent.size() != wtx.vout.size())
1092 printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %" PRIszu " != wtx.vout.size() %" PRIszu "\n", txindex.vSpent.size(), wtx.vout.size());
1095 for (unsigned int i = 0; i < txindex.vSpent.size(); i++)
1099 if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i]))
1103 vMissingTx.push_back(txindex.vSpent[i]);
1108 printf("ReacceptWalletTransactions found spent coin %snvc %s\n", FormatMoney(wtx.GetCredit(MINE_ALL)).c_str(), wtx.GetHash().ToString().c_str());
1115 // Re-accept any txes of ours that aren't already in a block
1116 if (!(wtx.IsCoinBase() || wtx.IsCoinStake()))
1117 wtx.AcceptWalletTransaction(txdb, false);
1120 if (!vMissingTx.empty())
1122 // TODO: optimize this to scan just part of the block chain?
1123 if (ScanForWalletTransactions(pindexGenesisBlock))
1124 fRepeat = true; // Found missing transactions: re-do re-accept.
1129 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
1131 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
1133 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
1135 uint256 hash = tx.GetHash();
1136 if (!txdb.ContainsTx(hash))
1137 RelayTransaction((CTransaction)tx, hash);
1140 if (!(IsCoinBase() || IsCoinStake()))
1142 uint256 hash = GetHash();
1143 if (!txdb.ContainsTx(hash))
1145 printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
1146 RelayTransaction((CTransaction)*this, hash);
1151 void CWalletTx::RelayWalletTransaction()
1154 RelayWalletTransaction(txdb);
1157 void CWallet::ResendWalletTransactions(bool fForceResend)
1159 if (!fForceResend) {
1160 // Do this infrequently and randomly to avoid giving away
1161 // that these are our transactions.
1162 static int64_t nNextTime = GetRand(GetTime() + 30 * 60);
1163 if (GetTime() < nNextTime)
1165 bool fFirst = (nNextTime == 0);
1166 nNextTime = GetTime() + GetRand(30 * 60);
1170 // Only do it if there's been a new block since last time
1171 static int64_t nLastTime = 0;
1172 if (nTimeBestReceived < nLastTime)
1174 nLastTime = GetTime();
1177 // Rebroadcast any of our txes that aren't in a block yet
1178 printf("ResendWalletTransactions()\n");
1182 // Sort them in chronological order
1183 multimap<unsigned int, CWalletTx*> mapSorted;
1184 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1186 CWalletTx& wtx = item.second;
1187 // Don't rebroadcast until it's had plenty of time that
1188 // it should have gotten in already by now.
1189 if (fForceResend || nTimeBestReceived - (int64_t)wtx.nTimeReceived > 5 * 60)
1190 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
1192 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
1194 CWalletTx& wtx = *item.second;
1195 if (wtx.CheckTransaction())
1196 wtx.RelayWalletTransaction(txdb);
1198 printf("ResendWalletTransactions() : CheckTransaction failed for transaction %s\n", wtx.GetHash().ToString().c_str());
1208 //////////////////////////////////////////////////////////////////////////////
1214 int64_t CWallet::GetBalance() const
1219 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1221 const CWalletTx* pcoin = &(*it).second;
1222 if (pcoin->IsTrusted())
1223 nTotal += pcoin->GetAvailableCredit();
1230 int64_t CWallet::GetWatchOnlyBalance() const
1235 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1237 const CWalletTx* pcoin = &(*it).second;
1238 if (pcoin->IsTrusted())
1239 nTotal += pcoin->GetAvailableWatchCredit();
1246 int64_t CWallet::GetUnconfirmedBalance() const
1251 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1253 const CWalletTx* pcoin = &(*it).second;
1254 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
1255 nTotal += pcoin->GetAvailableCredit();
1261 int64_t CWallet::GetUnconfirmedWatchOnlyBalance() const
1266 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1268 const CWalletTx* pcoin = &(*it).second;
1269 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
1270 nTotal += pcoin->GetAvailableWatchCredit();
1276 int64_t CWallet::GetImmatureBalance() const
1281 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1283 const CWalletTx* pcoin = &(*it).second;
1284 nTotal += pcoin->GetImmatureCredit();
1290 int64_t CWallet::GetImmatureWatchOnlyBalance() const
1295 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1297 const CWalletTx* pcoin = &(*it).second;
1298 nTotal += pcoin->GetImmatureWatchOnlyCredit();
1304 // populate vCoins with vector of spendable COutputs
1305 void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl) const
1311 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1313 const CWalletTx* pcoin = &(*it).second;
1315 if (!pcoin->IsFinal())
1318 if (fOnlyConfirmed && !pcoin->IsTrusted())
1321 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
1324 if(pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0)
1327 for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
1328 isminetype mine = IsMine(pcoin->vout[i]);
1329 if (!(pcoin->IsSpent(i)) && mine != MINE_NO &&
1330 pcoin->vout[i].nValue >= nMinimumInputValue &&
1331 (!coinControl || !coinControl->HasSelected() || coinControl->IsSelected((*it).first, i)))
1333 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain(), mine == MINE_SPENDABLE));
1340 void CWallet::AvailableCoinsMinConf(vector<COutput>& vCoins, int nConf, int64_t nMinValue, int64_t nMaxValue) const
1346 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1348 const CWalletTx* pcoin = &(*it).second;
1350 if (!pcoin->IsFinal())
1353 if(pcoin->GetDepthInMainChain() < nConf)
1356 for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
1357 isminetype mine = IsMine(pcoin->vout[i]);
1359 // ignore coin if it was already spent or we don't own it
1360 if (pcoin->IsSpent(i) || mine == MINE_NO)
1363 // if coin value is between required limits then add new item to vector
1364 if (pcoin->vout[i].nValue >= nMinValue && pcoin->vout[i].nValue < nMaxValue)
1365 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain(), mine == MINE_SPENDABLE));
1371 static void ApproximateBestSubset(vector<pair<int64_t, pair<const CWalletTx*,unsigned int> > >vValue, int64_t nTotalLower, int64_t nTargetValue,
1372 vector<char>& vfBest, int64_t& nBest, int iterations = 1000)
1374 vector<char> vfIncluded;
1376 vfBest.assign(vValue.size(), true);
1377 nBest = nTotalLower;
1379 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
1381 vfIncluded.assign(vValue.size(), false);
1383 bool fReachedTarget = false;
1384 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
1386 for (unsigned int i = 0; i < vValue.size(); i++)
1388 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
1390 nTotal += vValue[i].first;
1391 vfIncluded[i] = true;
1392 if (nTotal >= nTargetValue)
1394 fReachedTarget = true;
1398 vfBest = vfIncluded;
1400 nTotal -= vValue[i].first;
1401 vfIncluded[i] = false;
1409 int64_t CWallet::GetStake() const
1413 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1415 const CWalletTx* pcoin = &(*it).second;
1416 if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1417 nTotal += CWallet::GetCredit(*pcoin, MINE_ALL);
1422 int64_t CWallet::GetWatchOnlyStake() const
1426 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1428 const CWalletTx* pcoin = &(*it).second;
1429 if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1430 nTotal += CWallet::GetCredit(*pcoin, MINE_WATCH_ONLY);
1435 int64_t CWallet::GetNewMint() const
1439 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1441 const CWalletTx* pcoin = &(*it).second;
1442 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1443 nTotal += CWallet::GetCredit(*pcoin, MINE_ALL);
1448 int64_t CWallet::GetWatchOnlyNewMint() const
1452 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1454 const CWalletTx* pcoin = &(*it).second;
1455 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1456 nTotal += CWallet::GetCredit(*pcoin, MINE_WATCH_ONLY);
1461 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
1463 setCoinsRet.clear();
1466 // List of values less than target
1467 pair<int64_t, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
1468 coinLowestLarger.first = std::numeric_limits<int64_t>::max();
1469 coinLowestLarger.second.first = NULL;
1470 vector<pair<int64_t, pair<const CWalletTx*,unsigned int> > > vValue;
1471 int64_t nTotalLower = 0;
1473 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
1475 BOOST_FOREACH(const COutput &output, vCoins)
1477 if (!output.fSpendable)
1480 const CWalletTx *pcoin = output.tx;
1482 if (output.nDepth < (pcoin->IsFromMe(MINE_ALL) ? nConfMine : nConfTheirs))
1487 // Follow the timestamp rules
1488 if (pcoin->nTime > nSpendTime)
1491 int64_t n = pcoin->vout[i].nValue;
1493 pair<int64_t,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1495 if (n == nTargetValue)
1497 setCoinsRet.insert(coin.second);
1498 nValueRet += coin.first;
1501 else if (n < nTargetValue + CENT)
1503 vValue.push_back(coin);
1506 else if (n < coinLowestLarger.first)
1508 coinLowestLarger = coin;
1512 if (nTotalLower == nTargetValue)
1514 for (unsigned int i = 0; i < vValue.size(); ++i)
1516 setCoinsRet.insert(vValue[i].second);
1517 nValueRet += vValue[i].first;
1522 if (nTotalLower < nTargetValue)
1524 if (coinLowestLarger.second.first == NULL)
1526 setCoinsRet.insert(coinLowestLarger.second);
1527 nValueRet += coinLowestLarger.first;
1531 // Solve subset sum by stochastic approximation
1532 sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
1533 vector<char> vfBest;
1536 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);
1537 if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT)
1538 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000);
1540 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
1541 // or the next bigger coin is closer), return the bigger coin
1542 if (coinLowestLarger.second.first &&
1543 ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest))
1545 setCoinsRet.insert(coinLowestLarger.second);
1546 nValueRet += coinLowestLarger.first;
1549 for (unsigned int i = 0; i < vValue.size(); i++)
1552 setCoinsRet.insert(vValue[i].second);
1553 nValueRet += vValue[i].first;
1556 if (fDebug && GetBoolArg("-printpriority"))
1559 printf("SelectCoins() best subset: ");
1560 for (unsigned int i = 0; i < vValue.size(); i++)
1562 printf("%s ", FormatMoney(vValue[i].first).c_str());
1563 printf("total %s\n", FormatMoney(nBest).c_str());
1570 bool CWallet::SelectCoins(int64_t nTargetValue, unsigned int nSpendTime, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64_t& nValueRet, const CCoinControl* coinControl) const
1572 vector<COutput> vCoins;
1573 AvailableCoins(vCoins, true, coinControl);
1575 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
1576 if (coinControl && coinControl->HasSelected())
1578 BOOST_FOREACH(const COutput& out, vCoins)
1582 nValueRet += out.tx->vout[out.i].nValue;
1583 setCoinsRet.insert(make_pair(out.tx, out.i));
1585 return (nValueRet >= nTargetValue);
1588 return (SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 6, vCoins, setCoinsRet, nValueRet) ||
1589 SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 1, vCoins, setCoinsRet, nValueRet) ||
1590 SelectCoinsMinConf(nTargetValue, nSpendTime, 0, 1, vCoins, setCoinsRet, nValueRet));
1593 // Select some coins without random shuffle or best subset approximation
1594 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
1596 vector<COutput> vCoins;
1597 AvailableCoinsMinConf(vCoins, nMinConf, nMinValue, nMaxValue);
1599 setCoinsRet.clear();
1602 BOOST_FOREACH(COutput output, vCoins)
1604 if(!output.fSpendable)
1606 const CWalletTx *pcoin = output.tx;
1609 // Ignore immature coins
1610 if (pcoin->GetBlocksToMaturity() > 0)
1613 // Stop if we've chosen enough inputs
1614 if (nValueRet >= nTargetValue)
1617 // Follow the timestamp rules
1618 if (pcoin->nTime > nSpendTime)
1621 int64_t n = pcoin->vout[i].nValue;
1623 pair<int64_t,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1625 if (n >= nTargetValue)
1627 // If input value is greater or equal to target then simply insert
1628 // it into the current subset and exit
1629 setCoinsRet.insert(coin.second);
1630 nValueRet += coin.first;
1633 else if (n < nTargetValue + CENT)
1635 setCoinsRet.insert(coin.second);
1636 nValueRet += coin.first;
1643 bool CWallet::CreateTransaction(const vector<pair<CScript, int64_t> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl* coinControl)
1646 BOOST_FOREACH (const PAIRTYPE(CScript, int64_t)& s, vecSend)
1652 if (vecSend.empty() || nValue < 0)
1655 wtxNew.BindWallet(this);
1658 LOCK2(cs_main, cs_wallet);
1659 // txdb must be opened before the mapWallet lock
1662 nFeeRet = nTransactionFee;
1666 wtxNew.vout.clear();
1667 wtxNew.fFromMe = true;
1669 int64_t nTotalValue = nValue + nFeeRet;
1670 double dPriority = 0;
1671 // vouts to the payees
1672 BOOST_FOREACH (const PAIRTYPE(CScript, int64_t)& s, vecSend)
1673 wtxNew.vout.push_back(CTxOut(s.second, s.first));
1675 // Choose coins to use
1676 set<pair<const CWalletTx*,unsigned int> > setCoins;
1677 int64_t nValueIn = 0;
1678 if (!SelectCoins(nTotalValue, wtxNew.nTime, setCoins, nValueIn, coinControl))
1680 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1682 int64_t nCredit = pcoin.first->vout[pcoin.second].nValue;
1683 dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
1686 int64_t nChange = nValueIn - nValue - nFeeRet;
1689 // Fill a vout to ourself
1690 // TODO: pass in scriptChange instead of reservekey so
1691 // change transaction isn't always pay-to-bitcoin-address
1692 CScript scriptChange;
1694 // coin control: send change to custom address
1695 if (coinControl && coinControl->destChange.IsValid())
1696 scriptChange.SetAddress(coinControl->destChange);
1698 // no coin control: send change to newly generated address
1701 // Note: We use a new key here to keep it from being obvious which side is the change.
1702 // The drawback is that by not reusing a previous key, the change may be lost if a
1703 // backup is restored, if the backup doesn't have the new private key for the change.
1704 // If we reused the old key, it would be possible to add code to look for and
1705 // rediscover unknown transactions that were written with keys of ours to recover
1706 // post-backup change.
1708 // Reserve a new key pair from key pool
1709 CPubKey vchPubKey = reservekey.GetReservedKey();
1711 scriptChange.SetDestination(vchPubKey.GetID());
1714 // Insert change txn at random position:
1715 vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
1716 wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
1719 reservekey.ReturnKey();
1722 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1723 wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
1727 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1728 if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
1732 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
1733 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1735 dPriority /= nBytes;
1737 // Check that enough fee is included
1738 bool fAllowFree = CTransaction::AllowFree(dPriority);
1739 int64_t nPayFee = nTransactionFee * (1 + (int64_t)nBytes / 1000);
1740 int64_t nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
1742 if (nFeeRet < max(nPayFee, nMinFee))
1744 nFeeRet = max(nPayFee, nMinFee);
1748 // Fill vtxPrev by copying from previous transactions vtxPrev
1749 wtxNew.AddSupportingTransactions(txdb);
1750 wtxNew.fTimeReceivedIsTxTime = true;
1759 bool CWallet::CreateTransaction(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl* coinControl)
1761 vector< pair<CScript, int64_t> > vecSend;
1762 vecSend.push_back(make_pair(scriptPubKey, nValue));
1763 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, coinControl);
1766 void CWallet::GetStakeWeightFromValue(const int64_t& nTime, const int64_t& nValue, uint64_t& nWeight)
1768 int64_t nTimeWeight = GetWeight(nTime, GetTime());
1770 // If time weight is lower or equal to zero then weight is zero.
1771 if (nTimeWeight <= 0)
1777 CBigNum bnCoinDayWeight = CBigNum(nValue) * nTimeWeight / COIN / nOneDay;
1778 nWeight = bnCoinDayWeight.getuint64();
1781 bool CWallet::MergeCoins(const int64_t& nAmount, const int64_t& nMinValue, const int64_t& nOutputValue, list<uint256>& listMerged)
1783 int64_t nBalance = GetBalance();
1785 if (nAmount > nBalance)
1789 int64_t nValueIn = 0;
1790 set<pair<const CWalletTx*,unsigned int> > setCoins;
1792 // Simple coins selection - no randomization
1793 if (!SelectCoinsSimple(nAmount, nMinValue, nOutputValue, GetTime(), 1, setCoins, nValueIn))
1796 if (setCoins.empty())
1800 vector<const CWalletTx*> vwtxPrev;
1802 // Reserve a new key pair from key pool
1803 CReserveKey reservekey(this);
1804 CPubKey vchPubKey = reservekey.GetReservedKey();
1807 CScript scriptOutput;
1808 scriptOutput.SetDestination(vchPubKey.GetID());
1811 wtxNew.vout.push_back(CTxOut(0, scriptOutput));
1814 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1816 int64_t nCredit = pcoin.first->vout[pcoin.second].nValue;
1818 // Add current coin to inputs list and add its credit to transaction output
1819 wtxNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1820 wtxNew.vout[0].nValue += nCredit;
1821 vwtxPrev.push_back(pcoin.first);
1824 // Replaced with estimation for performance purposes
1826 for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
1827 const CWalletTx *txin = vwtxPrev[i];
1829 // Sign scripts to get actual transaction size for fee calculation
1830 if (!SignSignature(*this, *txin, wtxNew, i))
1835 // Assuming that average scriptsig size is 110 bytes
1836 int64_t nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION) + wtxNew.vin.size() * 110;
1837 dWeight += (double)nCredit * pcoin.first->GetDepthInMainChain();
1839 double dFinalPriority = dWeight /= nBytes;
1840 bool fAllowFree = CTransaction::AllowFree(dFinalPriority);
1842 // Get actual transaction fee according to its estimated size and priority
1843 int64_t nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
1845 // Prepare transaction for commit if sum is enough ot its size is too big
1846 if (nBytes >= MAX_BLOCK_SIZE_GEN/6 || wtxNew.vout[0].nValue >= nOutputValue)
1848 wtxNew.vout[0].nValue -= nMinFee; // Set actual fee
1850 for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
1851 const CWalletTx *txin = vwtxPrev[i];
1854 if (!SignSignature(*this, *txin, wtxNew, i))
1858 // Try to commit, return false on failure
1859 if (!CommitTransaction(wtxNew, reservekey))
1862 listMerged.push_back(wtxNew.GetHash()); // Add to hashes list
1864 dWeight = 0; // Reset all temporary values
1867 wtxNew.vout.push_back(CTxOut(0, scriptOutput));
1871 // Create transactions if there are some unhandled coins left
1872 if (wtxNew.vout[0].nValue > 0) {
1873 int64_t nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION) + wtxNew.vin.size() * 110;
1875 double dFinalPriority = dWeight /= nBytes;
1876 bool fAllowFree = CTransaction::AllowFree(dFinalPriority);
1878 // Get actual transaction fee according to its size and priority
1879 int64_t nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
1881 wtxNew.vout[0].nValue -= nMinFee; // Set actual fee
1883 if (wtxNew.vout[0].nValue <= 0)
1886 for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
1887 const CWalletTx *txin = vwtxPrev[i];
1889 // Sign all scripts again
1890 if (!SignSignature(*this, *txin, wtxNew, i))
1894 // Try to commit, return false on failure
1895 if (!CommitTransaction(wtxNew, reservekey))
1898 listMerged.push_back(wtxNew.GetHash()); // Add to hashes list
1904 bool CWallet::CreateCoinStake(uint256 &hashTx, uint32_t nOut, uint32_t nGenerationTime, uint32_t nBits, CTransaction &txNew, CKey& key)
1907 if (!GetTransaction(hashTx, wtx))
1908 return error("Transaction %s is not found\n", hashTx.GetHex().c_str());
1910 vector<valtype> vSolutions;
1911 txnouttype whichType;
1912 CScript scriptPubKeyOut;
1913 CScript scriptPubKeyKernel = wtx.vout[nOut].scriptPubKey;
1914 if (!Solver(scriptPubKeyKernel, whichType, vSolutions))
1915 return error("CreateCoinStake : failed to parse kernel\n");
1917 if (fDebug && GetBoolArg("-printcoinstake"))
1918 printf("CreateCoinStake : parsed kernel type=%d\n", whichType);
1920 if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH)
1921 return error("CreateCoinStake : no support for kernel type=%d\n", whichType);
1923 if (whichType == TX_PUBKEYHASH) // pay to address type
1925 // convert to pay to public key type
1926 if (!GetKey(uint160(vSolutions[0]), key))
1927 return error("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1929 scriptPubKeyOut << key.GetPubKey() << OP_CHECKSIG;
1931 if (whichType == TX_PUBKEY)
1933 valtype& vchPubKey = vSolutions[0];
1934 if (!GetKey(Hash160(vchPubKey), key))
1935 return error("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1936 if (key.GetPubKey() != vchPubKey)
1937 return error("CreateCoinStake : invalid key for kernel type=%d\n", whichType); // keys mismatch
1938 scriptPubKeyOut = scriptPubKeyKernel;
1941 // The following combine threshold is important to security
1942 // Should not be adjusted if you don't understand the consequences
1943 int64_t nCombineThreshold = GetProofOfWorkReward(GetLastBlockIndex(pindexBest, false)->nBits) / 3;
1945 int64_t nBalance = GetBalance();
1946 int64_t nCredit = wtx.vout[nOut].nValue;
1951 // List of constake dependencies
1952 vector<const CWalletTx*> vwtxPrev;
1953 vwtxPrev.push_back(&wtx);
1955 // Set generation time, and kernel input
1956 txNew.nTime = nGenerationTime;
1957 txNew.vin.push_back(CTxIn(hashTx, nOut));
1959 // Mark coin stake transaction with empty vout[0]
1960 CScript scriptEmpty;
1961 scriptEmpty.clear();
1962 txNew.vout.push_back(CTxOut(0, scriptEmpty));
1964 if (fDebug && GetBoolArg("-printcoinstake"))
1965 printf("CreateCoinStake : added kernel type=%d\n", whichType);
1967 int64_t nValueIn = 0;
1969 if (!SelectCoinsSimple(nBalance - nReserveBalance, MIN_TX_FEE, MAX_MONEY, nGenerationTime, nCoinbaseMaturity * 10, setCoins, nValueIn))
1972 if (setCoins.empty())
1975 bool fDontSplitCoins = false;
1976 if (GetWeight((int64_t)wtx.nTime, (int64_t)nGenerationTime) == nStakeMaxAge)
1978 // Only one output for old kernel inputs
1979 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
1981 // Iterate through set of (wtx*, nout) in order to find some additional inputs for our new coinstake transaction.
1983 // * Value is higher than 0.01 NVC;
1984 // * Only add inputs of the same key/address as kernel;
1985 // * Input hash and kernel parent hash should be different.
1986 for(CoinsSet::iterator pcoin = setCoins.begin(); pcoin != setCoins.end(); pcoin++)
1988 // Stop adding more inputs if already too many inputs
1989 if (txNew.vin.size() >= 100)
1991 // Stop adding more inputs if value is already pretty significant
1992 if (nCredit > nCombineThreshold)
1994 // Stop adding inputs if reached reserve limit
1995 if (nCredit + pcoin->first->vout[pcoin->second].nValue > nBalance - nReserveBalance)
1998 int64_t nTimeWeight = GetWeight((int64_t)pcoin->first->nTime, (int64_t)nGenerationTime);
2000 // Do not add input that is still too young
2001 if (nTimeWeight < nStakeMaxAge)
2003 // Do not add input if key/address is not the same as kernel
2004 if (pcoin->first->vout[pcoin->second].scriptPubKey != scriptPubKeyKernel && pcoin->first->vout[pcoin->second].scriptPubKey != txNew.vout[1].scriptPubKey)
2006 // Do not add input if parents are the same
2007 if (pcoin->first->GetHash() != txNew.vin[0].prevout.hash)
2009 // Do not add additional significant input
2010 if (pcoin->first->vout[pcoin->second].nValue > nCombineThreshold)
2013 txNew.vin.push_back(CTxIn(pcoin->first->GetHash(), pcoin->second));
2014 nCredit += pcoin->first->vout[pcoin->second].nValue;
2015 vwtxPrev.push_back(pcoin->first);
2018 fDontSplitCoins = true;
2022 int64_t nSplitThreshold = GetArg("-splitthreshold", nCombineThreshold);
2024 if (fDebug && GetBoolArg("-printcoinstake"))
2025 printf("CreateCoinStake : nSplitThreshold=%" PRId64 "\n", nSplitThreshold);
2027 if (nCredit > nSplitThreshold)
2029 // Split stake input if credit is lower than combine threshold and maximum weight isn't reached yet
2030 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
2031 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
2033 if (fDebug && GetBoolArg("-printcoinstake"))
2034 printf("CreateCoinStake : splitting coinstake\n");
2038 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
2039 fDontSplitCoins = true;
2043 // Calculate coin age reward
2046 if (!txNew.GetCoinAge(txdb, nCoinAge))
2047 return error("CreateCoinStake : failed to calculate coin age\n");
2048 nCredit += GetProofOfStakeReward(nCoinAge, nBits, nGenerationTime);
2050 int64_t nMinFee = 0;
2053 // Set output amount
2054 if (fDontSplitCoins)
2055 txNew.vout[1].nValue = nCredit - nMinFee;
2058 txNew.vout[1].nValue = ((nCredit - nMinFee) / 2 / CENT) * CENT;
2059 txNew.vout[2].nValue = nCredit - nMinFee - txNew.vout[1].nValue;
2064 BOOST_FOREACH(const CWalletTx* pcoin, vwtxPrev)
2066 if (!SignSignature(*this, *pcoin, txNew, nIn++))
2067 return error("CreateCoinStake : failed to sign coinstake\n");
2071 unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION);
2072 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
2073 return error("CreateCoinStake : exceeded coinstake size limit\n");
2075 // Check enough fee is paid
2076 if (nMinFee < txNew.GetMinFee(1, false, GMF_BLOCK, nBytes) - CENT)
2078 nMinFee = txNew.GetMinFee(1, false, GMF_BLOCK, nBytes) - CENT;
2079 continue; // try signing again
2083 if (fDebug && GetBoolArg("-printfee"))
2084 printf("CreateCoinStake : fee for coinstake %s\n", FormatMoney(nMinFee).c_str());
2089 // Successfully created coinstake
2093 // Call after CreateTransaction unless you want to abort
2094 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
2097 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
2099 // Track how many getdata requests our transaction gets
2100 mapRequestCount[wtxNew.GetHash()] = 0;
2102 // Try to broadcast before saving
2103 if (!wtxNew.AcceptToMemoryPool())
2105 // This must not fail. The transaction has already been signed.
2106 printf("CommitTransaction() : Error: Transaction not valid");
2110 wtxNew.RelayWalletTransaction();
2113 LOCK2(cs_main, cs_wallet);
2115 // This is only to keep the database open to defeat the auto-flush for the
2116 // duration of this scope. This is the only place where this optimization
2117 // maybe makes sense; please don't do it anywhere else.
2118 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
2120 // Take key pair from key pool so it won't be used again
2121 reservekey.KeepKey();
2123 // Add tx to wallet, because if it has change it's also ours,
2124 // otherwise just for transaction history.
2125 AddToWallet(wtxNew);
2127 // Mark old coins as spent
2128 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
2130 CWalletTx &coin = mapWallet[txin.prevout.hash];
2131 coin.BindWallet(this);
2132 coin.MarkSpent(txin.prevout.n);
2134 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
2135 vMintingWalletUpdated.push_back(coin.GetHash());
2148 string CWallet::SendMoney(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, bool fAskFee)
2152 return _("Invalid amount");
2153 if (nValue + nTransactionFee > GetBalance())
2154 return _("Insufficient funds");
2156 CReserveKey reservekey(this);
2157 int64_t nFeeRequired;
2161 string strError = _("Error: Wallet locked, unable to create transaction ");
2162 printf("SendMoney() : %s", strError.c_str());
2165 if (fWalletUnlockMintOnly)
2167 string strError = _("Error: Wallet unlocked for block minting only, unable to create transaction.");
2168 printf("SendMoney() : %s", strError.c_str());
2171 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
2174 if (nValue + nFeeRequired > GetBalance())
2175 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());
2177 strError = _("Error: Transaction creation failed ");
2178 printf("SendMoney() : %s", strError.c_str());
2182 if (fAskFee && !uiInterface.ThreadSafeAskFee(nFeeRequired, _("Sending...")))
2185 if (!CommitTransaction(wtxNew, reservekey))
2186 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.");
2191 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
2195 fFirstRunRet = false;
2196 DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
2197 if (nLoadWalletRet == DB_NEED_REWRITE)
2199 if (CDB::Rewrite(strWalletFile, "\x04pool"))
2202 // Note: can't top-up keypool here, because wallet is locked.
2203 // User will be prompted to unlock wallet the next operation
2204 // the requires a new key.
2208 if (nLoadWalletRet != DB_LOAD_OK)
2209 return nLoadWalletRet;
2210 fFirstRunRet = !vchDefaultKey.IsValid();
2212 NewThread(ThreadFlushWalletDB, &strWalletFile);
2216 DBErrors CWallet::ZapWalletTx()
2220 DBErrors nZapWalletTxRet = CWalletDB(strWalletFile,"cr+").ZapWalletTx(this);
2221 if (nZapWalletTxRet == DB_NEED_REWRITE)
2223 if (CDB::Rewrite(strWalletFile, "\x04pool"))
2227 // Note: can't top-up keypool here, because wallet is locked.
2228 // User will be prompted to unlock wallet the next operation
2229 // the requires a new key.
2233 if (nZapWalletTxRet != DB_LOAD_OK)
2234 return nZapWalletTxRet;
2239 bool CWallet::SetAddressBookName(const CTxDestination& address, const string& strName)
2241 return SetAddressBookName(CBitcoinAddress(address), strName);
2244 bool CWallet::SetAddressBookName(const CBitcoinAddress& address, const string& strName)
2246 std::map<CBitcoinAddress, string>::iterator mi = mapAddressBook.find(address);
2247 mapAddressBook[address] = strName;
2248 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != MINE_NO, (mi == mapAddressBook.end()) ? CT_NEW : CT_UPDATED);
2251 return CWalletDB(strWalletFile).WriteName(address.ToString(), strName);
2254 bool CWallet::DelAddressBookName(const CBitcoinAddress& address)
2256 mapAddressBook.erase(address);
2257 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != MINE_NO, CT_DELETED);
2260 return CWalletDB(strWalletFile).EraseName(address.ToString());
2264 void CWallet::PrintWallet(const CBlock& block)
2268 if (block.IsProofOfStake() && mapWallet.count(block.vtx[1].GetHash()))
2270 CWalletTx& wtx = mapWallet[block.vtx[1].GetHash()];
2271 printf(" PoS: %d %d %" PRId64 "", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit(MINE_ALL));
2273 else if (mapWallet.count(block.vtx[0].GetHash()))
2275 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
2276 printf(" PoW: %d %d %" PRId64 "", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit(MINE_ALL));
2282 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
2286 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
2287 if (mi != mapWallet.end())
2296 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
2300 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
2303 vchDefaultKey = vchPubKey;
2307 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
2309 if (!pwallet->fFileBacked)
2311 strWalletFileOut = pwallet->strWalletFile;
2316 // Mark old keypool keys as used,
2317 // and generate all new keys
2319 bool CWallet::NewKeyPool(unsigned int nSize)
2323 CWalletDB walletdb(strWalletFile);
2324 BOOST_FOREACH(int64_t nIndex, setKeyPool)
2325 walletdb.ErasePool(nIndex);
2335 nKeys = max<uint64_t>(GetArg("-keypool", 100), 0);
2337 for (uint64_t i = 0; i < nKeys; i++)
2339 uint64_t nIndex = i+1;
2340 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
2341 setKeyPool.insert(nIndex);
2343 printf("CWallet::NewKeyPool wrote %" PRIu64 " new keys\n", nKeys);
2348 bool CWallet::TopUpKeyPool(unsigned int nSize)
2356 CWalletDB walletdb(strWalletFile);
2359 uint64_t nTargetSize;
2361 nTargetSize = nSize;
2363 nTargetSize = max<uint64_t>(GetArg("-keypool", 100), 0);
2365 while (setKeyPool.size() < (nTargetSize + 1))
2368 if (!setKeyPool.empty())
2369 nEnd = *(--setKeyPool.end()) + 1;
2370 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
2371 throw runtime_error("TopUpKeyPool() : writing generated key failed");
2372 setKeyPool.insert(nEnd);
2373 printf("keypool added key %" PRIu64 ", size=%" PRIszu "\n", nEnd, setKeyPool.size());
2379 void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool)
2382 keypool.vchPubKey = CPubKey();
2389 // Get the oldest key
2390 if(setKeyPool.empty())
2393 CWalletDB walletdb(strWalletFile);
2395 nIndex = *(setKeyPool.begin());
2396 setKeyPool.erase(setKeyPool.begin());
2397 if (!walletdb.ReadPool(nIndex, keypool))
2398 throw runtime_error("ReserveKeyFromKeyPool() : read failed");
2399 if (!HaveKey(keypool.vchPubKey.GetID()))
2400 throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
2401 assert(keypool.vchPubKey.IsValid());
2402 if (fDebug && GetBoolArg("-printkeypool"))
2403 printf("keypool reserve %" PRId64 "\n", nIndex);
2407 int64_t CWallet::AddReserveKey(const CKeyPool& keypool)
2410 LOCK2(cs_main, cs_wallet);
2411 CWalletDB walletdb(strWalletFile);
2413 int64_t nIndex = 1 + *(--setKeyPool.end());
2414 if (!walletdb.WritePool(nIndex, keypool))
2415 throw runtime_error("AddReserveKey() : writing added key failed");
2416 setKeyPool.insert(nIndex);
2422 void CWallet::KeepKey(int64_t nIndex)
2424 // Remove from key pool
2427 CWalletDB walletdb(strWalletFile);
2428 walletdb.ErasePool(nIndex);
2431 printf("keypool keep %" PRId64 "\n", nIndex);
2434 void CWallet::ReturnKey(int64_t nIndex)
2436 // Return to key pool
2439 setKeyPool.insert(nIndex);
2442 printf("keypool return %" PRId64 "\n", nIndex);
2445 bool CWallet::GetKeyFromPool(CPubKey& result, bool fAllowReuse)
2451 ReserveKeyFromKeyPool(nIndex, keypool);
2454 if (fAllowReuse && vchDefaultKey.IsValid())
2456 result = vchDefaultKey;
2459 if (IsLocked()) return false;
2460 result = GenerateNewKey();
2464 result = keypool.vchPubKey;
2469 int64_t CWallet::GetOldestKeyPoolTime()
2473 ReserveKeyFromKeyPool(nIndex, keypool);
2477 return keypool.nTime;
2480 std::map<CBitcoinAddress, int64_t> CWallet::GetAddressBalances()
2482 map<CBitcoinAddress, int64_t> balances;
2486 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2488 CWalletTx *pcoin = &walletEntry.second;
2490 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
2493 if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0)
2496 int nDepth = pcoin->GetDepthInMainChain();
2497 if (nDepth < (pcoin->IsFromMe(MINE_ALL) ? 0 : 1))
2500 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2502 CBitcoinAddress addr;
2503 if (!IsMine(pcoin->vout[i]))
2505 if(!ExtractAddress(*this, pcoin->vout[i].scriptPubKey, addr))
2508 int64_t n = pcoin->IsSpent(i) ? 0 : pcoin->vout[i].nValue;
2510 if (!balances.count(addr))
2512 balances[addr] += n;
2520 set< set<CBitcoinAddress> > CWallet::GetAddressGroupings()
2522 set< set<CBitcoinAddress> > groupings;
2523 set<CBitcoinAddress> grouping;
2525 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2527 CWalletTx *pcoin = &walletEntry.second;
2529 if (pcoin->vin.size() > 0 && IsMine(pcoin->vin[0]))
2531 // group all input addresses with each other
2532 BOOST_FOREACH(CTxIn txin, pcoin->vin)
2534 CBitcoinAddress address;
2535 if(!ExtractAddress(*this, mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
2537 grouping.insert(address);
2540 // group change with input addresses
2541 BOOST_FOREACH(CTxOut txout, pcoin->vout)
2542 if (IsChange(txout))
2544 CWalletTx tx = mapWallet[pcoin->vin[0].prevout.hash];
2545 CBitcoinAddress txoutAddr;
2546 if(!ExtractAddress(*this, txout.scriptPubKey, txoutAddr))
2548 grouping.insert(txoutAddr);
2550 groupings.insert(grouping);
2554 // group lone addrs by themselves
2555 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2556 if (IsMine(pcoin->vout[i]))
2558 CBitcoinAddress address;
2559 if(!ExtractAddress(*this, pcoin->vout[i].scriptPubKey, address))
2561 grouping.insert(address);
2562 groupings.insert(grouping);
2567 set< set<CBitcoinAddress>* > uniqueGroupings; // a set of pointers to groups of addresses
2568 map< CBitcoinAddress, set<CBitcoinAddress>* > setmap; // map addresses to the unique group containing it
2569 BOOST_FOREACH(set<CBitcoinAddress> grouping, groupings)
2571 // make a set of all the groups hit by this new group
2572 set< set<CBitcoinAddress>* > hits;
2573 map< CBitcoinAddress, set<CBitcoinAddress>* >::iterator it;
2574 BOOST_FOREACH(CBitcoinAddress address, grouping)
2575 if ((it = setmap.find(address)) != setmap.end())
2576 hits.insert((*it).second);
2578 // merge all hit groups into a new single group and delete old groups
2579 set<CBitcoinAddress>* merged = new set<CBitcoinAddress>(grouping);
2580 BOOST_FOREACH(set<CBitcoinAddress>* hit, hits)
2582 merged->insert(hit->begin(), hit->end());
2583 uniqueGroupings.erase(hit);
2586 uniqueGroupings.insert(merged);
2589 BOOST_FOREACH(CBitcoinAddress element, *merged)
2590 setmap[element] = merged;
2593 set< set<CBitcoinAddress> > ret;
2594 BOOST_FOREACH(set<CBitcoinAddress>* uniqueGrouping, uniqueGroupings)
2596 ret.insert(*uniqueGrouping);
2597 delete uniqueGrouping;
2603 // ppcoin: check 'spent' consistency between wallet and txindex
2604 // ppcoin: fix wallet spent state according to txindex
2605 void CWallet::FixSpentCoins(int& nMismatchFound, int64_t& nBalanceInQuestion, bool fCheckOnly)
2608 nBalanceInQuestion = 0;
2611 vector<CWalletTx*> vCoins;
2612 vCoins.reserve(mapWallet.size());
2613 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2614 vCoins.push_back(&(*it).second);
2617 BOOST_FOREACH(CWalletTx* pcoin, vCoins)
2619 // Find the corresponding transaction index
2621 if (!txdb.ReadTxIndex(pcoin->GetHash(), txindex))
2623 for (unsigned int n=0; n < pcoin->vout.size(); n++)
2625 if (IsMine(pcoin->vout[n]) && pcoin->IsSpent(n) && (txindex.vSpent.size() <= n || txindex.vSpent[n].IsNull()))
2627 printf("FixSpentCoins found lost coin %sppc %s[%u], %s\n",
2628 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2630 nBalanceInQuestion += pcoin->vout[n].nValue;
2633 pcoin->MarkUnspent(n);
2634 pcoin->WriteToDisk();
2637 else if (IsMine(pcoin->vout[n]) && !pcoin->IsSpent(n) && (txindex.vSpent.size() > n && !txindex.vSpent[n].IsNull()))
2639 printf("FixSpentCoins found spent coin %sppc %s[%u], %s\n",
2640 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2642 nBalanceInQuestion += pcoin->vout[n].nValue;
2645 pcoin->MarkSpent(n);
2646 pcoin->WriteToDisk();
2652 if(IsMine((CTransaction)*pcoin) && (pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetDepthInMainChain() == 0)
2654 printf("FixSpentCoins %s tx %s\n", fCheckOnly ? "found" : "removed", pcoin->GetHash().ToString().c_str());
2657 EraseFromWallet(pcoin->GetHash());
2663 // ppcoin: disable transaction (only for coinstake)
2664 void CWallet::DisableTransaction(const CTransaction &tx)
2666 if (!tx.IsCoinStake() || !IsFromMe(tx))
2667 return; // only disconnecting coinstake requires marking input unspent
2670 BOOST_FOREACH(const CTxIn& txin, tx.vin)
2672 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
2673 if (mi != mapWallet.end())
2675 CWalletTx& prev = (*mi).second;
2676 if (txin.prevout.n < prev.vout.size() && IsMine(prev.vout[txin.prevout.n]))
2678 prev.MarkUnspent(txin.prevout.n);
2685 CPubKey CReserveKey::GetReservedKey()
2690 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
2692 vchPubKey = keypool.vchPubKey;
2695 printf("CReserveKey::GetReservedKey(): Warning: Using default key instead of a new key, top up your keypool!");
2696 vchPubKey = pwallet->vchDefaultKey;
2699 assert(vchPubKey.IsValid());
2703 void CReserveKey::KeepKey()
2706 pwallet->KeepKey(nIndex);
2708 vchPubKey = CPubKey();
2711 void CReserveKey::ReturnKey()
2714 pwallet->ReturnKey(nIndex);
2716 vchPubKey = CPubKey();
2719 void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
2723 CWalletDB walletdb(strWalletFile);
2725 LOCK2(cs_main, cs_wallet);
2726 BOOST_FOREACH(const int64_t& id, setKeyPool)
2729 if (!walletdb.ReadPool(id, keypool))
2730 throw runtime_error("GetAllReserveKeyHashes() : read failed");
2731 assert(keypool.vchPubKey.IsValid());
2732 CKeyID keyID = keypool.vchPubKey.GetID();
2733 if (!HaveKey(keyID))
2734 throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
2735 setAddress.insert(keyID);
2739 void CWallet::UpdatedTransaction(const uint256 &hashTx)
2743 // Only notify UI if this transaction is in this wallet
2744 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
2745 if (mi != mapWallet.end())
2747 NotifyTransactionChanged(this, hashTx, CT_UPDATED);
2748 vMintingWalletUpdated.push_back(hashTx);
2753 void CWallet::GetAddresses(std::map<CBitcoinAddress, int64_t> &mapAddresses) const {
2754 mapAddresses.clear();
2756 // get birth times for keys with metadata
2757 for (std::map<CBitcoinAddress, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++) {
2758 mapAddresses[it->first] = it->second.nCreateTime ? it->second.nCreateTime : 0;
2761 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
2762 // iterate over all wallet transactions...
2763 const CWalletTx &wtx = (*it).second;
2764 if (wtx.hashBlock == 0)
2765 continue; // skip unconfirmed transactions
2767 for(std::vector<CTxOut>::const_iterator it2 = wtx.vout.begin(); it2 != wtx.vout.end(); it2++) {
2768 const CTxOut &out = (*it2);
2769 // iterate over all their outputs
2770 CBitcoinAddress addressRet;
2771 if (ExtractAddress(*this, out.scriptPubKey, addressRet)) {
2772 if (mapAddresses.find(addressRet) != mapAddresses.end() && (mapAddresses[addressRet] == 0 || mapAddresses[addressRet] > wtx.nTime))
2773 mapAddresses[addressRet] = wtx.nTime;
2776 // multisig output affects more than one key
2777 std::vector<CKeyID> vAffected;
2778 ::ExtractAffectedKeys(*this, out.scriptPubKey, vAffected);
2780 for(std::vector<CKeyID>::const_iterator it3 = vAffected.begin(); it3 != vAffected.end(); it3++) {
2781 CBitcoinAddress addrAffected(*it3);
2782 if (mapAddresses.find(addrAffected) != mapAddresses.end() && (mapAddresses[addrAffected] == 0 || mapAddresses[addrAffected] > wtx.nTime))
2783 mapAddresses[addrAffected] = wtx.nTime;
2791 void CWallet::ClearOrphans()
2793 list<uint256> orphans;
2796 for(map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2798 const CWalletTx *wtx = &(*it).second;
2799 if((wtx->IsCoinBase() || wtx->IsCoinStake()) && !wtx->IsInMainChain())
2801 orphans.push_back(wtx->GetHash());
2805 for(list<uint256>::const_iterator it = orphans.begin(); it != orphans.end(); ++it)
2806 EraseFromWallet(*it);