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[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 mapMalleableKeyMetadata[keyView] = CKeyMetadata(nCreationTime);
74 if (!nTimeFirstKey || nCreationTime < nTimeFirstKey)
75 nTimeFirstKey = nCreationTime;
77 if (!AddMalleableKey(mKey))
78 throw std::runtime_error("CWallet::GenerateNewMalleableKey() : AddMalleableKey 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[pubkey.GetID()]);
94 bool CWallet::AddMalleableKey(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, mapMalleableKeyMetadata[keyView]);
107 bool CWallet::AddCryptedMalleableKey(const CMalleableKeyView& keyView, const std::vector<unsigned char> &vchCryptedSecretH)
109 if (!CCryptoKeyStore::AddCryptedMalleableKey(keyView, vchCryptedSecretH))
117 if (pwalletdbEncryption)
118 return pwalletdbEncryption->WriteCryptedMalleableKey(keyView, vchCryptedSecretH, mapMalleableKeyMetadata[keyView]);
120 return CWalletDB(strWalletFile).WriteCryptedMalleableKey(keyView, vchCryptedSecretH, mapMalleableKeyMetadata[keyView]);
126 bool CWallet::AddCryptedKey(const CPubKey &vchPubKey, const vector<unsigned char> &vchCryptedSecret)
128 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
131 // check if we need to remove from watch-only
133 script.SetDestination(vchPubKey.GetID());
134 if (HaveWatchOnly(script))
135 RemoveWatchOnly(script);
141 if (pwalletdbEncryption)
142 return pwalletdbEncryption->WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]);
144 return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]);
149 bool CWallet::LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &meta)
151 if (meta.nCreateTime && (!nTimeFirstKey || meta.nCreateTime < nTimeFirstKey))
152 nTimeFirstKey = meta.nCreateTime;
154 mapKeyMetadata[pubkey.GetID()] = meta;
158 bool CWallet::LoadMalleableKeyMetadata(const CMalleableKeyView &keyView, const CKeyMetadata &metadata)
160 if (metadata.nCreateTime && (!nTimeFirstKey || metadata.nCreateTime < nTimeFirstKey))
161 nTimeFirstKey = metadata.nCreateTime;
163 mapMalleableKeyMetadata[keyView] = metadata;
167 bool CWallet::AddCScript(const CScript& redeemScript)
169 if (!CCryptoKeyStore::AddCScript(redeemScript))
173 return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript);
176 bool CWallet::LoadCScript(const CScript& redeemScript)
178 /* A sanity check was added in commit 5ed0a2b to avoid adding redeemScripts
179 * that never can be redeemed. However, old wallets may still contain
180 * these. Do not add them to the wallet and warn. */
181 if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
183 std::string strAddr = CBitcoinAddress(redeemScript.GetID()).ToString();
184 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",
185 redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr.c_str());
189 return CCryptoKeyStore::AddCScript(redeemScript);
193 bool CWallet::AddWatchOnly(const CScript &dest)
195 if (!CCryptoKeyStore::AddWatchOnly(dest))
197 nTimeFirstKey = 1; // No birthday information for watch-only keys.
198 NotifyWatchonlyChanged(true);
201 return CWalletDB(strWalletFile).WriteWatchOnly(dest);
204 bool CWallet::RemoveWatchOnly(const CScript &dest)
207 if (!CCryptoKeyStore::RemoveWatchOnly(dest))
209 if (!HaveWatchOnly())
210 NotifyWatchonlyChanged(false);
212 if (!CWalletDB(strWalletFile).EraseWatchOnly(dest))
218 bool CWallet::LoadWatchOnly(const CScript &dest)
220 return CCryptoKeyStore::AddWatchOnly(dest);
223 // ppcoin: optional setting to unlock wallet for block minting only;
224 // serves to disable the trivial sendmoney when OS account compromised
225 bool fWalletUnlockMintOnly = false;
227 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
233 CKeyingMaterial vMasterKey;
237 BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
239 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
241 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
243 if (CCryptoKeyStore::Unlock(vMasterKey))
250 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
252 bool fWasLocked = IsLocked();
259 CKeyingMaterial vMasterKey;
260 BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
262 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
264 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
266 if (CCryptoKeyStore::Unlock(vMasterKey))
268 int64_t nStartTime = GetTimeMillis();
269 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
270 double nFirstMultiplier = 1e2 / (GetTimeMillis() - nStartTime);
271 pMasterKey.second.nDeriveIterations = (uint32_t)(pMasterKey.second.nDeriveIterations *nFirstMultiplier);
273 nStartTime = GetTimeMillis();
274 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
275 double nSecondMultiplier = 1e2 / (GetTimeMillis() - nStartTime);
276 pMasterKey.second.nDeriveIterations = (uint32_t)((pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * nSecondMultiplier) / 2);
278 if (pMasterKey.second.nDeriveIterations < 25000)
279 pMasterKey.second.nDeriveIterations = 25000;
281 printf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
283 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
285 if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
287 CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
298 void CWallet::SetBestChain(const CBlockLocator& loc)
300 CWalletDB walletdb(strWalletFile);
301 walletdb.WriteBestBlock(loc);
304 // This class implements an addrIncoming entry that causes pre-0.4
305 // clients to crash on startup if reading a private-key-encrypted wallet.
306 class CCorruptAddress
311 if (nType & SER_DISK)
316 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
318 if (nWalletVersion >= nVersion)
321 // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
322 if (fExplicit && nVersion > nWalletMaxVersion)
323 nVersion = FEATURE_LATEST;
325 nWalletVersion = nVersion;
327 if (nVersion > nWalletMaxVersion)
328 nWalletMaxVersion = nVersion;
332 CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile);
333 if (nWalletVersion > 40000)
334 pwalletdb->WriteMinVersion(nWalletVersion);
342 bool CWallet::SetMaxVersion(int nVersion)
344 // cannot downgrade below current version
345 if (nWalletVersion > nVersion)
348 nWalletMaxVersion = nVersion;
353 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
358 CKeyingMaterial vMasterKey;
359 RandAddSeedPerfmon();
361 vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
362 RAND_bytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
364 CMasterKey kMasterKey;
366 RandAddSeedPerfmon();
367 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
368 RAND_bytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
371 int64_t nStartTime = GetTimeMillis();
372 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
373 int64_t nDivider = GetTimeMillis() - nStartTime;
374 kMasterKey.nDeriveIterations = (uint32_t)(25e5 / (double)(nDivider));
376 nStartTime = GetTimeMillis();
377 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
378 double nMultiplier = 1e2 / (GetTimeMillis() - nStartTime);
379 kMasterKey.nDeriveIterations = (uint32_t)((kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * nMultiplier) / 2);
381 if (kMasterKey.nDeriveIterations < 25000)
382 kMasterKey.nDeriveIterations = 25000;
384 printf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
386 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
388 if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
393 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
396 pwalletdbEncryption = new CWalletDB(strWalletFile);
397 if (!pwalletdbEncryption->TxnBegin())
399 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
402 if (!EncryptKeys(vMasterKey))
405 pwalletdbEncryption->TxnAbort();
406 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.
409 // Encryption was introduced in version 0.4.0
410 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
414 if (!pwalletdbEncryption->TxnCommit())
415 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.
417 delete pwalletdbEncryption;
418 pwalletdbEncryption = NULL;
422 Unlock(strWalletPassphrase);
426 // Need to completely rewrite the wallet file; if we don't, bdb might keep
427 // bits of the unencrypted private key in slack space in the database file.
428 CDB::Rewrite(strWalletFile);
431 NotifyStatusChanged(this);
436 bool CWallet::DecryptWallet(const SecureString& strWalletPassphrase)
442 CKeyingMaterial vMasterKey;
446 BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
448 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
450 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
452 if (!CCryptoKeyStore::Unlock(vMasterKey))
458 pwalletdbDecryption = new CWalletDB(strWalletFile);
459 if (!pwalletdbDecryption->TxnBegin())
463 if (!DecryptKeys(vMasterKey))
466 pwalletdbDecryption->TxnAbort();
467 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.
472 // Overwrite crypted keys
473 KeyMap::const_iterator mi = mapKeys.begin();
474 while (mi != mapKeys.end())
477 key.SetSecret((*mi).second.first, (*mi).second.second);
478 pwalletdbDecryption->EraseCryptedKey(key.GetPubKey());
479 pwalletdbDecryption->WriteKey(key.GetPubKey(), key.GetPrivKey(), mapKeyMetadata[(*mi).first]);
483 MalleableKeyMap::const_iterator mi2 = mapMalleableKeys.begin();
484 while (mi2 != mapMalleableKeys.end())
486 const CSecret &vchSecretH = mi2->second;
487 const CMalleableKeyView &keyView = mi2->first;
488 pwalletdbDecryption->EraseCryptedMalleableKey(keyView);
489 pwalletdbDecryption->WriteMalleableKey(keyView, vchSecretH, mapMalleableKeyMetadata[keyView]);
494 MasterKeyMap::const_iterator mk = mapMasterKeys.begin();
495 while (mk != mapMasterKeys.end())
497 pwalletdbDecryption->EraseMasterKey((*mk).first);
501 if (!pwalletdbDecryption->TxnCommit())
502 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.
504 delete pwalletdbDecryption;
505 pwalletdbDecryption = NULL;
508 // Need to completely rewrite the wallet file; if we don't, bdb might keep
509 // encrypted private keys in the database file which can be a reason of consistency issues.
510 CDB::Rewrite(strWalletFile);
512 NotifyStatusChanged(this);
517 int64_t CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
519 int64_t nRet = nOrderPosNext++;
521 pwalletdb->WriteOrderPosNext(nOrderPosNext);
523 CWalletDB(strWalletFile).WriteOrderPosNext(nOrderPosNext);
528 CWallet::TxItems CWallet::OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount)
530 CWalletDB walletdb(strWalletFile);
532 // First: get all CWalletTx and CAccountingEntry into a sorted-by-order multimap.
535 // Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry
536 // would make this much faster for applications that do this a lot.
537 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
539 CWalletTx* wtx = &((*it).second);
540 txOrdered.insert(make_pair(wtx->nOrderPos, TxPair(wtx, (CAccountingEntry*)0)));
543 walletdb.ListAccountCreditDebit(strAccount, acentries);
544 BOOST_FOREACH(CAccountingEntry& entry, acentries)
546 txOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
552 void CWallet::WalletUpdateSpent(const CTransaction &tx, bool fBlock)
554 // Anytime a signature is successfully verified, it's proof the outpoint is spent.
555 // Update the wallet spent flag if it doesn't know due to wallet.dat being
556 // restored from backup or the user making copies of wallet.dat.
559 BOOST_FOREACH(const CTxIn& txin, tx.vin)
561 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
562 if (mi != mapWallet.end())
564 CWalletTx& wtx = (*mi).second;
565 if (txin.prevout.n >= wtx.vout.size())
566 printf("WalletUpdateSpent: bad wtx %s\n", wtx.GetHash().ToString().c_str());
567 else if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n]))
569 printf("WalletUpdateSpent found spent coin %snvc %s\n", FormatMoney(wtx.GetCredit(MINE_ALL)).c_str(), wtx.GetHash().ToString().c_str());
570 wtx.MarkSpent(txin.prevout.n);
572 NotifyTransactionChanged(this, txin.prevout.hash, CT_UPDATED);
573 vMintingWalletUpdated.push_back(txin.prevout.hash);
580 uint256 hash = tx.GetHash();
581 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hash);
582 CWalletTx& wtx = (*mi).second;
584 BOOST_FOREACH(const CTxOut& txout, tx.vout)
588 wtx.MarkUnspent(&txout - &tx.vout[0]);
590 NotifyTransactionChanged(this, hash, CT_UPDATED);
591 vMintingWalletUpdated.push_back(hash);
599 void CWallet::MarkDirty()
603 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
604 item.second.MarkDirty();
608 bool CWallet::AddToWallet(const CWalletTx& wtxIn)
610 uint256 hash = wtxIn.GetHash();
613 // Inserts only if not already there, returns tx inserted or tx found
614 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
615 CWalletTx& wtx = (*ret.first).second;
616 wtx.BindWallet(this);
617 bool fInsertedNew = ret.second;
620 wtx.nTimeReceived = GetAdjustedTime();
621 wtx.nOrderPos = IncOrderPosNext();
623 wtx.nTimeSmart = wtx.nTimeReceived;
624 if (wtxIn.hashBlock != 0)
626 if (mapBlockIndex.count(wtxIn.hashBlock))
628 unsigned int latestNow = wtx.nTimeReceived;
629 unsigned int latestEntry = 0;
631 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
632 int64_t latestTolerated = latestNow + 300;
633 std::list<CAccountingEntry> acentries;
634 TxItems txOrdered = OrderedTxItems(acentries);
635 for (TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
637 CWalletTx *const pwtx = (*it).second.first;
640 CAccountingEntry *const pacentry = (*it).second.second;
644 nSmartTime = pwtx->nTimeSmart;
646 nSmartTime = pwtx->nTimeReceived;
649 nSmartTime = pacentry->nTime;
650 if (nSmartTime <= latestTolerated)
652 latestEntry = nSmartTime;
653 if (nSmartTime > latestNow)
654 latestNow = nSmartTime;
660 unsigned int& blocktime = mapBlockIndex[wtxIn.hashBlock]->nTime;
661 wtx.nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
664 printf("AddToWallet() : found %s in block %s not in index\n",
665 wtxIn.GetHash().ToString().substr(0,10).c_str(),
666 wtxIn.hashBlock.ToString().c_str());
670 bool fUpdated = false;
674 if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
676 wtx.hashBlock = wtxIn.hashBlock;
679 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
681 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
682 wtx.nIndex = wtxIn.nIndex;
685 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
687 wtx.fFromMe = wtxIn.fFromMe;
690 fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);
694 printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
697 if (fInsertedNew || fUpdated)
698 if (!wtx.WriteToDisk())
701 // If default receiving address gets used, replace it with a new one
702 CScript scriptDefaultKey;
703 scriptDefaultKey.SetDestination(vchDefaultKey.GetID());
704 BOOST_FOREACH(const CTxOut& txout, wtx.vout)
706 if (txout.scriptPubKey == scriptDefaultKey)
708 CPubKey newDefaultKey;
709 if (GetKeyFromPool(newDefaultKey, false))
711 SetDefaultKey(newDefaultKey);
712 SetAddressBookName(vchDefaultKey.GetID(), "");
717 // since AddToWallet is called directly for self-originating transactions, check for consumption of own coins
718 WalletUpdateSpent(wtx, (wtxIn.hashBlock != 0));
720 // Notify UI of new or updated transaction
721 NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
722 vMintingWalletUpdated.push_back(hash);
723 // notify an external script when a wallet transaction comes in or is updated
724 std::string strCmd = GetArg("-walletnotify", "");
726 if ( !strCmd.empty())
728 boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
729 boost::thread t(runCommand, strCmd); // thread runs free
736 // Add a transaction to the wallet, or update it.
737 // pblock is optional, but should be provided if the transaction is known to be in a block.
738 // If fUpdate is true, existing transactions will be updated.
739 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fFindBlock)
741 uint256 hash = tx.GetHash();
744 bool fExisted = mapWallet.count(hash) != 0;
745 if (fExisted && !fUpdate) return false;
746 if (fExisted || IsMine(tx) || IsFromMe(tx))
748 CWalletTx wtx(this,tx);
749 // Get merkle branch if transaction was found in a block
751 wtx.SetMerkleBranch(pblock);
752 return AddToWallet(wtx);
755 WalletUpdateSpent(tx);
760 bool CWallet::EraseFromWallet(uint256 hash)
766 if (mapWallet.erase(hash))
767 CWalletDB(strWalletFile).EraseTx(hash);
773 isminetype CWallet::IsMine(const CTxIn &txin) const
777 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
778 if (mi != mapWallet.end())
780 const CWalletTx& prev = (*mi).second;
781 if (txin.prevout.n < prev.vout.size())
782 return IsMine(prev.vout[txin.prevout.n]);
788 int64_t CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
792 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
793 if (mi != mapWallet.end())
795 const CWalletTx& prev = (*mi).second;
796 if (txin.prevout.n < prev.vout.size())
797 if (IsMine(prev.vout[txin.prevout.n]) & filter)
798 return prev.vout[txin.prevout.n].nValue;
804 bool CWallet::IsChange(const CTxOut& txout) const
806 // TODO: fix handling of 'change' outputs. The assumption is that any
807 // payment to a script that is ours, but isn't in the address book
808 // is change. That assumption is likely to break when we implement multisignature
809 // wallets that return change back into a multi-signature-protected address;
810 // a better way of identifying which outputs are 'the send' and which are
811 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
812 // which output, if any, was change).
813 if (::IsMine(*this, txout.scriptPubKey))
815 CTxDestination address;
816 if (!ExtractDestination(txout.scriptPubKey, address))
820 if (!mapAddressBook.count(address))
826 int64_t CWalletTx::GetTxTime() const
831 int CWalletTx::GetRequestCount() const
833 // Returns -1 if it wasn't being tracked
836 LOCK(pwallet->cs_wallet);
837 if (IsCoinBase() || IsCoinStake())
842 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
843 if (mi != pwallet->mapRequestCount.end())
844 nRequests = (*mi).second;
849 // Did anyone request this transaction?
850 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
851 if (mi != pwallet->mapRequestCount.end())
853 nRequests = (*mi).second;
855 // How about the block it's in?
856 if (nRequests == 0 && hashBlock != 0)
858 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
859 if (mi != pwallet->mapRequestCount.end())
860 nRequests = (*mi).second;
862 nRequests = 1; // If it's in someone else's block it must have got out
870 void CWalletTx::GetAmounts(int64_t& nGeneratedImmature, int64_t& nGeneratedMature, list<pair<CTxDestination, int64_t> >& listReceived,
871 list<pair<CTxDestination, int64_t> >& listSent, int64_t& nFee, string& strSentAccount, const isminefilter& filter) const
873 nGeneratedImmature = nGeneratedMature = nFee = 0;
874 listReceived.clear();
876 strSentAccount = strFromAccount;
878 if (IsCoinBase() || IsCoinStake())
880 if (GetBlocksToMaturity() > 0)
881 nGeneratedImmature = pwallet->GetCredit(*this, filter);
883 nGeneratedMature = GetCredit(filter);
888 int64_t nDebit = GetDebit(filter);
889 if (nDebit > 0) // debit>0 means we signed/sent this transaction
891 int64_t nValueOut = GetValueOut();
892 nFee = nDebit - nValueOut;
896 BOOST_FOREACH(const CTxOut& txout, vout)
898 isminetype fIsMine = pwallet->IsMine(txout);
899 // Only need to handle txouts if AT LEAST one of these is true:
900 // 1) they debit from us (sent)
901 // 2) the output is to us (received)
904 // Don't report 'change' txouts
905 if (pwallet->IsChange(txout))
908 else if (!(fIsMine & filter))
911 // In either case, we need to get the destination address
912 CTxDestination address;
913 if (!ExtractDestination(txout.scriptPubKey, address))
915 printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
916 this->GetHash().ToString().c_str());
917 address = CNoDestination();
920 // If we are debited by the transaction, add the output as a "sent" entry
922 listSent.push_back(make_pair(address, txout.nValue));
924 // If we are receiving the output, add it as a "received" entry
925 if (fIsMine & filter)
926 listReceived.push_back(make_pair(address, txout.nValue));
931 void CWalletTx::GetAccountAmounts(const string& strAccount, int64_t& nGenerated, int64_t& nReceived,
932 int64_t& nSent, int64_t& nFee, const isminefilter& filter) const
934 nGenerated = nReceived = nSent = nFee = 0;
936 int64_t allGeneratedImmature, allGeneratedMature, allFee;
937 allGeneratedImmature = allGeneratedMature = allFee = 0;
938 string strSentAccount;
939 list<pair<CTxDestination, int64_t> > listReceived;
940 list<pair<CTxDestination, int64_t> > listSent;
941 GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount, filter);
943 if (strAccount == "")
944 nGenerated = allGeneratedMature;
945 if (strAccount == strSentAccount)
947 BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64_t)& s, listSent)
952 LOCK(pwallet->cs_wallet);
953 BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64_t)& r, listReceived)
955 if (pwallet->mapAddressBook.count(r.first))
957 map<CTxDestination, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);
958 if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)
959 nReceived += r.second;
961 else if (strAccount.empty())
963 nReceived += r.second;
969 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
973 const int COPY_DEPTH = 3;
974 if (SetMerkleBranch() < COPY_DEPTH)
976 vector<uint256> vWorkQueue;
977 BOOST_FOREACH(const CTxIn& txin, vin)
978 vWorkQueue.push_back(txin.prevout.hash);
980 // This critsect is OK because txdb is already open
982 LOCK(pwallet->cs_wallet);
983 map<uint256, const CMerkleTx*> mapWalletPrev;
984 set<uint256> setAlreadyDone;
985 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
987 uint256 hash = vWorkQueue[i];
988 if (setAlreadyDone.count(hash))
990 setAlreadyDone.insert(hash);
993 map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
994 if (mi != pwallet->mapWallet.end())
997 BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev)
998 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
1000 else if (mapWalletPrev.count(hash))
1002 tx = *mapWalletPrev[hash];
1004 else if (!fClient && txdb.ReadDiskTx(hash, tx))
1010 printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
1014 int nDepth = tx.SetMerkleBranch();
1015 vtxPrev.push_back(tx);
1017 if (nDepth < COPY_DEPTH)
1019 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1020 vWorkQueue.push_back(txin.prevout.hash);
1026 reverse(vtxPrev.begin(), vtxPrev.end());
1029 bool CWalletTx::WriteToDisk()
1031 return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
1034 // Scan the block chain (starting in pindexStart) for transactions
1035 // from or to us. If fUpdate is true, found transactions that already
1036 // exist in the wallet will be updated.
1037 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
1041 CBlockIndex* pindex = pindexStart;
1047 block.ReadFromDisk(pindex, true);
1048 BOOST_FOREACH(CTransaction& tx, block.vtx)
1050 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
1053 pindex = pindex->pnext;
1059 int CWallet::ScanForWalletTransaction(const uint256& hashTx)
1062 tx.ReadFromDisk(COutPoint(hashTx, 0));
1063 if (AddToWalletIfInvolvingMe(tx, NULL, true, true))
1068 void CWallet::ReacceptWalletTransactions()
1071 bool fRepeat = true;
1076 vector<CDiskTxPos> vMissingTx;
1077 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1079 CWalletTx& wtx = item.second;
1080 if ((wtx.IsCoinBase() && wtx.IsSpent(0)) || (wtx.IsCoinStake() && wtx.IsSpent(1)))
1084 bool fUpdated = false;
1085 if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
1087 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
1088 if (txindex.vSpent.size() != wtx.vout.size())
1090 printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %" PRIszu " != wtx.vout.size() %" PRIszu "\n", txindex.vSpent.size(), wtx.vout.size());
1093 for (unsigned int i = 0; i < txindex.vSpent.size(); i++)
1097 if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i]))
1101 vMissingTx.push_back(txindex.vSpent[i]);
1106 printf("ReacceptWalletTransactions found spent coin %snvc %s\n", FormatMoney(wtx.GetCredit(MINE_ALL)).c_str(), wtx.GetHash().ToString().c_str());
1113 // Re-accept any txes of ours that aren't already in a block
1114 if (!(wtx.IsCoinBase() || wtx.IsCoinStake()))
1115 wtx.AcceptWalletTransaction(txdb, false);
1118 if (!vMissingTx.empty())
1120 // TODO: optimize this to scan just part of the block chain?
1121 if (ScanForWalletTransactions(pindexGenesisBlock))
1122 fRepeat = true; // Found missing transactions: re-do re-accept.
1127 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
1129 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
1131 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
1133 uint256 hash = tx.GetHash();
1134 if (!txdb.ContainsTx(hash))
1135 RelayTransaction((CTransaction)tx, hash);
1138 if (!(IsCoinBase() || IsCoinStake()))
1140 uint256 hash = GetHash();
1141 if (!txdb.ContainsTx(hash))
1143 printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
1144 RelayTransaction((CTransaction)*this, hash);
1149 void CWalletTx::RelayWalletTransaction()
1152 RelayWalletTransaction(txdb);
1155 void CWallet::ResendWalletTransactions(bool fForceResend)
1157 if (!fForceResend) {
1158 // Do this infrequently and randomly to avoid giving away
1159 // that these are our transactions.
1160 static int64_t nNextTime = GetRand(GetTime() + 30 * 60);
1161 if (GetTime() < nNextTime)
1163 bool fFirst = (nNextTime == 0);
1164 nNextTime = GetTime() + GetRand(30 * 60);
1168 // Only do it if there's been a new block since last time
1169 static int64_t nLastTime = 0;
1170 if (nTimeBestReceived < nLastTime)
1172 nLastTime = GetTime();
1175 // Rebroadcast any of our txes that aren't in a block yet
1176 printf("ResendWalletTransactions()\n");
1180 // Sort them in chronological order
1181 multimap<unsigned int, CWalletTx*> mapSorted;
1182 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1184 CWalletTx& wtx = item.second;
1185 // Don't rebroadcast until it's had plenty of time that
1186 // it should have gotten in already by now.
1187 if (fForceResend || nTimeBestReceived - (int64_t)wtx.nTimeReceived > 5 * 60)
1188 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
1190 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
1192 CWalletTx& wtx = *item.second;
1193 if (wtx.CheckTransaction())
1194 wtx.RelayWalletTransaction(txdb);
1196 printf("ResendWalletTransactions() : CheckTransaction failed for transaction %s\n", wtx.GetHash().ToString().c_str());
1206 //////////////////////////////////////////////////////////////////////////////
1212 int64_t CWallet::GetBalance() const
1217 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1219 const CWalletTx* pcoin = &(*it).second;
1220 if (pcoin->IsTrusted())
1221 nTotal += pcoin->GetAvailableCredit();
1228 int64_t CWallet::GetWatchOnlyBalance() const
1233 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1235 const CWalletTx* pcoin = &(*it).second;
1236 if (pcoin->IsTrusted())
1237 nTotal += pcoin->GetAvailableWatchCredit();
1244 int64_t CWallet::GetUnconfirmedBalance() const
1249 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1251 const CWalletTx* pcoin = &(*it).second;
1252 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
1253 nTotal += pcoin->GetAvailableCredit();
1259 int64_t CWallet::GetUnconfirmedWatchOnlyBalance() const
1264 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1266 const CWalletTx* pcoin = &(*it).second;
1267 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
1268 nTotal += pcoin->GetAvailableWatchCredit();
1274 int64_t CWallet::GetImmatureBalance() const
1279 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1281 const CWalletTx* pcoin = &(*it).second;
1282 nTotal += pcoin->GetImmatureCredit();
1288 int64_t CWallet::GetImmatureWatchOnlyBalance() const
1293 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1295 const CWalletTx* pcoin = &(*it).second;
1296 nTotal += pcoin->GetImmatureWatchOnlyCredit();
1302 // populate vCoins with vector of spendable COutputs
1303 void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl) const
1309 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1311 const CWalletTx* pcoin = &(*it).second;
1313 if (!pcoin->IsFinal())
1316 if (fOnlyConfirmed && !pcoin->IsTrusted())
1319 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
1322 if(pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0)
1325 for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
1326 isminetype mine = IsMine(pcoin->vout[i]);
1327 if (!(pcoin->IsSpent(i)) && mine != MINE_NO &&
1328 pcoin->vout[i].nValue >= nMinimumInputValue &&
1329 (!coinControl || !coinControl->HasSelected() || coinControl->IsSelected((*it).first, i)))
1331 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain(), mine == MINE_SPENDABLE));
1338 void CWallet::AvailableCoinsMinConf(vector<COutput>& vCoins, int nConf, int64_t nMinValue, int64_t nMaxValue) const
1344 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1346 const CWalletTx* pcoin = &(*it).second;
1348 if (!pcoin->IsFinal())
1351 if(pcoin->GetDepthInMainChain() < nConf)
1354 for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
1355 isminetype mine = IsMine(pcoin->vout[i]);
1357 // ignore coin if it was already spent or we don't own it
1358 if (pcoin->IsSpent(i) || mine == MINE_NO)
1361 // if coin value is between required limits then add new item to vector
1362 if (pcoin->vout[i].nValue >= nMinValue && pcoin->vout[i].nValue < nMaxValue)
1363 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain(), mine == MINE_SPENDABLE));
1369 static void ApproximateBestSubset(vector<pair<int64_t, pair<const CWalletTx*,unsigned int> > >vValue, int64_t nTotalLower, int64_t nTargetValue,
1370 vector<char>& vfBest, int64_t& nBest, int iterations = 1000)
1372 vector<char> vfIncluded;
1374 vfBest.assign(vValue.size(), true);
1375 nBest = nTotalLower;
1377 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
1379 vfIncluded.assign(vValue.size(), false);
1381 bool fReachedTarget = false;
1382 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
1384 for (unsigned int i = 0; i < vValue.size(); i++)
1386 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
1388 nTotal += vValue[i].first;
1389 vfIncluded[i] = true;
1390 if (nTotal >= nTargetValue)
1392 fReachedTarget = true;
1396 vfBest = vfIncluded;
1398 nTotal -= vValue[i].first;
1399 vfIncluded[i] = false;
1407 int64_t CWallet::GetStake() const
1411 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1413 const CWalletTx* pcoin = &(*it).second;
1414 if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1415 nTotal += CWallet::GetCredit(*pcoin, MINE_ALL);
1420 int64_t CWallet::GetWatchOnlyStake() const
1424 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1426 const CWalletTx* pcoin = &(*it).second;
1427 if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1428 nTotal += CWallet::GetCredit(*pcoin, MINE_WATCH_ONLY);
1433 int64_t CWallet::GetNewMint() const
1437 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1439 const CWalletTx* pcoin = &(*it).second;
1440 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1441 nTotal += CWallet::GetCredit(*pcoin, MINE_ALL);
1446 int64_t CWallet::GetWatchOnlyNewMint() const
1450 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1452 const CWalletTx* pcoin = &(*it).second;
1453 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1454 nTotal += CWallet::GetCredit(*pcoin, MINE_WATCH_ONLY);
1459 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
1461 setCoinsRet.clear();
1464 // List of values less than target
1465 pair<int64_t, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
1466 coinLowestLarger.first = std::numeric_limits<int64_t>::max();
1467 coinLowestLarger.second.first = NULL;
1468 vector<pair<int64_t, pair<const CWalletTx*,unsigned int> > > vValue;
1469 int64_t nTotalLower = 0;
1471 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
1473 BOOST_FOREACH(const COutput &output, vCoins)
1475 if (!output.fSpendable)
1478 const CWalletTx *pcoin = output.tx;
1480 if (output.nDepth < (pcoin->IsFromMe(MINE_ALL) ? nConfMine : nConfTheirs))
1485 // Follow the timestamp rules
1486 if (pcoin->nTime > nSpendTime)
1489 int64_t n = pcoin->vout[i].nValue;
1491 pair<int64_t,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1493 if (n == nTargetValue)
1495 setCoinsRet.insert(coin.second);
1496 nValueRet += coin.first;
1499 else if (n < nTargetValue + CENT)
1501 vValue.push_back(coin);
1504 else if (n < coinLowestLarger.first)
1506 coinLowestLarger = coin;
1510 if (nTotalLower == nTargetValue)
1512 for (unsigned int i = 0; i < vValue.size(); ++i)
1514 setCoinsRet.insert(vValue[i].second);
1515 nValueRet += vValue[i].first;
1520 if (nTotalLower < nTargetValue)
1522 if (coinLowestLarger.second.first == NULL)
1524 setCoinsRet.insert(coinLowestLarger.second);
1525 nValueRet += coinLowestLarger.first;
1529 // Solve subset sum by stochastic approximation
1530 sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
1531 vector<char> vfBest;
1534 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);
1535 if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT)
1536 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000);
1538 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
1539 // or the next bigger coin is closer), return the bigger coin
1540 if (coinLowestLarger.second.first &&
1541 ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest))
1543 setCoinsRet.insert(coinLowestLarger.second);
1544 nValueRet += coinLowestLarger.first;
1547 for (unsigned int i = 0; i < vValue.size(); i++)
1550 setCoinsRet.insert(vValue[i].second);
1551 nValueRet += vValue[i].first;
1554 if (fDebug && GetBoolArg("-printpriority"))
1557 printf("SelectCoins() best subset: ");
1558 for (unsigned int i = 0; i < vValue.size(); i++)
1560 printf("%s ", FormatMoney(vValue[i].first).c_str());
1561 printf("total %s\n", FormatMoney(nBest).c_str());
1568 bool CWallet::SelectCoins(int64_t nTargetValue, unsigned int nSpendTime, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64_t& nValueRet, const CCoinControl* coinControl) const
1570 vector<COutput> vCoins;
1571 AvailableCoins(vCoins, true, coinControl);
1573 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
1574 if (coinControl && coinControl->HasSelected())
1576 BOOST_FOREACH(const COutput& out, vCoins)
1580 nValueRet += out.tx->vout[out.i].nValue;
1581 setCoinsRet.insert(make_pair(out.tx, out.i));
1583 return (nValueRet >= nTargetValue);
1586 return (SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 6, vCoins, setCoinsRet, nValueRet) ||
1587 SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 1, vCoins, setCoinsRet, nValueRet) ||
1588 SelectCoinsMinConf(nTargetValue, nSpendTime, 0, 1, vCoins, setCoinsRet, nValueRet));
1591 // Select some coins without random shuffle or best subset approximation
1592 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
1594 vector<COutput> vCoins;
1595 AvailableCoinsMinConf(vCoins, nMinConf, nMinValue, nMaxValue);
1597 setCoinsRet.clear();
1600 BOOST_FOREACH(COutput output, vCoins)
1602 if(!output.fSpendable)
1604 const CWalletTx *pcoin = output.tx;
1607 // Ignore immature coins
1608 if (pcoin->GetBlocksToMaturity() > 0)
1611 // Stop if we've chosen enough inputs
1612 if (nValueRet >= nTargetValue)
1615 // Follow the timestamp rules
1616 if (pcoin->nTime > nSpendTime)
1619 int64_t n = pcoin->vout[i].nValue;
1621 pair<int64_t,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1623 if (n >= nTargetValue)
1625 // If input value is greater or equal to target then simply insert
1626 // it into the current subset and exit
1627 setCoinsRet.insert(coin.second);
1628 nValueRet += coin.first;
1631 else if (n < nTargetValue + CENT)
1633 setCoinsRet.insert(coin.second);
1634 nValueRet += coin.first;
1641 bool CWallet::CreateTransaction(const vector<pair<CScript, int64_t> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl* coinControl)
1644 BOOST_FOREACH (const PAIRTYPE(CScript, int64_t)& s, vecSend)
1650 if (vecSend.empty() || nValue < 0)
1653 wtxNew.BindWallet(this);
1656 LOCK2(cs_main, cs_wallet);
1657 // txdb must be opened before the mapWallet lock
1660 nFeeRet = nTransactionFee;
1664 wtxNew.vout.clear();
1665 wtxNew.fFromMe = true;
1667 int64_t nTotalValue = nValue + nFeeRet;
1668 double dPriority = 0;
1669 // vouts to the payees
1670 BOOST_FOREACH (const PAIRTYPE(CScript, int64_t)& s, vecSend)
1671 wtxNew.vout.push_back(CTxOut(s.second, s.first));
1673 // Choose coins to use
1674 set<pair<const CWalletTx*,unsigned int> > setCoins;
1675 int64_t nValueIn = 0;
1676 if (!SelectCoins(nTotalValue, wtxNew.nTime, setCoins, nValueIn, coinControl))
1678 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1680 int64_t nCredit = pcoin.first->vout[pcoin.second].nValue;
1681 dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
1684 int64_t nChange = nValueIn - nValue - nFeeRet;
1687 // Fill a vout to ourself
1688 // TODO: pass in scriptChange instead of reservekey so
1689 // change transaction isn't always pay-to-bitcoin-address
1690 CScript scriptChange;
1692 // coin control: send change to custom address
1693 if (coinControl && coinControl->destChange.IsValid())
1694 scriptChange.SetAddress(coinControl->destChange);
1696 // no coin control: send change to newly generated address
1699 // Note: We use a new key here to keep it from being obvious which side is the change.
1700 // The drawback is that by not reusing a previous key, the change may be lost if a
1701 // backup is restored, if the backup doesn't have the new private key for the change.
1702 // If we reused the old key, it would be possible to add code to look for and
1703 // rediscover unknown transactions that were written with keys of ours to recover
1704 // post-backup change.
1706 // Reserve a new key pair from key pool
1707 CPubKey vchPubKey = reservekey.GetReservedKey();
1709 scriptChange.SetDestination(vchPubKey.GetID());
1712 // Insert change txn at random position:
1713 vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
1714 wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
1717 reservekey.ReturnKey();
1720 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1721 wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
1725 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1726 if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
1730 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
1731 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1733 dPriority /= nBytes;
1735 // Check that enough fee is included
1736 bool fAllowFree = CTransaction::AllowFree(dPriority);
1737 int64_t nPayFee = nTransactionFee * (1 + (int64_t)nBytes / 1000);
1738 int64_t nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
1740 if (nFeeRet < max(nPayFee, nMinFee))
1742 nFeeRet = max(nPayFee, nMinFee);
1746 // Fill vtxPrev by copying from previous transactions vtxPrev
1747 wtxNew.AddSupportingTransactions(txdb);
1748 wtxNew.fTimeReceivedIsTxTime = true;
1757 bool CWallet::CreateTransaction(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl* coinControl)
1759 vector< pair<CScript, int64_t> > vecSend;
1760 vecSend.push_back(make_pair(scriptPubKey, nValue));
1761 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, coinControl);
1764 void CWallet::GetStakeWeightFromValue(const int64_t& nTime, const int64_t& nValue, uint64_t& nWeight)
1766 int64_t nTimeWeight = GetWeight(nTime, GetTime());
1768 // If time weight is lower or equal to zero then weight is zero.
1769 if (nTimeWeight <= 0)
1775 CBigNum bnCoinDayWeight = CBigNum(nValue) * nTimeWeight / COIN / nOneDay;
1776 nWeight = bnCoinDayWeight.getuint64();
1779 bool CWallet::MergeCoins(const int64_t& nAmount, const int64_t& nMinValue, const int64_t& nOutputValue, list<uint256>& listMerged)
1781 int64_t nBalance = GetBalance();
1783 if (nAmount > nBalance)
1787 int64_t nValueIn = 0;
1788 set<pair<const CWalletTx*,unsigned int> > setCoins;
1790 // Simple coins selection - no randomization
1791 if (!SelectCoinsSimple(nAmount, nMinValue, nOutputValue, GetTime(), 1, setCoins, nValueIn))
1794 if (setCoins.empty())
1798 vector<const CWalletTx*> vwtxPrev;
1800 // Reserve a new key pair from key pool
1801 CReserveKey reservekey(this);
1802 CPubKey vchPubKey = reservekey.GetReservedKey();
1805 CScript scriptOutput;
1806 scriptOutput.SetDestination(vchPubKey.GetID());
1809 wtxNew.vout.push_back(CTxOut(0, scriptOutput));
1812 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1814 int64_t nCredit = pcoin.first->vout[pcoin.second].nValue;
1816 // Add current coin to inputs list and add its credit to transaction output
1817 wtxNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1818 wtxNew.vout[0].nValue += nCredit;
1819 vwtxPrev.push_back(pcoin.first);
1822 // Replaced with estimation for performance purposes
1824 for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
1825 const CWalletTx *txin = vwtxPrev[i];
1827 // Sign scripts to get actual transaction size for fee calculation
1828 if (!SignSignature(*this, *txin, wtxNew, i))
1833 // Assuming that average scriptsig size is 110 bytes
1834 int64_t nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION) + wtxNew.vin.size() * 110;
1835 dWeight += (double)nCredit * pcoin.first->GetDepthInMainChain();
1837 double dFinalPriority = dWeight /= nBytes;
1838 bool fAllowFree = CTransaction::AllowFree(dFinalPriority);
1840 // Get actual transaction fee according to its estimated size and priority
1841 int64_t nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
1843 // Prepare transaction for commit if sum is enough ot its size is too big
1844 if (nBytes >= MAX_BLOCK_SIZE_GEN/6 || wtxNew.vout[0].nValue >= nOutputValue)
1846 wtxNew.vout[0].nValue -= nMinFee; // Set actual fee
1848 for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
1849 const CWalletTx *txin = vwtxPrev[i];
1852 if (!SignSignature(*this, *txin, wtxNew, i))
1856 // Try to commit, return false on failure
1857 if (!CommitTransaction(wtxNew, reservekey))
1860 listMerged.push_back(wtxNew.GetHash()); // Add to hashes list
1862 dWeight = 0; // Reset all temporary values
1865 wtxNew.vout.push_back(CTxOut(0, scriptOutput));
1869 // Create transactions if there are some unhandled coins left
1870 if (wtxNew.vout[0].nValue > 0) {
1871 int64_t nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION) + wtxNew.vin.size() * 110;
1873 double dFinalPriority = dWeight /= nBytes;
1874 bool fAllowFree = CTransaction::AllowFree(dFinalPriority);
1876 // Get actual transaction fee according to its size and priority
1877 int64_t nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
1879 wtxNew.vout[0].nValue -= nMinFee; // Set actual fee
1881 if (wtxNew.vout[0].nValue <= 0)
1884 for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
1885 const CWalletTx *txin = vwtxPrev[i];
1887 // Sign all scripts again
1888 if (!SignSignature(*this, *txin, wtxNew, i))
1892 // Try to commit, return false on failure
1893 if (!CommitTransaction(wtxNew, reservekey))
1896 listMerged.push_back(wtxNew.GetHash()); // Add to hashes list
1902 bool CWallet::CreateCoinStake(uint256 &hashTx, uint32_t nOut, uint32_t nGenerationTime, uint32_t nBits, CTransaction &txNew, CKey& key)
1905 if (!GetTransaction(hashTx, wtx))
1906 return error("Transaction %s is not found\n", hashTx.GetHex().c_str());
1908 vector<valtype> vSolutions;
1909 txnouttype whichType;
1910 CScript scriptPubKeyOut;
1911 CScript scriptPubKeyKernel = wtx.vout[nOut].scriptPubKey;
1912 if (!Solver(scriptPubKeyKernel, whichType, vSolutions))
1913 return error("CreateCoinStake : failed to parse kernel\n");
1915 if (fDebug && GetBoolArg("-printcoinstake"))
1916 printf("CreateCoinStake : parsed kernel type=%d\n", whichType);
1918 if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH)
1919 return error("CreateCoinStake : no support for kernel type=%d\n", whichType);
1921 if (whichType == TX_PUBKEYHASH) // pay to address type
1923 // convert to pay to public key type
1924 if (!GetKey(uint160(vSolutions[0]), key))
1925 return error("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1927 scriptPubKeyOut << key.GetPubKey() << OP_CHECKSIG;
1929 if (whichType == TX_PUBKEY)
1931 valtype& vchPubKey = vSolutions[0];
1932 if (!GetKey(Hash160(vchPubKey), key))
1933 return error("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1934 if (key.GetPubKey() != vchPubKey)
1935 return error("CreateCoinStake : invalid key for kernel type=%d\n", whichType); // keys mismatch
1936 scriptPubKeyOut = scriptPubKeyKernel;
1939 // The following combine threshold is important to security
1940 // Should not be adjusted if you don't understand the consequences
1941 int64_t nCombineThreshold = GetProofOfWorkReward(GetLastBlockIndex(pindexBest, false)->nBits) / 3;
1943 int64_t nBalance = GetBalance();
1944 int64_t nCredit = wtx.vout[nOut].nValue;
1949 // List of constake dependencies
1950 vector<const CWalletTx*> vwtxPrev;
1951 vwtxPrev.push_back(&wtx);
1953 // Set generation time, and kernel input
1954 txNew.nTime = nGenerationTime;
1955 txNew.vin.push_back(CTxIn(hashTx, nOut));
1957 // Mark coin stake transaction with empty vout[0]
1958 CScript scriptEmpty;
1959 scriptEmpty.clear();
1960 txNew.vout.push_back(CTxOut(0, scriptEmpty));
1962 if (fDebug && GetBoolArg("-printcoinstake"))
1963 printf("CreateCoinStake : added kernel type=%d\n", whichType);
1965 int64_t nValueIn = 0;
1967 if (!SelectCoinsSimple(nBalance - nReserveBalance, MIN_TX_FEE, MAX_MONEY, nGenerationTime, nCoinbaseMaturity * 10, setCoins, nValueIn))
1970 if (setCoins.empty())
1973 bool fDontSplitCoins = false;
1974 if (GetWeight((int64_t)wtx.nTime, (int64_t)nGenerationTime) == nStakeMaxAge)
1976 // Only one output for old kernel inputs
1977 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
1979 // Iterate through set of (wtx*, nout) in order to find some additional inputs for our new coinstake transaction.
1981 // * Value is higher than 0.01 NVC;
1982 // * Only add inputs of the same key/address as kernel;
1983 // * Input hash and kernel parent hash should be different.
1984 for(CoinsSet::iterator pcoin = setCoins.begin(); pcoin != setCoins.end(); pcoin++)
1986 // Stop adding more inputs if already too many inputs
1987 if (txNew.vin.size() >= 100)
1989 // Stop adding more inputs if value is already pretty significant
1990 if (nCredit > nCombineThreshold)
1992 // Stop adding inputs if reached reserve limit
1993 if (nCredit + pcoin->first->vout[pcoin->second].nValue > nBalance - nReserveBalance)
1996 int64_t nTimeWeight = GetWeight((int64_t)pcoin->first->nTime, (int64_t)nGenerationTime);
1998 // Do not add input that is still too young
1999 if (nTimeWeight < nStakeMaxAge)
2001 // Do not add input if key/address is not the same as kernel
2002 if (pcoin->first->vout[pcoin->second].scriptPubKey != scriptPubKeyKernel && pcoin->first->vout[pcoin->second].scriptPubKey != txNew.vout[1].scriptPubKey)
2004 // Do not add input if parents are the same
2005 if (pcoin->first->GetHash() != txNew.vin[0].prevout.hash)
2007 // Do not add additional significant input
2008 if (pcoin->first->vout[pcoin->second].nValue > nCombineThreshold)
2011 txNew.vin.push_back(CTxIn(pcoin->first->GetHash(), pcoin->second));
2012 nCredit += pcoin->first->vout[pcoin->second].nValue;
2013 vwtxPrev.push_back(pcoin->first);
2016 fDontSplitCoins = true;
2020 int64_t nSplitThreshold = GetArg("-splitthreshold", nCombineThreshold);
2022 if (fDebug && GetBoolArg("-printcoinstake"))
2023 printf("CreateCoinStake : nSplitThreshold=%" PRId64 "\n", nSplitThreshold);
2025 if (nCredit > nSplitThreshold)
2027 // Split stake input if credit is lower than combine threshold and maximum weight isn't reached yet
2028 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
2029 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
2031 if (fDebug && GetBoolArg("-printcoinstake"))
2032 printf("CreateCoinStake : splitting coinstake\n");
2036 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
2037 fDontSplitCoins = true;
2041 // Calculate coin age reward
2044 if (!txNew.GetCoinAge(txdb, nCoinAge))
2045 return error("CreateCoinStake : failed to calculate coin age\n");
2046 nCredit += GetProofOfStakeReward(nCoinAge, nBits, nGenerationTime);
2048 int64_t nMinFee = 0;
2051 // Set output amount
2052 if (fDontSplitCoins)
2053 txNew.vout[1].nValue = nCredit - nMinFee;
2056 txNew.vout[1].nValue = ((nCredit - nMinFee) / 2 / CENT) * CENT;
2057 txNew.vout[2].nValue = nCredit - nMinFee - txNew.vout[1].nValue;
2062 BOOST_FOREACH(const CWalletTx* pcoin, vwtxPrev)
2064 if (!SignSignature(*this, *pcoin, txNew, nIn++))
2065 return error("CreateCoinStake : failed to sign coinstake\n");
2069 unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION);
2070 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
2071 return error("CreateCoinStake : exceeded coinstake size limit\n");
2073 // Check enough fee is paid
2074 if (nMinFee < txNew.GetMinFee(1, false, GMF_BLOCK, nBytes) - CENT)
2076 nMinFee = txNew.GetMinFee(1, false, GMF_BLOCK, nBytes) - CENT;
2077 continue; // try signing again
2081 if (fDebug && GetBoolArg("-printfee"))
2082 printf("CreateCoinStake : fee for coinstake %s\n", FormatMoney(nMinFee).c_str());
2087 // Successfully created coinstake
2091 // Call after CreateTransaction unless you want to abort
2092 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
2095 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
2097 // Track how many getdata requests our transaction gets
2098 mapRequestCount[wtxNew.GetHash()] = 0;
2100 // Try to broadcast before saving
2101 if (!wtxNew.AcceptToMemoryPool())
2103 // This must not fail. The transaction has already been signed.
2104 printf("CommitTransaction() : Error: Transaction not valid");
2108 wtxNew.RelayWalletTransaction();
2111 LOCK2(cs_main, cs_wallet);
2113 // This is only to keep the database open to defeat the auto-flush for the
2114 // duration of this scope. This is the only place where this optimization
2115 // maybe makes sense; please don't do it anywhere else.
2116 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
2118 // Take key pair from key pool so it won't be used again
2119 reservekey.KeepKey();
2121 // Add tx to wallet, because if it has change it's also ours,
2122 // otherwise just for transaction history.
2123 AddToWallet(wtxNew);
2125 // Mark old coins as spent
2126 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
2128 CWalletTx &coin = mapWallet[txin.prevout.hash];
2129 coin.BindWallet(this);
2130 coin.MarkSpent(txin.prevout.n);
2132 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
2133 vMintingWalletUpdated.push_back(coin.GetHash());
2146 string CWallet::SendMoney(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, bool fAskFee)
2150 return _("Invalid amount");
2151 if (nValue + nTransactionFee > GetBalance())
2152 return _("Insufficient funds");
2154 CReserveKey reservekey(this);
2155 int64_t nFeeRequired;
2159 string strError = _("Error: Wallet locked, unable to create transaction ");
2160 printf("SendMoney() : %s", strError.c_str());
2163 if (fWalletUnlockMintOnly)
2165 string strError = _("Error: Wallet unlocked for block minting only, unable to create transaction.");
2166 printf("SendMoney() : %s", strError.c_str());
2169 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
2172 if (nValue + nFeeRequired > GetBalance())
2173 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());
2175 strError = _("Error: Transaction creation failed ");
2176 printf("SendMoney() : %s", strError.c_str());
2180 if (fAskFee && !uiInterface.ThreadSafeAskFee(nFeeRequired, _("Sending...")))
2183 if (!CommitTransaction(wtxNew, reservekey))
2184 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.");
2189 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
2193 fFirstRunRet = false;
2194 DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
2195 if (nLoadWalletRet == DB_NEED_REWRITE)
2197 if (CDB::Rewrite(strWalletFile, "\x04pool"))
2200 // Note: can't top-up keypool here, because wallet is locked.
2201 // User will be prompted to unlock wallet the next operation
2202 // the requires a new key.
2206 if (nLoadWalletRet != DB_LOAD_OK)
2207 return nLoadWalletRet;
2208 fFirstRunRet = !vchDefaultKey.IsValid();
2210 NewThread(ThreadFlushWalletDB, &strWalletFile);
2214 DBErrors CWallet::ZapWalletTx()
2218 DBErrors nZapWalletTxRet = CWalletDB(strWalletFile,"cr+").ZapWalletTx(this);
2219 if (nZapWalletTxRet == DB_NEED_REWRITE)
2221 if (CDB::Rewrite(strWalletFile, "\x04pool"))
2225 // Note: can't top-up keypool here, because wallet is locked.
2226 // User will be prompted to unlock wallet the next operation
2227 // the requires a new key.
2231 if (nZapWalletTxRet != DB_LOAD_OK)
2232 return nZapWalletTxRet;
2237 bool CWallet::SetAddressBookName(const CTxDestination& address, const string& strName)
2239 std::map<CTxDestination, std::string>::iterator mi = mapAddressBook.find(address);
2240 mapAddressBook[address] = strName;
2241 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != MINE_NO, (mi == mapAddressBook.end()) ? CT_NEW : CT_UPDATED);
2244 return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName);
2247 bool CWallet::DelAddressBookName(const CTxDestination& address)
2249 mapAddressBook.erase(address);
2250 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != MINE_NO, CT_DELETED);
2253 return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString());
2257 void CWallet::PrintWallet(const CBlock& block)
2261 if (block.IsProofOfStake() && mapWallet.count(block.vtx[1].GetHash()))
2263 CWalletTx& wtx = mapWallet[block.vtx[1].GetHash()];
2264 printf(" PoS: %d %d %" PRId64 "", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit(MINE_ALL));
2266 else if (mapWallet.count(block.vtx[0].GetHash()))
2268 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
2269 printf(" PoW: %d %d %" PRId64 "", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit(MINE_ALL));
2275 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
2279 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
2280 if (mi != mapWallet.end())
2289 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
2293 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
2296 vchDefaultKey = vchPubKey;
2300 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
2302 if (!pwallet->fFileBacked)
2304 strWalletFileOut = pwallet->strWalletFile;
2309 // Mark old keypool keys as used,
2310 // and generate all new keys
2312 bool CWallet::NewKeyPool(unsigned int nSize)
2316 CWalletDB walletdb(strWalletFile);
2317 BOOST_FOREACH(int64_t nIndex, setKeyPool)
2318 walletdb.ErasePool(nIndex);
2328 nKeys = max<uint64_t>(GetArg("-keypool", 100), 0);
2330 for (uint64_t i = 0; i < nKeys; i++)
2332 uint64_t nIndex = i+1;
2333 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
2334 setKeyPool.insert(nIndex);
2336 printf("CWallet::NewKeyPool wrote %" PRIu64 " new keys\n", nKeys);
2341 bool CWallet::TopUpKeyPool(unsigned int nSize)
2349 CWalletDB walletdb(strWalletFile);
2352 uint64_t nTargetSize;
2354 nTargetSize = nSize;
2356 nTargetSize = max<uint64_t>(GetArg("-keypool", 100), 0);
2358 while (setKeyPool.size() < (nTargetSize + 1))
2361 if (!setKeyPool.empty())
2362 nEnd = *(--setKeyPool.end()) + 1;
2363 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
2364 throw runtime_error("TopUpKeyPool() : writing generated key failed");
2365 setKeyPool.insert(nEnd);
2366 printf("keypool added key %" PRIu64 ", size=%" PRIszu "\n", nEnd, setKeyPool.size());
2372 void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool)
2375 keypool.vchPubKey = CPubKey();
2382 // Get the oldest key
2383 if(setKeyPool.empty())
2386 CWalletDB walletdb(strWalletFile);
2388 nIndex = *(setKeyPool.begin());
2389 setKeyPool.erase(setKeyPool.begin());
2390 if (!walletdb.ReadPool(nIndex, keypool))
2391 throw runtime_error("ReserveKeyFromKeyPool() : read failed");
2392 if (!HaveKey(keypool.vchPubKey.GetID()))
2393 throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
2394 assert(keypool.vchPubKey.IsValid());
2395 if (fDebug && GetBoolArg("-printkeypool"))
2396 printf("keypool reserve %" PRId64 "\n", nIndex);
2400 int64_t CWallet::AddReserveKey(const CKeyPool& keypool)
2403 LOCK2(cs_main, cs_wallet);
2404 CWalletDB walletdb(strWalletFile);
2406 int64_t nIndex = 1 + *(--setKeyPool.end());
2407 if (!walletdb.WritePool(nIndex, keypool))
2408 throw runtime_error("AddReserveKey() : writing added key failed");
2409 setKeyPool.insert(nIndex);
2415 void CWallet::KeepKey(int64_t nIndex)
2417 // Remove from key pool
2420 CWalletDB walletdb(strWalletFile);
2421 walletdb.ErasePool(nIndex);
2424 printf("keypool keep %" PRId64 "\n", nIndex);
2427 void CWallet::ReturnKey(int64_t nIndex)
2429 // Return to key pool
2432 setKeyPool.insert(nIndex);
2435 printf("keypool return %" PRId64 "\n", nIndex);
2438 bool CWallet::GetKeyFromPool(CPubKey& result, bool fAllowReuse)
2444 ReserveKeyFromKeyPool(nIndex, keypool);
2447 if (fAllowReuse && vchDefaultKey.IsValid())
2449 result = vchDefaultKey;
2452 if (IsLocked()) return false;
2453 result = GenerateNewKey();
2457 result = keypool.vchPubKey;
2462 int64_t CWallet::GetOldestKeyPoolTime()
2466 ReserveKeyFromKeyPool(nIndex, keypool);
2470 return keypool.nTime;
2473 std::map<CTxDestination, int64_t> CWallet::GetAddressBalances()
2475 map<CTxDestination, int64_t> balances;
2479 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2481 CWalletTx *pcoin = &walletEntry.second;
2483 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
2486 if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0)
2489 int nDepth = pcoin->GetDepthInMainChain();
2490 if (nDepth < (pcoin->IsFromMe(MINE_ALL) ? 0 : 1))
2493 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2495 CTxDestination addr;
2496 if (!IsMine(pcoin->vout[i]))
2498 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr))
2501 int64_t n = pcoin->IsSpent(i) ? 0 : pcoin->vout[i].nValue;
2503 if (!balances.count(addr))
2505 balances[addr] += n;
2513 set< set<CTxDestination> > CWallet::GetAddressGroupings()
2515 set< set<CTxDestination> > groupings;
2516 set<CTxDestination> grouping;
2518 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2520 CWalletTx *pcoin = &walletEntry.second;
2522 if (pcoin->vin.size() > 0 && IsMine(pcoin->vin[0]))
2524 // group all input addresses with each other
2525 BOOST_FOREACH(CTxIn txin, pcoin->vin)
2527 CTxDestination address;
2528 if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
2530 grouping.insert(address);
2533 // group change with input addresses
2534 BOOST_FOREACH(CTxOut txout, pcoin->vout)
2535 if (IsChange(txout))
2537 CWalletTx tx = mapWallet[pcoin->vin[0].prevout.hash];
2538 CTxDestination txoutAddr;
2539 if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
2541 grouping.insert(txoutAddr);
2543 groupings.insert(grouping);
2547 // group lone addrs by themselves
2548 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2549 if (IsMine(pcoin->vout[i]))
2551 CTxDestination address;
2552 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address))
2554 grouping.insert(address);
2555 groupings.insert(grouping);
2560 set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
2561 map< CTxDestination, set<CTxDestination>* > setmap; // map addresses to the unique group containing it
2562 BOOST_FOREACH(set<CTxDestination> grouping, groupings)
2564 // make a set of all the groups hit by this new group
2565 set< set<CTxDestination>* > hits;
2566 map< CTxDestination, set<CTxDestination>* >::iterator it;
2567 BOOST_FOREACH(CTxDestination address, grouping)
2568 if ((it = setmap.find(address)) != setmap.end())
2569 hits.insert((*it).second);
2571 // merge all hit groups into a new single group and delete old groups
2572 set<CTxDestination>* merged = new set<CTxDestination>(grouping);
2573 BOOST_FOREACH(set<CTxDestination>* hit, hits)
2575 merged->insert(hit->begin(), hit->end());
2576 uniqueGroupings.erase(hit);
2579 uniqueGroupings.insert(merged);
2582 BOOST_FOREACH(CTxDestination element, *merged)
2583 setmap[element] = merged;
2586 set< set<CTxDestination> > ret;
2587 BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings)
2589 ret.insert(*uniqueGrouping);
2590 delete uniqueGrouping;
2596 // ppcoin: check 'spent' consistency between wallet and txindex
2597 // ppcoin: fix wallet spent state according to txindex
2598 void CWallet::FixSpentCoins(int& nMismatchFound, int64_t& nBalanceInQuestion, bool fCheckOnly)
2601 nBalanceInQuestion = 0;
2604 vector<CWalletTx*> vCoins;
2605 vCoins.reserve(mapWallet.size());
2606 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2607 vCoins.push_back(&(*it).second);
2610 BOOST_FOREACH(CWalletTx* pcoin, vCoins)
2612 // Find the corresponding transaction index
2614 if (!txdb.ReadTxIndex(pcoin->GetHash(), txindex))
2616 for (unsigned int n=0; n < pcoin->vout.size(); n++)
2618 if (IsMine(pcoin->vout[n]) && pcoin->IsSpent(n) && (txindex.vSpent.size() <= n || txindex.vSpent[n].IsNull()))
2620 printf("FixSpentCoins found lost coin %sppc %s[%u], %s\n",
2621 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2623 nBalanceInQuestion += pcoin->vout[n].nValue;
2626 pcoin->MarkUnspent(n);
2627 pcoin->WriteToDisk();
2630 else if (IsMine(pcoin->vout[n]) && !pcoin->IsSpent(n) && (txindex.vSpent.size() > n && !txindex.vSpent[n].IsNull()))
2632 printf("FixSpentCoins found spent coin %sppc %s[%u], %s\n",
2633 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2635 nBalanceInQuestion += pcoin->vout[n].nValue;
2638 pcoin->MarkSpent(n);
2639 pcoin->WriteToDisk();
2645 if(IsMine((CTransaction)*pcoin) && (pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetDepthInMainChain() == 0)
2647 printf("FixSpentCoins %s tx %s\n", fCheckOnly ? "found" : "removed", pcoin->GetHash().ToString().c_str());
2650 EraseFromWallet(pcoin->GetHash());
2656 // ppcoin: disable transaction (only for coinstake)
2657 void CWallet::DisableTransaction(const CTransaction &tx)
2659 if (!tx.IsCoinStake() || !IsFromMe(tx))
2660 return; // only disconnecting coinstake requires marking input unspent
2663 BOOST_FOREACH(const CTxIn& txin, tx.vin)
2665 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
2666 if (mi != mapWallet.end())
2668 CWalletTx& prev = (*mi).second;
2669 if (txin.prevout.n < prev.vout.size() && IsMine(prev.vout[txin.prevout.n]))
2671 prev.MarkUnspent(txin.prevout.n);
2678 CPubKey CReserveKey::GetReservedKey()
2683 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
2685 vchPubKey = keypool.vchPubKey;
2688 printf("CReserveKey::GetReservedKey(): Warning: Using default key instead of a new key, top up your keypool!");
2689 vchPubKey = pwallet->vchDefaultKey;
2692 assert(vchPubKey.IsValid());
2696 void CReserveKey::KeepKey()
2699 pwallet->KeepKey(nIndex);
2701 vchPubKey = CPubKey();
2704 void CReserveKey::ReturnKey()
2707 pwallet->ReturnKey(nIndex);
2709 vchPubKey = CPubKey();
2712 void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
2716 CWalletDB walletdb(strWalletFile);
2718 LOCK2(cs_main, cs_wallet);
2719 BOOST_FOREACH(const int64_t& id, setKeyPool)
2722 if (!walletdb.ReadPool(id, keypool))
2723 throw runtime_error("GetAllReserveKeyHashes() : read failed");
2724 assert(keypool.vchPubKey.IsValid());
2725 CKeyID keyID = keypool.vchPubKey.GetID();
2726 if (!HaveKey(keyID))
2727 throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
2728 setAddress.insert(keyID);
2732 void CWallet::UpdatedTransaction(const uint256 &hashTx)
2736 // Only notify UI if this transaction is in this wallet
2737 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
2738 if (mi != mapWallet.end())
2740 NotifyTransactionChanged(this, hashTx, CT_UPDATED);
2741 vMintingWalletUpdated.push_back(hashTx);
2746 void CWallet::GetAddresses(std::map<CBitcoinAddress, int64_t> &mapAddresses) const {
2747 mapAddresses.clear();
2749 // get birth times for keys with metadata
2750 for (std::map<CMalleableKeyView, CKeyMetadata>::const_iterator it = mapMalleableKeyMetadata.begin(); it != mapMalleableKeyMetadata.end(); it++) {
2751 CBitcoinAddress addr(it->first.GetMalleablePubKey());
2752 mapAddresses[addr] = it->second.nCreateTime ? it->second.nCreateTime : 0;
2755 for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++) {
2756 CBitcoinAddress addr(it->first);
2757 mapAddresses[addr] = it->second.nCreateTime ? it->second.nCreateTime : 0;
2760 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
2761 // iterate over all wallet transactions...
2762 const CWalletTx &wtx = (*it).second;
2763 if (wtx.hashBlock == 0)
2764 continue; // skip unconfirmed transactions
2766 for(std::vector<CTxOut>::const_iterator it2 = wtx.vout.begin(); it2 != wtx.vout.end(); it2++) {
2767 const CTxOut &out = (*it2);
2768 // iterate over all their outputs
2769 CBitcoinAddress addressRet;
2770 if (const_cast<CWallet*>(this)->ExtractAddress(out.scriptPubKey, addressRet)) {
2771 if (mapAddresses.find(addressRet) != mapAddresses.end() && (mapAddresses[addressRet] == 0 || mapAddresses[addressRet] > wtx.nTime))
2772 mapAddresses[addressRet] = wtx.nTime;
2775 // multisig output affects more than one key
2776 std::vector<CKeyID> vAffected;
2777 ::ExtractAffectedKeys(*this, out.scriptPubKey, vAffected);
2779 for(std::vector<CKeyID>::const_iterator it3 = vAffected.begin(); it3 != vAffected.end(); it3++) {
2780 CBitcoinAddress addrAffected(*it3);
2781 if (mapAddresses.find(addrAffected) != mapAddresses.end() && (mapAddresses[addrAffected] == 0 || mapAddresses[addrAffected] > wtx.nTime))
2782 mapAddresses[addrAffected] = wtx.nTime;
2790 void CWallet::ClearOrphans()
2792 list<uint256> orphans;
2795 for(map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2797 const CWalletTx *wtx = &(*it).second;
2798 if((wtx->IsCoinBase() || wtx->IsCoinStake()) && !wtx->IsInMainChain())
2800 orphans.push_back(wtx->GetHash());
2804 for(list<uint256>::const_iterator it = orphans.begin(); it != orphans.end(); ++it)
2805 EraseFromWallet(*it);
2808 bool CWallet::ExtractAddress(const CScript& scriptPubKey, CBitcoinAddress& addressRet)
2810 vector<valtype> vSolutions;
2811 txnouttype whichType;
2812 if (!Solver(scriptPubKey, whichType, vSolutions))
2815 if (whichType == TX_PUBKEY)
2817 addressRet = CBitcoinAddress(CPubKey(vSolutions[0]).GetID());
2820 if (whichType == TX_PUBKEY_DROP)
2823 CMalleableKeyView view;
2824 if (!CheckOwnership(CPubKey(vSolutions[0]), CPubKey(vSolutions[1]), view))
2827 addressRet = CBitcoinAddress(view.GetMalleablePubKey());
2830 else if (whichType == TX_PUBKEYHASH)
2832 addressRet = CBitcoinAddress(CKeyID(uint160(vSolutions[0])));
2835 else if (whichType == TX_SCRIPTHASH)
2837 addressRet = CBitcoinAddress(CScriptID(uint160(vSolutions[0])));
2840 // Multisig txns have more than one address...