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>
21 bool fCoinsDataActual;
23 //////////////////////////////////////////////////////////////////////////////
28 struct CompareValueOnly
30 bool operator()(const pair<int64_t, pair<const CWalletTx*, unsigned int> >& t1,
31 const pair<int64_t, pair<const CWalletTx*, unsigned int> >& t2) const
33 return t1.first < t2.first;
37 CPubKey CWallet::GenerateNewKey()
39 bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
43 key.MakeNewKey(fCompressed);
45 // Compressed public keys were introduced in version 0.6.0
47 SetMinVersion(FEATURE_COMPRPUBKEY);
49 CPubKey pubkey = key.GetPubKey();
51 // Create new metadata
52 int64_t nCreationTime = GetTime();
53 mapKeyMetadata[pubkey.GetID()] = CKeyMetadata(nCreationTime);
54 if (!nTimeFirstKey || nCreationTime < nTimeFirstKey)
55 nTimeFirstKey = nCreationTime;
58 throw std::runtime_error("CWallet::GenerateNewKey() : AddKey failed");
59 return key.GetPubKey();
62 bool CWallet::AddKey(const CKey& key)
64 CPubKey pubkey = key.GetPubKey();
65 if (!CCryptoKeyStore::AddKey(key))
70 return CWalletDB(strWalletFile).WriteKey(pubkey, key.GetPrivKey(), mapKeyMetadata[pubkey.GetID()]);
74 bool CWallet::AddCryptedKey(const CPubKey &vchPubKey, const vector<unsigned char> &vchCryptedSecret)
76 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
79 // check if we need to remove from watch-only
81 script.SetDestination(vchPubKey.GetID());
82 if (HaveWatchOnly(script))
83 RemoveWatchOnly(script);
89 if (pwalletdbEncryption)
90 return pwalletdbEncryption->WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]);
92 return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]);
97 bool CWallet::LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &meta)
99 if (meta.nCreateTime && (!nTimeFirstKey || meta.nCreateTime < nTimeFirstKey))
100 nTimeFirstKey = meta.nCreateTime;
102 mapKeyMetadata[pubkey.GetID()] = meta;
106 bool CWallet::AddCScript(const CScript& redeemScript)
108 if (!CCryptoKeyStore::AddCScript(redeemScript))
112 return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript);
115 bool CWallet::LoadCScript(const CScript& redeemScript)
117 /* A sanity check was added in commit 5ed0a2b to avoid adding redeemScripts
118 * that never can be redeemed. However, old wallets may still contain
119 * these. Do not add them to the wallet and warn. */
120 if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
122 std::string strAddr = CBitcoinAddress(redeemScript.GetID()).ToString();
123 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",
124 redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr.c_str());
128 return CCryptoKeyStore::AddCScript(redeemScript);
132 bool CWallet::AddWatchOnly(const CScript &dest)
134 if (!CCryptoKeyStore::AddWatchOnly(dest))
136 nTimeFirstKey = 1; // No birthday information for watch-only keys.
137 NotifyWatchonlyChanged(true);
140 return CWalletDB(strWalletFile).WriteWatchOnly(dest);
143 bool CWallet::RemoveWatchOnly(const CScript &dest)
146 if (!CCryptoKeyStore::RemoveWatchOnly(dest))
148 if (!HaveWatchOnly())
149 NotifyWatchonlyChanged(false);
151 if (!CWalletDB(strWalletFile).EraseWatchOnly(dest))
157 bool CWallet::LoadWatchOnly(const CScript &dest)
159 return CCryptoKeyStore::AddWatchOnly(dest);
162 // ppcoin: optional setting to unlock wallet for block minting only;
163 // serves to disable the trivial sendmoney when OS account compromised
164 bool fWalletUnlockMintOnly = false;
166 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
172 CKeyingMaterial vMasterKey;
176 BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
178 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
180 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
182 if (CCryptoKeyStore::Unlock(vMasterKey))
189 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
191 bool fWasLocked = IsLocked();
198 CKeyingMaterial vMasterKey;
199 BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
201 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
203 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
205 if (CCryptoKeyStore::Unlock(vMasterKey))
207 int64_t nStartTime = GetTimeMillis();
208 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
209 pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
211 nStartTime = GetTimeMillis();
212 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
213 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
215 if (pMasterKey.second.nDeriveIterations < 25000)
216 pMasterKey.second.nDeriveIterations = 25000;
218 printf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
220 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
222 if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
224 CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
235 void CWallet::SetBestChain(const CBlockLocator& loc)
237 CWalletDB walletdb(strWalletFile);
238 walletdb.WriteBestBlock(loc);
241 // This class implements an addrIncoming entry that causes pre-0.4
242 // clients to crash on startup if reading a private-key-encrypted wallet.
243 class CCorruptAddress
248 if (nType & SER_DISK)
253 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
255 if (nWalletVersion >= nVersion)
258 // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
259 if (fExplicit && nVersion > nWalletMaxVersion)
260 nVersion = FEATURE_LATEST;
262 nWalletVersion = nVersion;
264 if (nVersion > nWalletMaxVersion)
265 nWalletMaxVersion = nVersion;
269 CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile);
270 if (nWalletVersion > 40000)
271 pwalletdb->WriteMinVersion(nWalletVersion);
279 bool CWallet::SetMaxVersion(int nVersion)
281 // cannot downgrade below current version
282 if (nWalletVersion > nVersion)
285 nWalletMaxVersion = nVersion;
290 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
295 CKeyingMaterial vMasterKey;
296 RandAddSeedPerfmon();
298 vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
299 RAND_bytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
301 CMasterKey kMasterKey;
303 RandAddSeedPerfmon();
304 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
305 RAND_bytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
308 int64_t nStartTime = GetTimeMillis();
309 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
310 kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
312 nStartTime = GetTimeMillis();
313 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
314 kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
316 if (kMasterKey.nDeriveIterations < 25000)
317 kMasterKey.nDeriveIterations = 25000;
319 printf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
321 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
323 if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
328 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
331 pwalletdbEncryption = new CWalletDB(strWalletFile);
332 if (!pwalletdbEncryption->TxnBegin())
334 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
337 if (!EncryptKeys(vMasterKey))
340 pwalletdbEncryption->TxnAbort();
341 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.
344 // Encryption was introduced in version 0.4.0
345 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
349 if (!pwalletdbEncryption->TxnCommit())
350 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.
352 delete pwalletdbEncryption;
353 pwalletdbEncryption = NULL;
357 Unlock(strWalletPassphrase);
361 // Need to completely rewrite the wallet file; if we don't, bdb might keep
362 // bits of the unencrypted private key in slack space in the database file.
363 CDB::Rewrite(strWalletFile);
366 NotifyStatusChanged(this);
371 bool CWallet::DecryptWallet(const SecureString& strWalletPassphrase)
377 CKeyingMaterial vMasterKey;
381 BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
383 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
385 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
387 if (!CCryptoKeyStore::Unlock(vMasterKey))
393 pwalletdbDecryption = new CWalletDB(strWalletFile);
394 if (!pwalletdbDecryption->TxnBegin())
398 if (!DecryptKeys(vMasterKey))
401 pwalletdbDecryption->TxnAbort();
402 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.
407 // Overwrite crypted keys
408 KeyMap::const_iterator mi = mapKeys.begin();
409 while (mi != mapKeys.end())
412 key.SetSecret((*mi).second.first, (*mi).second.second);
413 pwalletdbDecryption->EraseCryptedKey(key.GetPubKey());
414 pwalletdbDecryption->WriteKey(key.GetPubKey(), key.GetPrivKey(), mapKeyMetadata[(*mi).first]);
419 MasterKeyMap::const_iterator mk = mapMasterKeys.begin();
420 while (mk != mapMasterKeys.end())
422 pwalletdbDecryption->EraseMasterKey((*mk).first);
426 if (!pwalletdbDecryption->TxnCommit())
427 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.
429 delete pwalletdbDecryption;
430 pwalletdbDecryption = NULL;
433 // Need to completely rewrite the wallet file; if we don't, bdb might keep
434 // encrypted private keys in the database file which can be a reason of consistency issues.
435 CDB::Rewrite(strWalletFile);
437 NotifyStatusChanged(this);
442 int64_t CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
444 int64_t nRet = nOrderPosNext++;
446 pwalletdb->WriteOrderPosNext(nOrderPosNext);
448 CWalletDB(strWalletFile).WriteOrderPosNext(nOrderPosNext);
453 CWallet::TxItems CWallet::OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount)
455 CWalletDB walletdb(strWalletFile);
457 // First: get all CWalletTx and CAccountingEntry into a sorted-by-order multimap.
460 // Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry
461 // would make this much faster for applications that do this a lot.
462 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
464 CWalletTx* wtx = &((*it).second);
465 txOrdered.insert(make_pair(wtx->nOrderPos, TxPair(wtx, (CAccountingEntry*)0)));
468 walletdb.ListAccountCreditDebit(strAccount, acentries);
469 BOOST_FOREACH(CAccountingEntry& entry, acentries)
471 txOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
477 void CWallet::WalletUpdateSpent(const CTransaction &tx, bool fBlock)
479 // Anytime a signature is successfully verified, it's proof the outpoint is spent.
480 // Update the wallet spent flag if it doesn't know due to wallet.dat being
481 // restored from backup or the user making copies of wallet.dat.
484 BOOST_FOREACH(const CTxIn& txin, tx.vin)
486 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
487 if (mi != mapWallet.end())
489 CWalletTx& wtx = (*mi).second;
490 if (txin.prevout.n >= wtx.vout.size())
491 printf("WalletUpdateSpent: bad wtx %s\n", wtx.GetHash().ToString().c_str());
492 else if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n]))
494 printf("WalletUpdateSpent found spent coin %snvc %s\n", FormatMoney(wtx.GetCredit(MINE_ALL)).c_str(), wtx.GetHash().ToString().c_str());
495 wtx.MarkSpent(txin.prevout.n);
497 NotifyTransactionChanged(this, txin.prevout.hash, CT_UPDATED);
498 vMintingWalletUpdated.push_back(txin.prevout.hash);
505 uint256 hash = tx.GetHash();
506 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hash);
507 CWalletTx& wtx = (*mi).second;
509 BOOST_FOREACH(const CTxOut& txout, tx.vout)
513 wtx.MarkUnspent(&txout - &tx.vout[0]);
515 NotifyTransactionChanged(this, hash, CT_UPDATED);
516 vMintingWalletUpdated.push_back(hash);
524 void CWallet::MarkDirty()
528 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
529 item.second.MarkDirty();
533 bool CWallet::AddToWallet(const CWalletTx& wtxIn)
535 uint256 hash = wtxIn.GetHash();
538 // Inserts only if not already there, returns tx inserted or tx found
539 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
540 CWalletTx& wtx = (*ret.first).second;
541 wtx.BindWallet(this);
542 bool fInsertedNew = ret.second;
545 wtx.nTimeReceived = GetAdjustedTime();
546 wtx.nOrderPos = IncOrderPosNext();
548 wtx.nTimeSmart = wtx.nTimeReceived;
549 if (wtxIn.hashBlock != 0)
551 if (mapBlockIndex.count(wtxIn.hashBlock))
553 unsigned int latestNow = wtx.nTimeReceived;
554 unsigned int latestEntry = 0;
556 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
557 int64_t latestTolerated = latestNow + 300;
558 std::list<CAccountingEntry> acentries;
559 TxItems txOrdered = OrderedTxItems(acentries);
560 for (TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
562 CWalletTx *const pwtx = (*it).second.first;
565 CAccountingEntry *const pacentry = (*it).second.second;
569 nSmartTime = pwtx->nTimeSmart;
571 nSmartTime = pwtx->nTimeReceived;
574 nSmartTime = pacentry->nTime;
575 if (nSmartTime <= latestTolerated)
577 latestEntry = nSmartTime;
578 if (nSmartTime > latestNow)
579 latestNow = nSmartTime;
585 unsigned int& blocktime = mapBlockIndex[wtxIn.hashBlock]->nTime;
586 wtx.nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
589 printf("AddToWallet() : found %s in block %s not in index\n",
590 wtxIn.GetHash().ToString().substr(0,10).c_str(),
591 wtxIn.hashBlock.ToString().c_str());
595 bool fUpdated = false;
599 if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
601 wtx.hashBlock = wtxIn.hashBlock;
604 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
606 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
607 wtx.nIndex = wtxIn.nIndex;
610 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
612 wtx.fFromMe = wtxIn.fFromMe;
615 fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);
619 printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
622 if (fInsertedNew || fUpdated)
623 if (!wtx.WriteToDisk())
626 // If default receiving address gets used, replace it with a new one
627 CScript scriptDefaultKey;
628 scriptDefaultKey.SetDestination(vchDefaultKey.GetID());
629 BOOST_FOREACH(const CTxOut& txout, wtx.vout)
631 if (txout.scriptPubKey == scriptDefaultKey)
633 CPubKey newDefaultKey;
634 if (GetKeyFromPool(newDefaultKey, false))
636 SetDefaultKey(newDefaultKey);
637 SetAddressBookName(vchDefaultKey.GetID(), "");
642 // since AddToWallet is called directly for self-originating transactions, check for consumption of own coins
643 WalletUpdateSpent(wtx, (wtxIn.hashBlock != 0));
645 // Notify UI of new or updated transaction
646 NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
647 vMintingWalletUpdated.push_back(hash);
648 // notify an external script when a wallet transaction comes in or is updated
649 std::string strCmd = GetArg("-walletnotify", "");
651 if ( !strCmd.empty())
653 boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
654 boost::thread t(runCommand, strCmd); // thread runs free
661 // Add a transaction to the wallet, or update it.
662 // pblock is optional, but should be provided if the transaction is known to be in a block.
663 // If fUpdate is true, existing transactions will be updated.
664 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fFindBlock)
666 uint256 hash = tx.GetHash();
669 bool fExisted = mapWallet.count(hash);
670 if (fExisted && !fUpdate) return false;
671 if (fExisted || IsMine(tx) || IsFromMe(tx))
673 CWalletTx wtx(this,tx);
674 // Get merkle branch if transaction was found in a block
676 wtx.SetMerkleBranch(pblock);
677 return AddToWallet(wtx);
680 WalletUpdateSpent(tx);
685 bool CWallet::EraseFromWallet(uint256 hash)
691 if (mapWallet.erase(hash))
692 CWalletDB(strWalletFile).EraseTx(hash);
698 isminetype CWallet::IsMine(const CTxIn &txin) const
702 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
703 if (mi != mapWallet.end())
705 const CWalletTx& prev = (*mi).second;
706 if (txin.prevout.n < prev.vout.size())
707 return IsMine(prev.vout[txin.prevout.n]);
713 int64_t CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
717 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
718 if (mi != mapWallet.end())
720 const CWalletTx& prev = (*mi).second;
721 if (txin.prevout.n < prev.vout.size())
722 if (IsMine(prev.vout[txin.prevout.n]) & filter)
723 return prev.vout[txin.prevout.n].nValue;
729 bool CWallet::IsChange(const CTxOut& txout) const
731 // TODO: fix handling of 'change' outputs. The assumption is that any
732 // payment to a script that is ours, but isn't in the address book
733 // is change. That assumption is likely to break when we implement multisignature
734 // wallets that return change back into a multi-signature-protected address;
735 // a better way of identifying which outputs are 'the send' and which are
736 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
737 // which output, if any, was change).
738 if (::IsMine(*this, txout.scriptPubKey))
740 CTxDestination address;
741 if (!ExtractDestination(txout.scriptPubKey, address))
745 if (!mapAddressBook.count(address))
751 int64_t CWalletTx::GetTxTime() const
756 int CWalletTx::GetRequestCount() const
758 // Returns -1 if it wasn't being tracked
761 LOCK(pwallet->cs_wallet);
762 if (IsCoinBase() || IsCoinStake())
767 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
768 if (mi != pwallet->mapRequestCount.end())
769 nRequests = (*mi).second;
774 // Did anyone request this transaction?
775 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
776 if (mi != pwallet->mapRequestCount.end())
778 nRequests = (*mi).second;
780 // How about the block it's in?
781 if (nRequests == 0 && hashBlock != 0)
783 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
784 if (mi != pwallet->mapRequestCount.end())
785 nRequests = (*mi).second;
787 nRequests = 1; // If it's in someone else's block it must have got out
795 void CWalletTx::GetAmounts(int64_t& nGeneratedImmature, int64_t& nGeneratedMature, list<pair<CTxDestination, int64_t> >& listReceived,
796 list<pair<CTxDestination, int64_t> >& listSent, int64_t& nFee, string& strSentAccount, const isminefilter& filter) const
798 nGeneratedImmature = nGeneratedMature = nFee = 0;
799 listReceived.clear();
801 strSentAccount = strFromAccount;
803 if (IsCoinBase() || IsCoinStake())
805 if (GetBlocksToMaturity() > 0)
806 nGeneratedImmature = pwallet->GetCredit(*this, filter);
808 nGeneratedMature = GetCredit(filter);
813 int64_t nDebit = GetDebit(filter);
814 if (nDebit > 0) // debit>0 means we signed/sent this transaction
816 int64_t nValueOut = GetValueOut();
817 nFee = nDebit - nValueOut;
821 BOOST_FOREACH(const CTxOut& txout, vout)
823 isminetype fIsMine = pwallet->IsMine(txout);
824 // Only need to handle txouts if AT LEAST one of these is true:
825 // 1) they debit from us (sent)
826 // 2) the output is to us (received)
829 // Don't report 'change' txouts
830 if (pwallet->IsChange(txout))
833 else if (!(fIsMine & filter))
836 // In either case, we need to get the destination address
837 CTxDestination address;
838 if (!ExtractDestination(txout.scriptPubKey, address))
840 printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
841 this->GetHash().ToString().c_str());
842 address = CNoDestination();
845 // If we are debited by the transaction, add the output as a "sent" entry
847 listSent.push_back(make_pair(address, txout.nValue));
849 // If we are receiving the output, add it as a "received" entry
850 if (fIsMine & filter)
851 listReceived.push_back(make_pair(address, txout.nValue));
856 void CWalletTx::GetAccountAmounts(const string& strAccount, int64_t& nGenerated, int64_t& nReceived,
857 int64_t& nSent, int64_t& nFee, const isminefilter& filter) const
859 nGenerated = nReceived = nSent = nFee = 0;
861 int64_t allGeneratedImmature, allGeneratedMature, allFee;
862 allGeneratedImmature = allGeneratedMature = allFee = 0;
863 string strSentAccount;
864 list<pair<CTxDestination, int64_t> > listReceived;
865 list<pair<CTxDestination, int64_t> > listSent;
866 GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount, filter);
868 if (strAccount == "")
869 nGenerated = allGeneratedMature;
870 if (strAccount == strSentAccount)
872 BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64_t)& s, listSent)
877 LOCK(pwallet->cs_wallet);
878 BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64_t)& r, listReceived)
880 if (pwallet->mapAddressBook.count(r.first))
882 map<CTxDestination, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);
883 if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)
884 nReceived += r.second;
886 else if (strAccount.empty())
888 nReceived += r.second;
894 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
898 const int COPY_DEPTH = 3;
899 if (SetMerkleBranch() < COPY_DEPTH)
901 vector<uint256> vWorkQueue;
902 BOOST_FOREACH(const CTxIn& txin, vin)
903 vWorkQueue.push_back(txin.prevout.hash);
905 // This critsect is OK because txdb is already open
907 LOCK(pwallet->cs_wallet);
908 map<uint256, const CMerkleTx*> mapWalletPrev;
909 set<uint256> setAlreadyDone;
910 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
912 uint256 hash = vWorkQueue[i];
913 if (setAlreadyDone.count(hash))
915 setAlreadyDone.insert(hash);
918 map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
919 if (mi != pwallet->mapWallet.end())
922 BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev)
923 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
925 else if (mapWalletPrev.count(hash))
927 tx = *mapWalletPrev[hash];
929 else if (!fClient && txdb.ReadDiskTx(hash, tx))
935 printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
939 int nDepth = tx.SetMerkleBranch();
940 vtxPrev.push_back(tx);
942 if (nDepth < COPY_DEPTH)
944 BOOST_FOREACH(const CTxIn& txin, tx.vin)
945 vWorkQueue.push_back(txin.prevout.hash);
951 reverse(vtxPrev.begin(), vtxPrev.end());
954 bool CWalletTx::WriteToDisk()
956 return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
959 // Scan the block chain (starting in pindexStart) for transactions
960 // from or to us. If fUpdate is true, found transactions that already
961 // exist in the wallet will be updated.
962 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
966 CBlockIndex* pindex = pindexStart;
972 block.ReadFromDisk(pindex, true);
973 BOOST_FOREACH(CTransaction& tx, block.vtx)
975 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
978 pindex = pindex->pnext;
984 int CWallet::ScanForWalletTransaction(const uint256& hashTx)
987 tx.ReadFromDisk(COutPoint(hashTx, 0));
988 if (AddToWalletIfInvolvingMe(tx, NULL, true, true))
993 void CWallet::ReacceptWalletTransactions()
1001 vector<CDiskTxPos> vMissingTx;
1002 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1004 CWalletTx& wtx = item.second;
1005 if ((wtx.IsCoinBase() && wtx.IsSpent(0)) || (wtx.IsCoinStake() && wtx.IsSpent(1)))
1009 bool fUpdated = false;
1010 if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
1012 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
1013 if (txindex.vSpent.size() != wtx.vout.size())
1015 printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %" PRIszu " != wtx.vout.size() %" PRIszu "\n", txindex.vSpent.size(), wtx.vout.size());
1018 for (unsigned int i = 0; i < txindex.vSpent.size(); i++)
1022 if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i]))
1026 vMissingTx.push_back(txindex.vSpent[i]);
1031 printf("ReacceptWalletTransactions found spent coin %snvc %s\n", FormatMoney(wtx.GetCredit(MINE_ALL)).c_str(), wtx.GetHash().ToString().c_str());
1038 // Re-accept any txes of ours that aren't already in a block
1039 if (!(wtx.IsCoinBase() || wtx.IsCoinStake()))
1040 wtx.AcceptWalletTransaction(txdb, false);
1043 if (!vMissingTx.empty())
1045 // TODO: optimize this to scan just part of the block chain?
1046 if (ScanForWalletTransactions(pindexGenesisBlock))
1047 fRepeat = true; // Found missing transactions: re-do re-accept.
1052 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
1054 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
1056 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
1058 uint256 hash = tx.GetHash();
1059 if (!txdb.ContainsTx(hash))
1060 RelayTransaction((CTransaction)tx, hash);
1063 if (!(IsCoinBase() || IsCoinStake()))
1065 uint256 hash = GetHash();
1066 if (!txdb.ContainsTx(hash))
1068 printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
1069 RelayTransaction((CTransaction)*this, hash);
1074 void CWalletTx::RelayWalletTransaction()
1077 RelayWalletTransaction(txdb);
1080 void CWallet::ResendWalletTransactions()
1082 // Do this infrequently and randomly to avoid giving away
1083 // that these are our transactions.
1084 static int64_t nNextTime;
1085 if (GetTime() < nNextTime)
1087 bool fFirst = (nNextTime == 0);
1088 nNextTime = GetTime() + GetRand(30 * 60);
1092 // Only do it if there's been a new block since last time
1093 static int64_t nLastTime;
1094 if (nTimeBestReceived < nLastTime)
1096 nLastTime = GetTime();
1098 // Rebroadcast any of our txes that aren't in a block yet
1099 printf("ResendWalletTransactions()\n");
1103 // Sort them in chronological order
1104 multimap<unsigned int, CWalletTx*> mapSorted;
1105 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1107 CWalletTx& wtx = item.second;
1108 // Don't rebroadcast until it's had plenty of time that
1109 // it should have gotten in already by now.
1110 if (nTimeBestReceived - (int64_t)wtx.nTimeReceived > 5 * 60)
1111 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
1113 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
1115 CWalletTx& wtx = *item.second;
1116 if (wtx.CheckTransaction())
1117 wtx.RelayWalletTransaction(txdb);
1119 printf("ResendWalletTransactions() : CheckTransaction failed for transaction %s\n", wtx.GetHash().ToString().c_str());
1129 //////////////////////////////////////////////////////////////////////////////
1135 int64_t CWallet::GetBalance() const
1140 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1142 const CWalletTx* pcoin = &(*it).second;
1143 if (pcoin->IsTrusted())
1144 nTotal += pcoin->GetAvailableCredit();
1151 int64_t CWallet::GetWatchOnlyBalance() const
1156 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1158 const CWalletTx* pcoin = &(*it).second;
1159 if (pcoin->IsTrusted())
1160 nTotal += pcoin->GetAvailableWatchCredit();
1167 int64_t CWallet::GetUnconfirmedBalance() const
1172 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1174 const CWalletTx* pcoin = &(*it).second;
1175 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
1176 nTotal += pcoin->GetAvailableCredit();
1182 int64_t CWallet::GetUnconfirmedWatchOnlyBalance() const
1187 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1189 const CWalletTx* pcoin = &(*it).second;
1190 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
1191 nTotal += pcoin->GetAvailableWatchCredit();
1197 int64_t CWallet::GetImmatureBalance() const
1202 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1204 const CWalletTx* pcoin = &(*it).second;
1205 nTotal += pcoin->GetImmatureCredit();
1211 int64_t CWallet::GetImmatureWatchOnlyBalance() const
1216 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1218 const CWalletTx* pcoin = &(*it).second;
1219 nTotal += pcoin->GetImmatureWatchOnlyCredit();
1225 // populate vCoins with vector of spendable COutputs
1226 void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl) const
1232 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1234 const CWalletTx* pcoin = &(*it).second;
1236 if (!pcoin->IsFinal())
1239 if (fOnlyConfirmed && !pcoin->IsTrusted())
1242 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
1245 if(pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0)
1248 for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
1249 isminetype mine = IsMine(pcoin->vout[i]);
1250 if (!(pcoin->IsSpent(i)) && mine != MINE_NO &&
1251 pcoin->vout[i].nValue >= nMinimumInputValue &&
1252 (!coinControl || !coinControl->HasSelected() || coinControl->IsSelected((*it).first, i)))
1254 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain(), mine == MINE_SPENDABLE));
1261 void CWallet::AvailableCoinsMinConf(vector<COutput>& vCoins, int nConf, int64_t nMinValue, int64_t nMaxValue) const
1267 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1269 const CWalletTx* pcoin = &(*it).second;
1271 if (!pcoin->IsFinal())
1274 if(pcoin->GetDepthInMainChain() < nConf)
1277 for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
1278 isminetype mine = IsMine(pcoin->vout[i]);
1280 // ignore coin if it was already spent or we don't own it
1281 if (pcoin->IsSpent(i) || mine == MINE_NO)
1284 // if coin value is between required limits then add new item to vector
1285 if (pcoin->vout[i].nValue >= nMinValue && pcoin->vout[i].nValue < nMaxValue)
1286 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain(), mine == MINE_SPENDABLE));
1292 static void ApproximateBestSubset(vector<pair<int64_t, pair<const CWalletTx*,unsigned int> > >vValue, int64_t nTotalLower, int64_t nTargetValue,
1293 vector<char>& vfBest, int64_t& nBest, int iterations = 1000)
1295 vector<char> vfIncluded;
1297 vfBest.assign(vValue.size(), true);
1298 nBest = nTotalLower;
1300 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
1302 vfIncluded.assign(vValue.size(), false);
1304 bool fReachedTarget = false;
1305 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
1307 for (unsigned int i = 0; i < vValue.size(); i++)
1309 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
1311 nTotal += vValue[i].first;
1312 vfIncluded[i] = true;
1313 if (nTotal >= nTargetValue)
1315 fReachedTarget = true;
1319 vfBest = vfIncluded;
1321 nTotal -= vValue[i].first;
1322 vfIncluded[i] = false;
1330 int64_t CWallet::GetStake() const
1334 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1336 const CWalletTx* pcoin = &(*it).second;
1337 if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1338 nTotal += CWallet::GetCredit(*pcoin, MINE_ALL);
1343 int64_t CWallet::GetWatchOnlyStake() const
1347 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1349 const CWalletTx* pcoin = &(*it).second;
1350 if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1351 nTotal += CWallet::GetCredit(*pcoin, MINE_WATCH_ONLY);
1356 int64_t CWallet::GetNewMint() const
1360 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1362 const CWalletTx* pcoin = &(*it).second;
1363 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1364 nTotal += CWallet::GetCredit(*pcoin, MINE_ALL);
1369 int64_t CWallet::GetWatchOnlyNewMint() const
1373 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1375 const CWalletTx* pcoin = &(*it).second;
1376 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1377 nTotal += CWallet::GetCredit(*pcoin, MINE_WATCH_ONLY);
1382 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
1384 setCoinsRet.clear();
1387 // List of values less than target
1388 pair<int64_t, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
1389 coinLowestLarger.first = std::numeric_limits<int64_t>::max();
1390 coinLowestLarger.second.first = NULL;
1391 vector<pair<int64_t, pair<const CWalletTx*,unsigned int> > > vValue;
1392 int64_t nTotalLower = 0;
1394 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
1396 BOOST_FOREACH(const COutput &output, vCoins)
1398 if (!output.fSpendable)
1401 const CWalletTx *pcoin = output.tx;
1403 if (output.nDepth < (pcoin->IsFromMe(MINE_ALL) ? nConfMine : nConfTheirs))
1408 // Follow the timestamp rules
1409 if (pcoin->nTime > nSpendTime)
1412 int64_t n = pcoin->vout[i].nValue;
1414 pair<int64_t,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1416 if (n == nTargetValue)
1418 setCoinsRet.insert(coin.second);
1419 nValueRet += coin.first;
1422 else if (n < nTargetValue + CENT)
1424 vValue.push_back(coin);
1427 else if (n < coinLowestLarger.first)
1429 coinLowestLarger = coin;
1433 if (nTotalLower == nTargetValue)
1435 for (unsigned int i = 0; i < vValue.size(); ++i)
1437 setCoinsRet.insert(vValue[i].second);
1438 nValueRet += vValue[i].first;
1443 if (nTotalLower < nTargetValue)
1445 if (coinLowestLarger.second.first == NULL)
1447 setCoinsRet.insert(coinLowestLarger.second);
1448 nValueRet += coinLowestLarger.first;
1452 // Solve subset sum by stochastic approximation
1453 sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
1454 vector<char> vfBest;
1457 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);
1458 if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT)
1459 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000);
1461 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
1462 // or the next bigger coin is closer), return the bigger coin
1463 if (coinLowestLarger.second.first &&
1464 ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest))
1466 setCoinsRet.insert(coinLowestLarger.second);
1467 nValueRet += coinLowestLarger.first;
1470 for (unsigned int i = 0; i < vValue.size(); i++)
1473 setCoinsRet.insert(vValue[i].second);
1474 nValueRet += vValue[i].first;
1477 if (fDebug && GetBoolArg("-printpriority"))
1480 printf("SelectCoins() best subset: ");
1481 for (unsigned int i = 0; i < vValue.size(); i++)
1483 printf("%s ", FormatMoney(vValue[i].first).c_str());
1484 printf("total %s\n", FormatMoney(nBest).c_str());
1491 bool CWallet::SelectCoins(int64_t nTargetValue, unsigned int nSpendTime, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64_t& nValueRet, const CCoinControl* coinControl) const
1493 vector<COutput> vCoins;
1494 AvailableCoins(vCoins, true, coinControl);
1496 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
1497 if (coinControl && coinControl->HasSelected())
1499 BOOST_FOREACH(const COutput& out, vCoins)
1503 nValueRet += out.tx->vout[out.i].nValue;
1504 setCoinsRet.insert(make_pair(out.tx, out.i));
1506 return (nValueRet >= nTargetValue);
1509 return (SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 6, vCoins, setCoinsRet, nValueRet) ||
1510 SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 1, vCoins, setCoinsRet, nValueRet) ||
1511 SelectCoinsMinConf(nTargetValue, nSpendTime, 0, 1, vCoins, setCoinsRet, nValueRet));
1514 // Select some coins without random shuffle or best subset approximation
1515 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
1517 vector<COutput> vCoins;
1518 AvailableCoinsMinConf(vCoins, nMinConf, nMinValue, nMaxValue);
1520 setCoinsRet.clear();
1523 BOOST_FOREACH(COutput output, vCoins)
1525 if(!output.fSpendable)
1527 const CWalletTx *pcoin = output.tx;
1530 // Ignore immature coins
1531 if (pcoin->GetBlocksToMaturity() > 0)
1534 // Stop if we've chosen enough inputs
1535 if (nValueRet >= nTargetValue)
1538 // Follow the timestamp rules
1539 if (pcoin->nTime > nSpendTime)
1542 int64_t n = pcoin->vout[i].nValue;
1544 pair<int64_t,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1546 if (n >= nTargetValue)
1548 // If input value is greater or equal to target then simply insert
1549 // it into the current subset and exit
1550 setCoinsRet.insert(coin.second);
1551 nValueRet += coin.first;
1554 else if (n < nTargetValue + CENT)
1556 setCoinsRet.insert(coin.second);
1557 nValueRet += coin.first;
1564 bool CWallet::CreateTransaction(const vector<pair<CScript, int64_t> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl* coinControl)
1567 BOOST_FOREACH (const PAIRTYPE(CScript, int64_t)& s, vecSend)
1573 if (vecSend.empty() || nValue < 0)
1576 wtxNew.BindWallet(this);
1579 LOCK2(cs_main, cs_wallet);
1580 // txdb must be opened before the mapWallet lock
1583 nFeeRet = nTransactionFee;
1587 wtxNew.vout.clear();
1588 wtxNew.fFromMe = true;
1590 int64_t nTotalValue = nValue + nFeeRet;
1591 double dPriority = 0;
1592 // vouts to the payees
1593 BOOST_FOREACH (const PAIRTYPE(CScript, int64_t)& s, vecSend)
1594 wtxNew.vout.push_back(CTxOut(s.second, s.first));
1596 // Choose coins to use
1597 set<pair<const CWalletTx*,unsigned int> > setCoins;
1598 int64_t nValueIn = 0;
1599 if (!SelectCoins(nTotalValue, wtxNew.nTime, setCoins, nValueIn, coinControl))
1601 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1603 int64_t nCredit = pcoin.first->vout[pcoin.second].nValue;
1604 dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
1607 int64_t nChange = nValueIn - nValue - nFeeRet;
1610 // Fill a vout to ourself
1611 // TODO: pass in scriptChange instead of reservekey so
1612 // change transaction isn't always pay-to-bitcoin-address
1613 CScript scriptChange;
1615 // coin control: send change to custom address
1616 if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange))
1617 scriptChange.SetDestination(coinControl->destChange);
1619 // no coin control: send change to newly generated address
1622 // Note: We use a new key here to keep it from being obvious which side is the change.
1623 // The drawback is that by not reusing a previous key, the change may be lost if a
1624 // backup is restored, if the backup doesn't have the new private key for the change.
1625 // If we reused the old key, it would be possible to add code to look for and
1626 // rediscover unknown transactions that were written with keys of ours to recover
1627 // post-backup change.
1629 // Reserve a new key pair from key pool
1630 CPubKey vchPubKey = reservekey.GetReservedKey();
1632 scriptChange.SetDestination(vchPubKey.GetID());
1635 // Insert change txn at random position:
1636 vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
1637 wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
1640 reservekey.ReturnKey();
1643 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1644 wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
1648 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1649 if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
1653 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
1654 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1656 dPriority /= nBytes;
1658 // Check that enough fee is included
1659 bool fAllowFree = CTransaction::AllowFree(dPriority);
1660 int64_t nPayFee = nTransactionFee * (1 + (int64_t)nBytes / 1000);
1661 int64_t nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
1663 if (nFeeRet < max(nPayFee, nMinFee))
1665 nFeeRet = max(nPayFee, nMinFee);
1669 // Fill vtxPrev by copying from previous transactions vtxPrev
1670 wtxNew.AddSupportingTransactions(txdb);
1671 wtxNew.fTimeReceivedIsTxTime = true;
1680 bool CWallet::CreateTransaction(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl* coinControl)
1682 vector< pair<CScript, int64_t> > vecSend;
1683 vecSend.push_back(make_pair(scriptPubKey, nValue));
1684 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, coinControl);
1687 void CWallet::GetStakeWeightFromValue(const int64_t& nTime, const int64_t& nValue, uint64_t& nWeight)
1689 int64_t nTimeWeight = GetWeight(nTime, (int64_t)GetTime());
1691 // If time weight is lower or equal to zero then weight is zero.
1692 if (nTimeWeight <= 0)
1698 CBigNum bnCoinDayWeight = CBigNum(nValue) * nTimeWeight / COIN / (24 * 60 * 60);
1699 nWeight = bnCoinDayWeight.getuint64();
1703 // NovaCoin: get current stake miner statistics
1704 void CWallet::GetStakeStats(float &nKernelsRate, float &nCoinDaysRate)
1706 static uint64_t nLastKernels = 0, nLastCoinDays = 0;
1707 static float nLastKernelsRate = 0, nLastCoinDaysRate = 0;
1708 static int64_t nLastTime = GetTime();
1710 if (nKernelsTried < nLastKernels)
1715 nLastTime = GetTime();
1718 int64_t nInterval = GetTime() - nLastTime;
1719 //if (nKernelsTried > 1000 && nInterval > 5)
1722 nKernelsRate = nLastKernelsRate = ( nKernelsTried - nLastKernels ) / (float) nInterval;
1723 nCoinDaysRate = nLastCoinDaysRate = ( nCoinDaysTried - nLastCoinDays ) / (float) nInterval;
1725 nLastKernels = nKernelsTried;
1726 nLastCoinDays = nCoinDaysTried;
1727 nLastTime = GetTime();
1731 nKernelsRate = nLastKernelsRate;
1732 nCoinDaysRate = nLastCoinDaysRate;
1736 bool CWallet::MergeCoins(const int64_t& nAmount, const int64_t& nMinValue, const int64_t& nOutputValue, list<uint256>& listMerged)
1738 int64_t nBalance = GetBalance();
1740 if (nAmount > nBalance)
1744 int64_t nValueIn = 0;
1745 set<pair<const CWalletTx*,unsigned int> > setCoins;
1747 // Simple coins selection - no randomization
1748 if (!SelectCoinsSimple(nAmount, nMinValue, nOutputValue, GetTime(), 1, setCoins, nValueIn))
1751 if (setCoins.empty())
1755 vector<const CWalletTx*> vwtxPrev;
1757 // Reserve a new key pair from key pool
1758 CReserveKey reservekey(this);
1759 CPubKey vchPubKey = reservekey.GetReservedKey();
1762 CScript scriptOutput;
1763 scriptOutput.SetDestination(vchPubKey.GetID());
1766 wtxNew.vout.push_back(CTxOut(0, scriptOutput));
1769 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1771 int64_t nCredit = pcoin.first->vout[pcoin.second].nValue;
1773 // Add current coin to inputs list and add its credit to transaction output
1774 wtxNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1775 wtxNew.vout[0].nValue += nCredit;
1776 vwtxPrev.push_back(pcoin.first);
1779 // Replaced with estimation for performance purposes
1781 for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
1782 const CWalletTx *txin = vwtxPrev[i];
1784 // Sign scripts to get actual transaction size for fee calculation
1785 if (!SignSignature(*this, *txin, wtxNew, i))
1790 // Assuming that average scriptsig size is 110 bytes
1791 int64_t nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION) + wtxNew.vin.size() * 110;
1792 dWeight += (double)nCredit * pcoin.first->GetDepthInMainChain();
1794 double dFinalPriority = dWeight /= nBytes;
1795 bool fAllowFree = CTransaction::AllowFree(dFinalPriority);
1797 // Get actual transaction fee according to its estimated size and priority
1798 int64_t nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
1800 // Prepare transaction for commit if sum is enough ot its size is too big
1801 if (nBytes >= MAX_BLOCK_SIZE_GEN/6 || wtxNew.vout[0].nValue >= nOutputValue)
1803 wtxNew.vout[0].nValue -= nMinFee; // Set actual fee
1805 for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
1806 const CWalletTx *txin = vwtxPrev[i];
1809 if (!SignSignature(*this, *txin, wtxNew, i))
1813 // Try to commit, return false on failure
1814 if (!CommitTransaction(wtxNew, reservekey))
1817 listMerged.push_back(wtxNew.GetHash()); // Add to hashes list
1819 dWeight = 0; // Reset all temporary values
1822 wtxNew.vout.push_back(CTxOut(0, scriptOutput));
1826 // Create transactions if there are some unhandled coins left
1827 if (wtxNew.vout[0].nValue > 0) {
1828 int64_t nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION) + wtxNew.vin.size() * 110;
1830 double dFinalPriority = dWeight /= nBytes;
1831 bool fAllowFree = CTransaction::AllowFree(dFinalPriority);
1833 // Get actual transaction fee according to its size and priority
1834 int64_t nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
1836 wtxNew.vout[0].nValue -= nMinFee; // Set actual fee
1838 if (wtxNew.vout[0].nValue <= 0)
1841 for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
1842 const CWalletTx *txin = vwtxPrev[i];
1844 // Sign all scripts again
1845 if (!SignSignature(*this, *txin, wtxNew, i))
1849 // Try to commit, return false on failure
1850 if (!CommitTransaction(wtxNew, reservekey))
1853 listMerged.push_back(wtxNew.GetHash()); // Add to hashes list
1860 bool CWallet::CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, uint32_t nSearchInterval, CTransaction& txNew, CKey& key)
1862 // The following combine threshold is important to security
1863 // Should not be adjusted if you don't understand the consequences
1864 int64_t nCombineThreshold = GetProofOfWorkReward(GetLastBlockIndex(pindexBest, false)->nBits) / 3;
1866 CBigNum bnTargetPerCoinDay;
1867 bnTargetPerCoinDay.SetCompact(nBits);
1872 // Mark coin stake transaction
1873 CScript scriptEmpty;
1874 scriptEmpty.clear();
1875 txNew.vout.push_back(CTxOut(0, scriptEmpty));
1877 // Choose coins to use
1878 int64_t nBalance = GetBalance();
1879 int64_t nReserveBalance = 0;
1881 if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
1882 return error("CreateCoinStake : invalid reserve balance amount");
1884 if (nBalance <= nReserveBalance)
1887 vector<const CWalletTx*> vwtxPrev;
1891 LOCK2(cs_main, cs_wallet);
1892 // Cache outputs unless best block or wallet transaction set changed
1893 if (!fCoinsDataActual)
1896 int64_t nValueIn = 0;
1898 if (!SelectCoinsSimple(nBalance - nReserveBalance, MIN_TX_FEE, MAX_MONEY, txNew.nTime, nCoinbaseMaturity * 10, setCoins, nValueIn))
1901 if (setCoins.empty())
1907 for(CoinsSet::iterator pcoin = setCoins.begin(); pcoin != setCoins.end(); pcoin++)
1909 // Load transaction index item
1910 if (!txdb.ReadTxIndex(pcoin->first->GetHash(), txindex))
1913 // Read block header
1914 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
1917 uint64_t nStakeModifier = 0;
1918 if (!GetKernelStakeModifier(block.GetHash(), nStakeModifier))
1922 // (txid, vout.n) => ((txindex, (tx, vout.n)), (block, modifier))
1923 mapMeta[make_pair(pcoin->first->GetHash(), pcoin->second)] = make_pair(make_pair(txindex, *pcoin), make_pair(block, nStakeModifier));
1926 printf("Load coin: %s\n", pcoin->first->GetHash().GetHex().c_str());
1931 printf("Stake miner: %" PRIszu " meta items loaded for %" PRIszu " coins\n", mapMeta.size(), setCoins.size());
1933 fCoinsDataActual = true;
1939 int64_t nCredit = 0;
1940 CScript scriptPubKeyKernel;
1942 unsigned int nTimeTx, nBlockTime;
1943 COutPoint prevoutStake;
1944 CoinsSet::value_type kernelcoin;
1946 if (ScanForStakeKernelHash(mapMeta, nBits, txNew.nTime, nSearchInterval, kernelcoin, nTimeTx, nBlockTime, nKernelsTried, nCoinDaysTried))
1949 if (fDebug && GetBoolArg("-printcoinstake"))
1950 printf("CreateCoinStake : kernel found\n");
1951 vector<valtype> vSolutions;
1952 txnouttype whichType;
1953 CScript scriptPubKeyOut;
1954 scriptPubKeyKernel = kernelcoin.first->vout[kernelcoin.second].scriptPubKey;
1955 if (!Solver(scriptPubKeyKernel, whichType, vSolutions))
1957 if (fDebug && GetBoolArg("-printcoinstake"))
1958 printf("CreateCoinStake : failed to parse kernel\n");
1961 if (fDebug && GetBoolArg("-printcoinstake"))
1962 printf("CreateCoinStake : parsed kernel type=%d\n", whichType);
1963 if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH)
1965 if (fDebug && GetBoolArg("-printcoinstake"))
1966 printf("CreateCoinStake : no support for kernel type=%d\n", whichType);
1967 return false; // only support pay to public key and pay to address
1969 if (whichType == TX_PUBKEYHASH) // pay to address type
1971 // convert to pay to public key type
1972 if (!keystore.GetKey(uint160(vSolutions[0]), key))
1974 if (fDebug && GetBoolArg("-printcoinstake"))
1975 printf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1976 return false; // unable to find corresponding public key
1978 scriptPubKeyOut << key.GetPubKey() << OP_CHECKSIG;
1980 if (whichType == TX_PUBKEY)
1982 valtype& vchPubKey = vSolutions[0];
1983 if (!keystore.GetKey(Hash160(vchPubKey), key))
1985 if (fDebug && GetBoolArg("-printcoinstake"))
1986 printf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1987 return false; // unable to find corresponding public key
1989 if (key.GetPubKey() != vchPubKey)
1991 if (fDebug && GetBoolArg("-printcoinstake"))
1992 printf("CreateCoinStake : invalid key for kernel type=%d\n", whichType);
1993 return false; // keys mismatch
1996 scriptPubKeyOut = scriptPubKeyKernel;
1999 txNew.nTime = nTimeTx;
2000 txNew.vin.push_back(CTxIn(kernelcoin.first->GetHash(), kernelcoin.second));
2001 nCredit += kernelcoin.first->vout[kernelcoin.second].nValue;
2002 vwtxPrev.push_back(kernelcoin.first);
2003 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
2005 if (GetWeight((int64_t)nBlockTime, (int64_t)txNew.nTime) < nStakeMaxAge)
2006 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut)); //split stake
2007 if (fDebug && GetBoolArg("-printcoinstake"))
2008 printf("CreateCoinStake : added kernel type=%d\n", whichType);
2011 if (nCredit == 0 || nCredit > nBalance - nReserveBalance)
2014 // (txid, vout.n) => ((txindex, (tx, vout.n)), (block, modifier))
2015 for(MetaMap::const_iterator meta_item = mapMeta.begin(); meta_item != mapMeta.end(); meta_item++)
2018 CoinsSet::value_type pcoin = meta_item->second.first.second;
2020 // Attempt to add more inputs
2021 // Only add coins of the same key/address as kernel
2022 if (txNew.vout.size() == 2 && ((pcoin.first->vout[pcoin.second].scriptPubKey == scriptPubKeyKernel || pcoin.first->vout[pcoin.second].scriptPubKey == txNew.vout[1].scriptPubKey))
2023 && pcoin.first->GetHash() != txNew.vin[0].prevout.hash)
2025 int64_t nTimeWeight = GetWeight((int64_t)pcoin.first->nTime, (int64_t)txNew.nTime);
2027 // Stop adding more inputs if already too many inputs
2028 if (txNew.vin.size() >= 100)
2030 // Stop adding more inputs if value is already pretty significant
2031 if (nCredit > nCombineThreshold)
2033 // Stop adding inputs if reached reserve limit
2034 if (nCredit + pcoin.first->vout[pcoin.second].nValue > nBalance - nReserveBalance)
2036 // Do not add additional significant input
2037 if (pcoin.first->vout[pcoin.second].nValue > nCombineThreshold)
2039 // Do not add input that is still too young
2040 if (nTimeWeight < nStakeMaxAge)
2043 txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
2044 nCredit += pcoin.first->vout[pcoin.second].nValue;
2045 vwtxPrev.push_back(pcoin.first);
2049 // Calculate coin age reward
2053 if (!txNew.GetCoinAge(txdb, nCoinAge))
2054 return error("CreateCoinStake : failed to calculate coin age");
2056 int64_t nReward = GetProofOfStakeReward(nCoinAge, nBits, txNew.nTime);
2057 // Refuse to create mint that has zero or negative reward
2064 int64_t nMinFee = 0;
2067 // Set output amount
2068 if (txNew.vout.size() == 3)
2070 txNew.vout[1].nValue = ((nCredit - nMinFee) / 2 / CENT) * CENT;
2071 txNew.vout[2].nValue = nCredit - nMinFee - txNew.vout[1].nValue;
2074 txNew.vout[1].nValue = nCredit - nMinFee;
2078 BOOST_FOREACH(const CWalletTx* pcoin, vwtxPrev)
2080 if (!SignSignature(*this, *pcoin, txNew, nIn++))
2081 return error("CreateCoinStake : failed to sign coinstake");
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");
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 generated coinstake
2108 // Call after CreateTransaction unless you want to abort
2109 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
2112 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
2114 // Track how many getdata requests our transaction gets
2115 mapRequestCount[wtxNew.GetHash()] = 0;
2117 // Try to broadcast before saving
2118 if (!wtxNew.AcceptToMemoryPool())
2120 // This must not fail. The transaction has already been signed.
2121 printf("CommitTransaction() : Error: Transaction not valid");
2125 wtxNew.RelayWalletTransaction();
2128 LOCK2(cs_main, cs_wallet);
2130 // This is only to keep the database open to defeat the auto-flush for the
2131 // duration of this scope. This is the only place where this optimization
2132 // maybe makes sense; please don't do it anywhere else.
2133 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
2135 // Take key pair from key pool so it won't be used again
2136 reservekey.KeepKey();
2138 // Add tx to wallet, because if it has change it's also ours,
2139 // otherwise just for transaction history.
2140 AddToWallet(wtxNew);
2142 // Mark old coins as spent
2143 set<CWalletTx*> setCoins;
2144 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
2146 CWalletTx &coin = mapWallet[txin.prevout.hash];
2147 coin.BindWallet(this);
2148 coin.MarkSpent(txin.prevout.n);
2150 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
2151 vMintingWalletUpdated.push_back(coin.GetHash());
2164 string CWallet::SendMoney(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, bool fAskFee)
2166 CReserveKey reservekey(this);
2167 int64_t nFeeRequired;
2171 string strError = _("Error: Wallet locked, unable to create transaction ");
2172 printf("SendMoney() : %s", strError.c_str());
2175 if (fWalletUnlockMintOnly)
2177 string strError = _("Error: Wallet unlocked for block minting only, unable to create transaction.");
2178 printf("SendMoney() : %s", strError.c_str());
2181 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
2184 if (nValue + nFeeRequired > GetBalance())
2185 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());
2187 strError = _("Error: Transaction creation failed ");
2188 printf("SendMoney() : %s", strError.c_str());
2192 if (fAskFee && !uiInterface.ThreadSafeAskFee(nFeeRequired, _("Sending...")))
2195 if (!CommitTransaction(wtxNew, reservekey))
2196 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.");
2203 string CWallet::SendMoneyToDestination(const CTxDestination& address, int64_t nValue, CWalletTx& wtxNew, bool fAskFee)
2207 return _("Invalid amount");
2208 if (nValue + nTransactionFee > GetBalance())
2209 return _("Insufficient funds");
2211 // Parse Bitcoin address
2212 CScript scriptPubKey;
2213 scriptPubKey.SetDestination(address);
2215 return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
2221 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
2225 fFirstRunRet = false;
2226 DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
2227 if (nLoadWalletRet == DB_NEED_REWRITE)
2229 if (CDB::Rewrite(strWalletFile, "\x04pool"))
2232 // Note: can't top-up keypool here, because wallet is locked.
2233 // User will be prompted to unlock wallet the next operation
2234 // the requires a new key.
2238 if (nLoadWalletRet != DB_LOAD_OK)
2239 return nLoadWalletRet;
2240 fFirstRunRet = !vchDefaultKey.IsValid();
2242 NewThread(ThreadFlushWalletDB, &strWalletFile);
2247 bool CWallet::SetAddressBookName(const CTxDestination& address, const string& strName)
2249 std::map<CTxDestination, std::string>::iterator mi = mapAddressBook.find(address);
2250 mapAddressBook[address] = strName;
2251 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address), (mi == mapAddressBook.end()) ? CT_NEW : CT_UPDATED);
2254 return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName);
2257 bool CWallet::DelAddressBookName(const CTxDestination& address)
2259 mapAddressBook.erase(address);
2260 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address), CT_DELETED);
2263 return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString());
2267 void CWallet::PrintWallet(const CBlock& block)
2271 if (block.IsProofOfStake() && mapWallet.count(block.vtx[1].GetHash()))
2273 CWalletTx& wtx = mapWallet[block.vtx[1].GetHash()];
2274 printf(" PoS: %d %d %" PRId64 "", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit(MINE_ALL));
2276 else if (mapWallet.count(block.vtx[0].GetHash()))
2278 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
2279 printf(" PoW: %d %d %" PRId64 "", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit(MINE_ALL));
2285 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
2289 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
2290 if (mi != mapWallet.end())
2299 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
2303 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
2306 vchDefaultKey = vchPubKey;
2310 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
2312 if (!pwallet->fFileBacked)
2314 strWalletFileOut = pwallet->strWalletFile;
2319 // Mark old keypool keys as used,
2320 // and generate all new keys
2322 bool CWallet::NewKeyPool(unsigned int nSize)
2326 CWalletDB walletdb(strWalletFile);
2327 BOOST_FOREACH(int64_t nIndex, setKeyPool)
2328 walletdb.ErasePool(nIndex);
2338 nKeys = max<uint64_t>(GetArg("-keypool", 100), 0);
2340 for (uint64_t i = 0; i < nKeys; i++)
2342 uint64_t nIndex = i+1;
2343 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
2344 setKeyPool.insert(nIndex);
2346 printf("CWallet::NewKeyPool wrote %" PRIu64 " new keys\n", nKeys);
2351 bool CWallet::TopUpKeyPool(unsigned int nSize)
2359 CWalletDB walletdb(strWalletFile);
2362 uint64_t nTargetSize;
2364 nTargetSize = nSize;
2366 nTargetSize = max<uint64_t>(GetArg("-keypool", 100), 0);
2368 while (setKeyPool.size() < (nTargetSize + 1))
2371 if (!setKeyPool.empty())
2372 nEnd = *(--setKeyPool.end()) + 1;
2373 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
2374 throw runtime_error("TopUpKeyPool() : writing generated key failed");
2375 setKeyPool.insert(nEnd);
2376 printf("keypool added key %" PRIu64 ", size=%" PRIszu "\n", nEnd, setKeyPool.size());
2382 void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool)
2385 keypool.vchPubKey = CPubKey();
2392 // Get the oldest key
2393 if(setKeyPool.empty())
2396 CWalletDB walletdb(strWalletFile);
2398 nIndex = *(setKeyPool.begin());
2399 setKeyPool.erase(setKeyPool.begin());
2400 if (!walletdb.ReadPool(nIndex, keypool))
2401 throw runtime_error("ReserveKeyFromKeyPool() : read failed");
2402 if (!HaveKey(keypool.vchPubKey.GetID()))
2403 throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
2404 assert(keypool.vchPubKey.IsValid());
2405 if (fDebug && GetBoolArg("-printkeypool"))
2406 printf("keypool reserve %" PRId64 "\n", nIndex);
2410 int64_t CWallet::AddReserveKey(const CKeyPool& keypool)
2413 LOCK2(cs_main, cs_wallet);
2414 CWalletDB walletdb(strWalletFile);
2416 int64_t nIndex = 1 + *(--setKeyPool.end());
2417 if (!walletdb.WritePool(nIndex, keypool))
2418 throw runtime_error("AddReserveKey() : writing added key failed");
2419 setKeyPool.insert(nIndex);
2425 void CWallet::KeepKey(int64_t nIndex)
2427 // Remove from key pool
2430 CWalletDB walletdb(strWalletFile);
2431 walletdb.ErasePool(nIndex);
2434 printf("keypool keep %" PRId64 "\n", nIndex);
2437 void CWallet::ReturnKey(int64_t nIndex)
2439 // Return to key pool
2442 setKeyPool.insert(nIndex);
2445 printf("keypool return %" PRId64 "\n", nIndex);
2448 bool CWallet::GetKeyFromPool(CPubKey& result, bool fAllowReuse)
2454 ReserveKeyFromKeyPool(nIndex, keypool);
2457 if (fAllowReuse && vchDefaultKey.IsValid())
2459 result = vchDefaultKey;
2462 if (IsLocked()) return false;
2463 result = GenerateNewKey();
2467 result = keypool.vchPubKey;
2472 int64_t CWallet::GetOldestKeyPoolTime()
2476 ReserveKeyFromKeyPool(nIndex, keypool);
2480 return keypool.nTime;
2483 std::map<CTxDestination, int64_t> CWallet::GetAddressBalances()
2485 map<CTxDestination, int64_t> balances;
2489 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2491 CWalletTx *pcoin = &walletEntry.second;
2493 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
2496 if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0)
2499 int nDepth = pcoin->GetDepthInMainChain();
2500 if (nDepth < (pcoin->IsFromMe(MINE_ALL) ? 0 : 1))
2503 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2505 CTxDestination addr;
2506 if (!IsMine(pcoin->vout[i]))
2508 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr))
2511 int64_t n = pcoin->IsSpent(i) ? 0 : pcoin->vout[i].nValue;
2513 if (!balances.count(addr))
2515 balances[addr] += n;
2523 set< set<CTxDestination> > CWallet::GetAddressGroupings()
2525 set< set<CTxDestination> > groupings;
2526 set<CTxDestination> grouping;
2528 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2530 CWalletTx *pcoin = &walletEntry.second;
2532 if (pcoin->vin.size() > 0 && IsMine(pcoin->vin[0]))
2534 // group all input addresses with each other
2535 BOOST_FOREACH(CTxIn txin, pcoin->vin)
2537 CTxDestination address;
2538 if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
2540 grouping.insert(address);
2543 // group change with input addresses
2544 BOOST_FOREACH(CTxOut txout, pcoin->vout)
2545 if (IsChange(txout))
2547 CWalletTx tx = mapWallet[pcoin->vin[0].prevout.hash];
2548 CTxDestination txoutAddr;
2549 if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
2551 grouping.insert(txoutAddr);
2553 groupings.insert(grouping);
2557 // group lone addrs by themselves
2558 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2559 if (IsMine(pcoin->vout[i]))
2561 CTxDestination address;
2562 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address))
2564 grouping.insert(address);
2565 groupings.insert(grouping);
2570 set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
2571 map< CTxDestination, set<CTxDestination>* > setmap; // map addresses to the unique group containing it
2572 BOOST_FOREACH(set<CTxDestination> grouping, groupings)
2574 // make a set of all the groups hit by this new group
2575 set< set<CTxDestination>* > hits;
2576 map< CTxDestination, set<CTxDestination>* >::iterator it;
2577 BOOST_FOREACH(CTxDestination address, grouping)
2578 if ((it = setmap.find(address)) != setmap.end())
2579 hits.insert((*it).second);
2581 // merge all hit groups into a new single group and delete old groups
2582 set<CTxDestination>* merged = new set<CTxDestination>(grouping);
2583 BOOST_FOREACH(set<CTxDestination>* hit, hits)
2585 merged->insert(hit->begin(), hit->end());
2586 uniqueGroupings.erase(hit);
2589 uniqueGroupings.insert(merged);
2592 BOOST_FOREACH(CTxDestination element, *merged)
2593 setmap[element] = merged;
2596 set< set<CTxDestination> > ret;
2597 BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings)
2599 ret.insert(*uniqueGrouping);
2600 delete uniqueGrouping;
2606 // ppcoin: check 'spent' consistency between wallet and txindex
2607 // ppcoin: fix wallet spent state according to txindex
2608 void CWallet::FixSpentCoins(int& nMismatchFound, int64_t& nBalanceInQuestion, bool fCheckOnly)
2611 nBalanceInQuestion = 0;
2614 vector<CWalletTx*> vCoins;
2615 vCoins.reserve(mapWallet.size());
2616 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2617 vCoins.push_back(&(*it).second);
2620 BOOST_FOREACH(CWalletTx* pcoin, vCoins)
2622 // Find the corresponding transaction index
2624 if (!txdb.ReadTxIndex(pcoin->GetHash(), txindex))
2626 for (unsigned int n=0; n < pcoin->vout.size(); n++)
2628 if (IsMine(pcoin->vout[n]) && pcoin->IsSpent(n) && (txindex.vSpent.size() <= n || txindex.vSpent[n].IsNull()))
2630 printf("FixSpentCoins found lost coin %sppc %s[%d], %s\n",
2631 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2633 nBalanceInQuestion += pcoin->vout[n].nValue;
2636 pcoin->MarkUnspent(n);
2637 pcoin->WriteToDisk();
2640 else if (IsMine(pcoin->vout[n]) && !pcoin->IsSpent(n) && (txindex.vSpent.size() > n && !txindex.vSpent[n].IsNull()))
2642 printf("FixSpentCoins found spent coin %sppc %s[%d], %s\n",
2643 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2645 nBalanceInQuestion += pcoin->vout[n].nValue;
2648 pcoin->MarkSpent(n);
2649 pcoin->WriteToDisk();
2655 if(IsMine((CTransaction)*pcoin) && (pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetDepthInMainChain() == 0)
2657 printf("FixSpentCoins %s tx %s\n", fCheckOnly ? "found" : "removed", pcoin->GetHash().ToString().c_str());
2660 EraseFromWallet(pcoin->GetHash());
2666 // ppcoin: disable transaction (only for coinstake)
2667 void CWallet::DisableTransaction(const CTransaction &tx)
2669 if (!tx.IsCoinStake() || !IsFromMe(tx))
2670 return; // only disconnecting coinstake requires marking input unspent
2673 BOOST_FOREACH(const CTxIn& txin, tx.vin)
2675 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
2676 if (mi != mapWallet.end())
2678 CWalletTx& prev = (*mi).second;
2679 if (txin.prevout.n < prev.vout.size() && IsMine(prev.vout[txin.prevout.n]))
2681 prev.MarkUnspent(txin.prevout.n);
2688 CPubKey CReserveKey::GetReservedKey()
2693 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
2695 vchPubKey = keypool.vchPubKey;
2698 printf("CReserveKey::GetReservedKey(): Warning: Using default key instead of a new key, top up your keypool!");
2699 vchPubKey = pwallet->vchDefaultKey;
2702 assert(vchPubKey.IsValid());
2706 void CReserveKey::KeepKey()
2709 pwallet->KeepKey(nIndex);
2711 vchPubKey = CPubKey();
2714 void CReserveKey::ReturnKey()
2717 pwallet->ReturnKey(nIndex);
2719 vchPubKey = CPubKey();
2722 void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
2726 CWalletDB walletdb(strWalletFile);
2728 LOCK2(cs_main, cs_wallet);
2729 BOOST_FOREACH(const int64_t& id, setKeyPool)
2732 if (!walletdb.ReadPool(id, keypool))
2733 throw runtime_error("GetAllReserveKeyHashes() : read failed");
2734 assert(keypool.vchPubKey.IsValid());
2735 CKeyID keyID = keypool.vchPubKey.GetID();
2736 if (!HaveKey(keyID))
2737 throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
2738 setAddress.insert(keyID);
2742 void CWallet::UpdatedTransaction(const uint256 &hashTx)
2746 // Only notify UI if this transaction is in this wallet
2747 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
2748 if (mi != mapWallet.end())
2750 NotifyTransactionChanged(this, hashTx, CT_UPDATED);
2751 vMintingWalletUpdated.push_back(hashTx);
2756 void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const {
2757 mapKeyBirth.clear();
2759 // get birth times for keys with metadata
2760 for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++)
2761 if (it->second.nCreateTime)
2762 mapKeyBirth[it->first] = it->second.nCreateTime;
2764 // map in which we'll infer heights of other keys
2765 CBlockIndex *pindexMax = FindBlockByHeight(std::max(0, nBestHeight - 144)); // the tip can be reorganised; use a 144-block safety margin
2766 std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
2767 std::set<CKeyID> setKeys;
2769 BOOST_FOREACH(const CKeyID &keyid, setKeys) {
2770 if (mapKeyBirth.count(keyid) == 0)
2771 mapKeyFirstBlock[keyid] = pindexMax;
2775 // if there are no such keys, we're done
2776 if (mapKeyFirstBlock.empty())
2779 // find first block that affects those keys, if there are any left
2780 std::vector<CKeyID> vAffected;
2781 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
2782 // iterate over all wallet transactions...
2783 const CWalletTx &wtx = (*it).second;
2784 std::map<uint256, CBlockIndex*>::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
2785 if (blit != mapBlockIndex.end() && blit->second->IsInMainChain()) {
2786 // ... which are already in a block
2787 int nHeight = blit->second->nHeight;
2788 BOOST_FOREACH(const CTxOut &txout, wtx.vout) {
2789 // iterate over all their outputs
2790 ::ExtractAffectedKeys(*this, txout.scriptPubKey, vAffected);
2791 BOOST_FOREACH(const CKeyID &keyid, vAffected) {
2792 // ... and all their affected keys
2793 std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
2794 if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
2795 rit->second = blit->second;
2802 // Extract block timestamps for those keys
2803 for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
2804 mapKeyBirth[it->first] = it->second->nTime - 7200; // block times can be 2h off
2807 void CWallet::ClearOrphans()
2809 list<uint256> orphans;
2812 for(map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2814 const CWalletTx *wtx = &(*it).second;
2815 if((wtx->IsCoinBase() || wtx->IsCoinStake()) && !wtx->IsInMainChain())
2817 orphans.push_back(wtx->GetHash());
2821 for(list<uint256>::const_iterator it = orphans.begin(); it != orphans.end(); ++it)
2822 EraseFromWallet(*it);