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()
1157 // Do this infrequently and randomly to avoid giving away
1158 // that these are our transactions.
1159 static int64_t nNextTime = GetRand(GetTime() + 30 * 60);
1160 if (GetTime() < nNextTime)
1162 bool fFirst = (nNextTime == 0);
1163 nNextTime = GetTime() + GetRand(30 * 60);
1167 // Only do it if there's been a new block since last time
1168 static int64_t nLastTime = 0;
1169 if (nTimeBestReceived < nLastTime)
1171 nLastTime = GetTime();
1173 // Rebroadcast any of our txes that aren't in a block yet
1174 printf("ResendWalletTransactions()\n");
1178 // Sort them in chronological order
1179 multimap<unsigned int, CWalletTx*> mapSorted;
1180 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1182 CWalletTx& wtx = item.second;
1183 // Don't rebroadcast until it's had plenty of time that
1184 // it should have gotten in already by now.
1185 if (nTimeBestReceived - (int64_t)wtx.nTimeReceived > 5 * 60)
1186 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
1188 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
1190 CWalletTx& wtx = *item.second;
1191 if (wtx.CheckTransaction())
1192 wtx.RelayWalletTransaction(txdb);
1194 printf("ResendWalletTransactions() : CheckTransaction failed for transaction %s\n", wtx.GetHash().ToString().c_str());
1204 //////////////////////////////////////////////////////////////////////////////
1210 int64_t CWallet::GetBalance() const
1215 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1217 const CWalletTx* pcoin = &(*it).second;
1218 if (pcoin->IsTrusted())
1219 nTotal += pcoin->GetAvailableCredit();
1226 int64_t CWallet::GetWatchOnlyBalance() const
1231 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1233 const CWalletTx* pcoin = &(*it).second;
1234 if (pcoin->IsTrusted())
1235 nTotal += pcoin->GetAvailableWatchCredit();
1242 int64_t CWallet::GetUnconfirmedBalance() const
1247 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1249 const CWalletTx* pcoin = &(*it).second;
1250 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
1251 nTotal += pcoin->GetAvailableCredit();
1257 int64_t CWallet::GetUnconfirmedWatchOnlyBalance() const
1262 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1264 const CWalletTx* pcoin = &(*it).second;
1265 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
1266 nTotal += pcoin->GetAvailableWatchCredit();
1272 int64_t CWallet::GetImmatureBalance() const
1277 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1279 const CWalletTx* pcoin = &(*it).second;
1280 nTotal += pcoin->GetImmatureCredit();
1286 int64_t CWallet::GetImmatureWatchOnlyBalance() const
1291 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1293 const CWalletTx* pcoin = &(*it).second;
1294 nTotal += pcoin->GetImmatureWatchOnlyCredit();
1300 // populate vCoins with vector of spendable COutputs
1301 void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl) const
1307 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1309 const CWalletTx* pcoin = &(*it).second;
1311 if (!pcoin->IsFinal())
1314 if (fOnlyConfirmed && !pcoin->IsTrusted())
1317 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
1320 if(pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0)
1323 for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
1324 isminetype mine = IsMine(pcoin->vout[i]);
1325 if (!(pcoin->IsSpent(i)) && mine != MINE_NO &&
1326 pcoin->vout[i].nValue >= nMinimumInputValue &&
1327 (!coinControl || !coinControl->HasSelected() || coinControl->IsSelected((*it).first, i)))
1329 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain(), mine == MINE_SPENDABLE));
1336 void CWallet::AvailableCoinsMinConf(vector<COutput>& vCoins, int nConf, int64_t nMinValue, int64_t nMaxValue) const
1342 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1344 const CWalletTx* pcoin = &(*it).second;
1346 if (!pcoin->IsFinal())
1349 if(pcoin->GetDepthInMainChain() < nConf)
1352 for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
1353 isminetype mine = IsMine(pcoin->vout[i]);
1355 // ignore coin if it was already spent or we don't own it
1356 if (pcoin->IsSpent(i) || mine == MINE_NO)
1359 // if coin value is between required limits then add new item to vector
1360 if (pcoin->vout[i].nValue >= nMinValue && pcoin->vout[i].nValue < nMaxValue)
1361 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain(), mine == MINE_SPENDABLE));
1367 static void ApproximateBestSubset(vector<pair<int64_t, pair<const CWalletTx*,unsigned int> > >vValue, int64_t nTotalLower, int64_t nTargetValue,
1368 vector<char>& vfBest, int64_t& nBest, int iterations = 1000)
1370 vector<char> vfIncluded;
1372 vfBest.assign(vValue.size(), true);
1373 nBest = nTotalLower;
1375 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
1377 vfIncluded.assign(vValue.size(), false);
1379 bool fReachedTarget = false;
1380 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
1382 for (unsigned int i = 0; i < vValue.size(); i++)
1384 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
1386 nTotal += vValue[i].first;
1387 vfIncluded[i] = true;
1388 if (nTotal >= nTargetValue)
1390 fReachedTarget = true;
1394 vfBest = vfIncluded;
1396 nTotal -= vValue[i].first;
1397 vfIncluded[i] = false;
1405 int64_t CWallet::GetStake() const
1409 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1411 const CWalletTx* pcoin = &(*it).second;
1412 if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1413 nTotal += CWallet::GetCredit(*pcoin, MINE_ALL);
1418 int64_t CWallet::GetWatchOnlyStake() const
1422 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1424 const CWalletTx* pcoin = &(*it).second;
1425 if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1426 nTotal += CWallet::GetCredit(*pcoin, MINE_WATCH_ONLY);
1431 int64_t CWallet::GetNewMint() const
1435 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1437 const CWalletTx* pcoin = &(*it).second;
1438 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1439 nTotal += CWallet::GetCredit(*pcoin, MINE_ALL);
1444 int64_t CWallet::GetWatchOnlyNewMint() const
1448 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1450 const CWalletTx* pcoin = &(*it).second;
1451 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1452 nTotal += CWallet::GetCredit(*pcoin, MINE_WATCH_ONLY);
1457 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
1459 setCoinsRet.clear();
1462 // List of values less than target
1463 pair<int64_t, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
1464 coinLowestLarger.first = std::numeric_limits<int64_t>::max();
1465 coinLowestLarger.second.first = NULL;
1466 vector<pair<int64_t, pair<const CWalletTx*,unsigned int> > > vValue;
1467 int64_t nTotalLower = 0;
1469 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
1471 BOOST_FOREACH(const COutput &output, vCoins)
1473 if (!output.fSpendable)
1476 const CWalletTx *pcoin = output.tx;
1478 if (output.nDepth < (pcoin->IsFromMe(MINE_ALL) ? nConfMine : nConfTheirs))
1483 // Follow the timestamp rules
1484 if (pcoin->nTime > nSpendTime)
1487 int64_t n = pcoin->vout[i].nValue;
1489 pair<int64_t,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1491 if (n == nTargetValue)
1493 setCoinsRet.insert(coin.second);
1494 nValueRet += coin.first;
1497 else if (n < nTargetValue + CENT)
1499 vValue.push_back(coin);
1502 else if (n < coinLowestLarger.first)
1504 coinLowestLarger = coin;
1508 if (nTotalLower == nTargetValue)
1510 for (unsigned int i = 0; i < vValue.size(); ++i)
1512 setCoinsRet.insert(vValue[i].second);
1513 nValueRet += vValue[i].first;
1518 if (nTotalLower < nTargetValue)
1520 if (coinLowestLarger.second.first == NULL)
1522 setCoinsRet.insert(coinLowestLarger.second);
1523 nValueRet += coinLowestLarger.first;
1527 // Solve subset sum by stochastic approximation
1528 sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
1529 vector<char> vfBest;
1532 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);
1533 if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT)
1534 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000);
1536 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
1537 // or the next bigger coin is closer), return the bigger coin
1538 if (coinLowestLarger.second.first &&
1539 ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest))
1541 setCoinsRet.insert(coinLowestLarger.second);
1542 nValueRet += coinLowestLarger.first;
1545 for (unsigned int i = 0; i < vValue.size(); i++)
1548 setCoinsRet.insert(vValue[i].second);
1549 nValueRet += vValue[i].first;
1552 if (fDebug && GetBoolArg("-printpriority"))
1555 printf("SelectCoins() best subset: ");
1556 for (unsigned int i = 0; i < vValue.size(); i++)
1558 printf("%s ", FormatMoney(vValue[i].first).c_str());
1559 printf("total %s\n", FormatMoney(nBest).c_str());
1566 bool CWallet::SelectCoins(int64_t nTargetValue, unsigned int nSpendTime, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64_t& nValueRet, const CCoinControl* coinControl) const
1568 vector<COutput> vCoins;
1569 AvailableCoins(vCoins, true, coinControl);
1571 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
1572 if (coinControl && coinControl->HasSelected())
1574 BOOST_FOREACH(const COutput& out, vCoins)
1578 nValueRet += out.tx->vout[out.i].nValue;
1579 setCoinsRet.insert(make_pair(out.tx, out.i));
1581 return (nValueRet >= nTargetValue);
1584 return (SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 6, vCoins, setCoinsRet, nValueRet) ||
1585 SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 1, vCoins, setCoinsRet, nValueRet) ||
1586 SelectCoinsMinConf(nTargetValue, nSpendTime, 0, 1, vCoins, setCoinsRet, nValueRet));
1589 // Select some coins without random shuffle or best subset approximation
1590 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
1592 vector<COutput> vCoins;
1593 AvailableCoinsMinConf(vCoins, nMinConf, nMinValue, nMaxValue);
1595 setCoinsRet.clear();
1598 BOOST_FOREACH(COutput output, vCoins)
1600 if(!output.fSpendable)
1602 const CWalletTx *pcoin = output.tx;
1605 // Ignore immature coins
1606 if (pcoin->GetBlocksToMaturity() > 0)
1609 // Stop if we've chosen enough inputs
1610 if (nValueRet >= nTargetValue)
1613 // Follow the timestamp rules
1614 if (pcoin->nTime > nSpendTime)
1617 int64_t n = pcoin->vout[i].nValue;
1619 pair<int64_t,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1621 if (n >= nTargetValue)
1623 // If input value is greater or equal to target then simply insert
1624 // it into the current subset and exit
1625 setCoinsRet.insert(coin.second);
1626 nValueRet += coin.first;
1629 else if (n < nTargetValue + CENT)
1631 setCoinsRet.insert(coin.second);
1632 nValueRet += coin.first;
1639 bool CWallet::CreateTransaction(const vector<pair<CScript, int64_t> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl* coinControl)
1642 BOOST_FOREACH (const PAIRTYPE(CScript, int64_t)& s, vecSend)
1648 if (vecSend.empty() || nValue < 0)
1651 wtxNew.BindWallet(this);
1654 LOCK2(cs_main, cs_wallet);
1655 // txdb must be opened before the mapWallet lock
1658 nFeeRet = nTransactionFee;
1662 wtxNew.vout.clear();
1663 wtxNew.fFromMe = true;
1665 int64_t nTotalValue = nValue + nFeeRet;
1666 double dPriority = 0;
1667 // vouts to the payees
1668 BOOST_FOREACH (const PAIRTYPE(CScript, int64_t)& s, vecSend)
1669 wtxNew.vout.push_back(CTxOut(s.second, s.first));
1671 // Choose coins to use
1672 set<pair<const CWalletTx*,unsigned int> > setCoins;
1673 int64_t nValueIn = 0;
1674 if (!SelectCoins(nTotalValue, wtxNew.nTime, setCoins, nValueIn, coinControl))
1676 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1678 int64_t nCredit = pcoin.first->vout[pcoin.second].nValue;
1679 dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
1682 int64_t nChange = nValueIn - nValue - nFeeRet;
1685 // Fill a vout to ourself
1686 // TODO: pass in scriptChange instead of reservekey so
1687 // change transaction isn't always pay-to-bitcoin-address
1688 CScript scriptChange;
1690 // coin control: send change to custom address
1691 if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange))
1692 scriptChange.SetDestination(coinControl->destChange);
1694 // no coin control: send change to newly generated address
1697 // Note: We use a new key here to keep it from being obvious which side is the change.
1698 // The drawback is that by not reusing a previous key, the change may be lost if a
1699 // backup is restored, if the backup doesn't have the new private key for the change.
1700 // If we reused the old key, it would be possible to add code to look for and
1701 // rediscover unknown transactions that were written with keys of ours to recover
1702 // post-backup change.
1704 // Reserve a new key pair from key pool
1705 CPubKey vchPubKey = reservekey.GetReservedKey();
1707 scriptChange.SetDestination(vchPubKey.GetID());
1710 // Insert change txn at random position:
1711 vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
1712 wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
1715 reservekey.ReturnKey();
1718 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1719 wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
1723 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1724 if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
1728 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
1729 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1731 dPriority /= nBytes;
1733 // Check that enough fee is included
1734 bool fAllowFree = CTransaction::AllowFree(dPriority);
1735 int64_t nPayFee = nTransactionFee * (1 + (int64_t)nBytes / 1000);
1736 int64_t nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
1738 if (nFeeRet < max(nPayFee, nMinFee))
1740 nFeeRet = max(nPayFee, nMinFee);
1744 // Fill vtxPrev by copying from previous transactions vtxPrev
1745 wtxNew.AddSupportingTransactions(txdb);
1746 wtxNew.fTimeReceivedIsTxTime = true;
1755 bool CWallet::CreateTransaction(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl* coinControl)
1757 vector< pair<CScript, int64_t> > vecSend;
1758 vecSend.push_back(make_pair(scriptPubKey, nValue));
1759 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, coinControl);
1762 void CWallet::GetStakeWeightFromValue(const int64_t& nTime, const int64_t& nValue, uint64_t& nWeight)
1764 int64_t nTimeWeight = GetWeight(nTime, GetTime());
1766 // If time weight is lower or equal to zero then weight is zero.
1767 if (nTimeWeight <= 0)
1773 CBigNum bnCoinDayWeight = CBigNum(nValue) * nTimeWeight / COIN / nOneDay;
1774 nWeight = bnCoinDayWeight.getuint64();
1777 bool CWallet::MergeCoins(const int64_t& nAmount, const int64_t& nMinValue, const int64_t& nOutputValue, list<uint256>& listMerged)
1779 int64_t nBalance = GetBalance();
1781 if (nAmount > nBalance)
1785 int64_t nValueIn = 0;
1786 set<pair<const CWalletTx*,unsigned int> > setCoins;
1788 // Simple coins selection - no randomization
1789 if (!SelectCoinsSimple(nAmount, nMinValue, nOutputValue, GetTime(), 1, setCoins, nValueIn))
1792 if (setCoins.empty())
1796 vector<const CWalletTx*> vwtxPrev;
1798 // Reserve a new key pair from key pool
1799 CReserveKey reservekey(this);
1800 CPubKey vchPubKey = reservekey.GetReservedKey();
1803 CScript scriptOutput;
1804 scriptOutput.SetDestination(vchPubKey.GetID());
1807 wtxNew.vout.push_back(CTxOut(0, scriptOutput));
1810 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1812 int64_t nCredit = pcoin.first->vout[pcoin.second].nValue;
1814 // Add current coin to inputs list and add its credit to transaction output
1815 wtxNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1816 wtxNew.vout[0].nValue += nCredit;
1817 vwtxPrev.push_back(pcoin.first);
1820 // Replaced with estimation for performance purposes
1822 for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
1823 const CWalletTx *txin = vwtxPrev[i];
1825 // Sign scripts to get actual transaction size for fee calculation
1826 if (!SignSignature(*this, *txin, wtxNew, i))
1831 // Assuming that average scriptsig size is 110 bytes
1832 int64_t nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION) + wtxNew.vin.size() * 110;
1833 dWeight += (double)nCredit * pcoin.first->GetDepthInMainChain();
1835 double dFinalPriority = dWeight /= nBytes;
1836 bool fAllowFree = CTransaction::AllowFree(dFinalPriority);
1838 // Get actual transaction fee according to its estimated size and priority
1839 int64_t nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
1841 // Prepare transaction for commit if sum is enough ot its size is too big
1842 if (nBytes >= MAX_BLOCK_SIZE_GEN/6 || wtxNew.vout[0].nValue >= nOutputValue)
1844 wtxNew.vout[0].nValue -= nMinFee; // Set actual fee
1846 for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
1847 const CWalletTx *txin = vwtxPrev[i];
1850 if (!SignSignature(*this, *txin, wtxNew, i))
1854 // Try to commit, return false on failure
1855 if (!CommitTransaction(wtxNew, reservekey))
1858 listMerged.push_back(wtxNew.GetHash()); // Add to hashes list
1860 dWeight = 0; // Reset all temporary values
1863 wtxNew.vout.push_back(CTxOut(0, scriptOutput));
1867 // Create transactions if there are some unhandled coins left
1868 if (wtxNew.vout[0].nValue > 0) {
1869 int64_t nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION) + wtxNew.vin.size() * 110;
1871 double dFinalPriority = dWeight /= nBytes;
1872 bool fAllowFree = CTransaction::AllowFree(dFinalPriority);
1874 // Get actual transaction fee according to its size and priority
1875 int64_t nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
1877 wtxNew.vout[0].nValue -= nMinFee; // Set actual fee
1879 if (wtxNew.vout[0].nValue <= 0)
1882 for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
1883 const CWalletTx *txin = vwtxPrev[i];
1885 // Sign all scripts again
1886 if (!SignSignature(*this, *txin, wtxNew, i))
1890 // Try to commit, return false on failure
1891 if (!CommitTransaction(wtxNew, reservekey))
1894 listMerged.push_back(wtxNew.GetHash()); // Add to hashes list
1900 bool CWallet::CreateCoinStake(uint256 &hashTx, uint32_t nOut, uint32_t nGenerationTime, uint32_t nBits, CTransaction &txNew, CKey& key)
1903 if (!GetTransaction(hashTx, wtx))
1904 return error("Transaction %s is not found\n", hashTx.GetHex().c_str());
1906 vector<valtype> vSolutions;
1907 txnouttype whichType;
1908 CScript scriptPubKeyOut;
1909 CScript scriptPubKeyKernel = wtx.vout[nOut].scriptPubKey;
1910 if (!Solver(scriptPubKeyKernel, whichType, vSolutions))
1911 return error("CreateCoinStake : failed to parse kernel\n");
1913 if (fDebug && GetBoolArg("-printcoinstake"))
1914 printf("CreateCoinStake : parsed kernel type=%d\n", whichType);
1916 if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH)
1917 return error("CreateCoinStake : no support for kernel type=%d\n", whichType);
1919 if (whichType == TX_PUBKEYHASH) // pay to address type
1921 // convert to pay to public key type
1922 if (!GetKey(uint160(vSolutions[0]), key))
1923 return error("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1925 scriptPubKeyOut << key.GetPubKey() << OP_CHECKSIG;
1927 if (whichType == TX_PUBKEY)
1929 valtype& vchPubKey = vSolutions[0];
1930 if (!GetKey(Hash160(vchPubKey), key))
1931 return error("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1932 if (key.GetPubKey() != vchPubKey)
1933 return error("CreateCoinStake : invalid key for kernel type=%d\n", whichType); // keys mismatch
1934 scriptPubKeyOut = scriptPubKeyKernel;
1937 // The following combine threshold is important to security
1938 // Should not be adjusted if you don't understand the consequences
1939 int64_t nCombineThreshold = GetProofOfWorkReward(GetLastBlockIndex(pindexBest, false)->nBits) / 3;
1941 int64_t nBalance = GetBalance();
1942 int64_t nCredit = wtx.vout[nOut].nValue;
1947 // List of constake dependencies
1948 vector<const CWalletTx*> vwtxPrev;
1949 vwtxPrev.push_back(&wtx);
1951 // Set generation time, and kernel input
1952 txNew.nTime = nGenerationTime;
1953 txNew.vin.push_back(CTxIn(hashTx, nOut));
1955 // Mark coin stake transaction with empty vout[0]
1956 CScript scriptEmpty;
1957 scriptEmpty.clear();
1958 txNew.vout.push_back(CTxOut(0, scriptEmpty));
1960 if (fDebug && GetBoolArg("-printcoinstake"))
1961 printf("CreateCoinStake : added kernel type=%d\n", whichType);
1963 int64_t nValueIn = 0;
1965 if (!SelectCoinsSimple(nBalance - nReserveBalance, MIN_TX_FEE, MAX_MONEY, nGenerationTime, nCoinbaseMaturity * 10, setCoins, nValueIn))
1968 if (setCoins.empty())
1971 bool fDontSplitCoins = false;
1972 if (GetWeight((int64_t)wtx.nTime, (int64_t)nGenerationTime) == nStakeMaxAge)
1974 // Only one output for old kernel inputs
1975 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
1977 // Iterate through set of (wtx*, nout) in order to find some additional inputs for our new coinstake transaction.
1979 // * Value is higher than 0.01 NVC;
1980 // * Only add inputs of the same key/address as kernel;
1981 // * Input hash and kernel parent hash should be different.
1982 for(CoinsSet::iterator pcoin = setCoins.begin(); pcoin != setCoins.end(); pcoin++)
1984 // Stop adding more inputs if already too many inputs
1985 if (txNew.vin.size() >= 100)
1987 // Stop adding more inputs if value is already pretty significant
1988 if (nCredit > nCombineThreshold)
1990 // Stop adding inputs if reached reserve limit
1991 if (nCredit + pcoin->first->vout[pcoin->second].nValue > nBalance - nReserveBalance)
1994 int64_t nTimeWeight = GetWeight((int64_t)pcoin->first->nTime, (int64_t)nGenerationTime);
1996 // Do not add input that is still too young
1997 if (nTimeWeight < nStakeMaxAge)
1999 // Do not add input if key/address is not the same as kernel
2000 if (pcoin->first->vout[pcoin->second].scriptPubKey != scriptPubKeyKernel && pcoin->first->vout[pcoin->second].scriptPubKey != txNew.vout[1].scriptPubKey)
2002 // Do not add input if parents are the same
2003 if (pcoin->first->GetHash() != txNew.vin[0].prevout.hash)
2005 // Do not add additional significant input
2006 if (pcoin->first->vout[pcoin->second].nValue > nCombineThreshold)
2009 txNew.vin.push_back(CTxIn(pcoin->first->GetHash(), pcoin->second));
2010 nCredit += pcoin->first->vout[pcoin->second].nValue;
2011 vwtxPrev.push_back(pcoin->first);
2014 fDontSplitCoins = true;
2018 int64_t nSplitThreshold = GetArg("-splitthreshold", nCombineThreshold);
2020 if (fDebug && GetBoolArg("-printcoinstake"))
2021 printf("CreateCoinStake : nSplitThreshold=%" PRId64 "\n", nSplitThreshold);
2023 if (nCredit > nSplitThreshold)
2025 // Split stake input if credit is lower than combine threshold and maximum weight isn't reached yet
2026 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
2027 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
2029 if (fDebug && GetBoolArg("-printcoinstake"))
2030 printf("CreateCoinStake : splitting coinstake\n");
2034 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
2035 fDontSplitCoins = true;
2039 // Calculate coin age reward
2042 if (!txNew.GetCoinAge(txdb, nCoinAge))
2043 return error("CreateCoinStake : failed to calculate coin age\n");
2044 nCredit += GetProofOfStakeReward(nCoinAge, nBits, nGenerationTime);
2046 int64_t nMinFee = 0;
2049 // Set output amount
2050 if (fDontSplitCoins)
2051 txNew.vout[1].nValue = nCredit - nMinFee;
2054 txNew.vout[1].nValue = ((nCredit - nMinFee) / 2 / CENT) * CENT;
2055 txNew.vout[2].nValue = nCredit - nMinFee - txNew.vout[1].nValue;
2060 BOOST_FOREACH(const CWalletTx* pcoin, vwtxPrev)
2062 if (!SignSignature(*this, *pcoin, txNew, nIn++))
2063 return error("CreateCoinStake : failed to sign coinstake\n");
2067 unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION);
2068 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
2069 return error("CreateCoinStake : exceeded coinstake size limit\n");
2071 // Check enough fee is paid
2072 if (nMinFee < txNew.GetMinFee(1, false, GMF_BLOCK, nBytes) - CENT)
2074 nMinFee = txNew.GetMinFee(1, false, GMF_BLOCK, nBytes) - CENT;
2075 continue; // try signing again
2079 if (fDebug && GetBoolArg("-printfee"))
2080 printf("CreateCoinStake : fee for coinstake %s\n", FormatMoney(nMinFee).c_str());
2085 // Successfully created coinstake
2089 // Call after CreateTransaction unless you want to abort
2090 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
2093 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
2095 // Track how many getdata requests our transaction gets
2096 mapRequestCount[wtxNew.GetHash()] = 0;
2098 // Try to broadcast before saving
2099 if (!wtxNew.AcceptToMemoryPool())
2101 // This must not fail. The transaction has already been signed.
2102 printf("CommitTransaction() : Error: Transaction not valid");
2106 wtxNew.RelayWalletTransaction();
2109 LOCK2(cs_main, cs_wallet);
2111 // This is only to keep the database open to defeat the auto-flush for the
2112 // duration of this scope. This is the only place where this optimization
2113 // maybe makes sense; please don't do it anywhere else.
2114 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
2116 // Take key pair from key pool so it won't be used again
2117 reservekey.KeepKey();
2119 // Add tx to wallet, because if it has change it's also ours,
2120 // otherwise just for transaction history.
2121 AddToWallet(wtxNew);
2123 // Mark old coins as spent
2124 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
2126 CWalletTx &coin = mapWallet[txin.prevout.hash];
2127 coin.BindWallet(this);
2128 coin.MarkSpent(txin.prevout.n);
2130 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
2131 vMintingWalletUpdated.push_back(coin.GetHash());
2144 string CWallet::SendMoney(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, bool fAskFee)
2148 return _("Invalid amount");
2149 if (nValue + nTransactionFee > GetBalance())
2150 return _("Insufficient funds");
2152 CReserveKey reservekey(this);
2153 int64_t nFeeRequired;
2157 string strError = _("Error: Wallet locked, unable to create transaction ");
2158 printf("SendMoney() : %s", strError.c_str());
2161 if (fWalletUnlockMintOnly)
2163 string strError = _("Error: Wallet unlocked for block minting only, unable to create transaction.");
2164 printf("SendMoney() : %s", strError.c_str());
2167 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
2170 if (nValue + nFeeRequired > GetBalance())
2171 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());
2173 strError = _("Error: Transaction creation failed ");
2174 printf("SendMoney() : %s", strError.c_str());
2178 if (fAskFee && !uiInterface.ThreadSafeAskFee(nFeeRequired, _("Sending...")))
2181 if (!CommitTransaction(wtxNew, reservekey))
2182 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.");
2187 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
2191 fFirstRunRet = false;
2192 DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
2193 if (nLoadWalletRet == DB_NEED_REWRITE)
2195 if (CDB::Rewrite(strWalletFile, "\x04pool"))
2198 // Note: can't top-up keypool here, because wallet is locked.
2199 // User will be prompted to unlock wallet the next operation
2200 // the requires a new key.
2204 if (nLoadWalletRet != DB_LOAD_OK)
2205 return nLoadWalletRet;
2206 fFirstRunRet = !vchDefaultKey.IsValid();
2208 NewThread(ThreadFlushWalletDB, &strWalletFile);
2212 DBErrors CWallet::ZapWalletTx()
2216 DBErrors nZapWalletTxRet = CWalletDB(strWalletFile,"cr+").ZapWalletTx(this);
2217 if (nZapWalletTxRet == DB_NEED_REWRITE)
2219 if (CDB::Rewrite(strWalletFile, "\x04pool"))
2223 // Note: can't top-up keypool here, because wallet is locked.
2224 // User will be prompted to unlock wallet the next operation
2225 // the requires a new key.
2229 if (nZapWalletTxRet != DB_LOAD_OK)
2230 return nZapWalletTxRet;
2235 bool CWallet::SetAddressBookName(const CTxDestination& address, const string& strName)
2237 std::map<CTxDestination, std::string>::iterator mi = mapAddressBook.find(address);
2238 mapAddressBook[address] = strName;
2239 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != MINE_NO, (mi == mapAddressBook.end()) ? CT_NEW : CT_UPDATED);
2242 return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName);
2245 bool CWallet::DelAddressBookName(const CTxDestination& address)
2247 mapAddressBook.erase(address);
2248 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != MINE_NO, CT_DELETED);
2251 return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString());
2255 void CWallet::PrintWallet(const CBlock& block)
2259 if (block.IsProofOfStake() && mapWallet.count(block.vtx[1].GetHash()))
2261 CWalletTx& wtx = mapWallet[block.vtx[1].GetHash()];
2262 printf(" PoS: %d %d %" PRId64 "", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit(MINE_ALL));
2264 else if (mapWallet.count(block.vtx[0].GetHash()))
2266 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
2267 printf(" PoW: %d %d %" PRId64 "", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit(MINE_ALL));
2273 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
2277 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
2278 if (mi != mapWallet.end())
2287 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
2291 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
2294 vchDefaultKey = vchPubKey;
2298 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
2300 if (!pwallet->fFileBacked)
2302 strWalletFileOut = pwallet->strWalletFile;
2307 // Mark old keypool keys as used,
2308 // and generate all new keys
2310 bool CWallet::NewKeyPool(unsigned int nSize)
2314 CWalletDB walletdb(strWalletFile);
2315 BOOST_FOREACH(int64_t nIndex, setKeyPool)
2316 walletdb.ErasePool(nIndex);
2326 nKeys = max<uint64_t>(GetArg("-keypool", 100), 0);
2328 for (uint64_t i = 0; i < nKeys; i++)
2330 uint64_t nIndex = i+1;
2331 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
2332 setKeyPool.insert(nIndex);
2334 printf("CWallet::NewKeyPool wrote %" PRIu64 " new keys\n", nKeys);
2339 bool CWallet::TopUpKeyPool(unsigned int nSize)
2347 CWalletDB walletdb(strWalletFile);
2350 uint64_t nTargetSize;
2352 nTargetSize = nSize;
2354 nTargetSize = max<uint64_t>(GetArg("-keypool", 100), 0);
2356 while (setKeyPool.size() < (nTargetSize + 1))
2359 if (!setKeyPool.empty())
2360 nEnd = *(--setKeyPool.end()) + 1;
2361 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
2362 throw runtime_error("TopUpKeyPool() : writing generated key failed");
2363 setKeyPool.insert(nEnd);
2364 printf("keypool added key %" PRIu64 ", size=%" PRIszu "\n", nEnd, setKeyPool.size());
2370 void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool)
2373 keypool.vchPubKey = CPubKey();
2380 // Get the oldest key
2381 if(setKeyPool.empty())
2384 CWalletDB walletdb(strWalletFile);
2386 nIndex = *(setKeyPool.begin());
2387 setKeyPool.erase(setKeyPool.begin());
2388 if (!walletdb.ReadPool(nIndex, keypool))
2389 throw runtime_error("ReserveKeyFromKeyPool() : read failed");
2390 if (!HaveKey(keypool.vchPubKey.GetID()))
2391 throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
2392 assert(keypool.vchPubKey.IsValid());
2393 if (fDebug && GetBoolArg("-printkeypool"))
2394 printf("keypool reserve %" PRId64 "\n", nIndex);
2398 int64_t CWallet::AddReserveKey(const CKeyPool& keypool)
2401 LOCK2(cs_main, cs_wallet);
2402 CWalletDB walletdb(strWalletFile);
2404 int64_t nIndex = 1 + *(--setKeyPool.end());
2405 if (!walletdb.WritePool(nIndex, keypool))
2406 throw runtime_error("AddReserveKey() : writing added key failed");
2407 setKeyPool.insert(nIndex);
2413 void CWallet::KeepKey(int64_t nIndex)
2415 // Remove from key pool
2418 CWalletDB walletdb(strWalletFile);
2419 walletdb.ErasePool(nIndex);
2422 printf("keypool keep %" PRId64 "\n", nIndex);
2425 void CWallet::ReturnKey(int64_t nIndex)
2427 // Return to key pool
2430 setKeyPool.insert(nIndex);
2433 printf("keypool return %" PRId64 "\n", nIndex);
2436 bool CWallet::GetKeyFromPool(CPubKey& result, bool fAllowReuse)
2442 ReserveKeyFromKeyPool(nIndex, keypool);
2445 if (fAllowReuse && vchDefaultKey.IsValid())
2447 result = vchDefaultKey;
2450 if (IsLocked()) return false;
2451 result = GenerateNewKey();
2455 result = keypool.vchPubKey;
2460 int64_t CWallet::GetOldestKeyPoolTime()
2464 ReserveKeyFromKeyPool(nIndex, keypool);
2468 return keypool.nTime;
2471 std::map<CTxDestination, int64_t> CWallet::GetAddressBalances()
2473 map<CTxDestination, int64_t> balances;
2477 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2479 CWalletTx *pcoin = &walletEntry.second;
2481 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
2484 if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0)
2487 int nDepth = pcoin->GetDepthInMainChain();
2488 if (nDepth < (pcoin->IsFromMe(MINE_ALL) ? 0 : 1))
2491 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2493 CTxDestination addr;
2494 if (!IsMine(pcoin->vout[i]))
2496 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr))
2499 int64_t n = pcoin->IsSpent(i) ? 0 : pcoin->vout[i].nValue;
2501 if (!balances.count(addr))
2503 balances[addr] += n;
2511 set< set<CTxDestination> > CWallet::GetAddressGroupings()
2513 set< set<CTxDestination> > groupings;
2514 set<CTxDestination> grouping;
2516 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2518 CWalletTx *pcoin = &walletEntry.second;
2520 if (pcoin->vin.size() > 0 && IsMine(pcoin->vin[0]))
2522 // group all input addresses with each other
2523 BOOST_FOREACH(CTxIn txin, pcoin->vin)
2525 CTxDestination address;
2526 if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
2528 grouping.insert(address);
2531 // group change with input addresses
2532 BOOST_FOREACH(CTxOut txout, pcoin->vout)
2533 if (IsChange(txout))
2535 CWalletTx tx = mapWallet[pcoin->vin[0].prevout.hash];
2536 CTxDestination txoutAddr;
2537 if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
2539 grouping.insert(txoutAddr);
2541 groupings.insert(grouping);
2545 // group lone addrs by themselves
2546 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2547 if (IsMine(pcoin->vout[i]))
2549 CTxDestination address;
2550 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address))
2552 grouping.insert(address);
2553 groupings.insert(grouping);
2558 set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
2559 map< CTxDestination, set<CTxDestination>* > setmap; // map addresses to the unique group containing it
2560 BOOST_FOREACH(set<CTxDestination> grouping, groupings)
2562 // make a set of all the groups hit by this new group
2563 set< set<CTxDestination>* > hits;
2564 map< CTxDestination, set<CTxDestination>* >::iterator it;
2565 BOOST_FOREACH(CTxDestination address, grouping)
2566 if ((it = setmap.find(address)) != setmap.end())
2567 hits.insert((*it).second);
2569 // merge all hit groups into a new single group and delete old groups
2570 set<CTxDestination>* merged = new set<CTxDestination>(grouping);
2571 BOOST_FOREACH(set<CTxDestination>* hit, hits)
2573 merged->insert(hit->begin(), hit->end());
2574 uniqueGroupings.erase(hit);
2577 uniqueGroupings.insert(merged);
2580 BOOST_FOREACH(CTxDestination element, *merged)
2581 setmap[element] = merged;
2584 set< set<CTxDestination> > ret;
2585 BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings)
2587 ret.insert(*uniqueGrouping);
2588 delete uniqueGrouping;
2594 // ppcoin: check 'spent' consistency between wallet and txindex
2595 // ppcoin: fix wallet spent state according to txindex
2596 void CWallet::FixSpentCoins(int& nMismatchFound, int64_t& nBalanceInQuestion, bool fCheckOnly)
2599 nBalanceInQuestion = 0;
2602 vector<CWalletTx*> vCoins;
2603 vCoins.reserve(mapWallet.size());
2604 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2605 vCoins.push_back(&(*it).second);
2608 BOOST_FOREACH(CWalletTx* pcoin, vCoins)
2610 // Find the corresponding transaction index
2612 if (!txdb.ReadTxIndex(pcoin->GetHash(), txindex))
2614 for (unsigned int n=0; n < pcoin->vout.size(); n++)
2616 if (IsMine(pcoin->vout[n]) && pcoin->IsSpent(n) && (txindex.vSpent.size() <= n || txindex.vSpent[n].IsNull()))
2618 printf("FixSpentCoins found lost coin %sppc %s[%u], %s\n",
2619 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2621 nBalanceInQuestion += pcoin->vout[n].nValue;
2624 pcoin->MarkUnspent(n);
2625 pcoin->WriteToDisk();
2628 else if (IsMine(pcoin->vout[n]) && !pcoin->IsSpent(n) && (txindex.vSpent.size() > n && !txindex.vSpent[n].IsNull()))
2630 printf("FixSpentCoins found spent coin %sppc %s[%u], %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->MarkSpent(n);
2637 pcoin->WriteToDisk();
2643 if(IsMine((CTransaction)*pcoin) && (pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetDepthInMainChain() == 0)
2645 printf("FixSpentCoins %s tx %s\n", fCheckOnly ? "found" : "removed", pcoin->GetHash().ToString().c_str());
2648 EraseFromWallet(pcoin->GetHash());
2654 // ppcoin: disable transaction (only for coinstake)
2655 void CWallet::DisableTransaction(const CTransaction &tx)
2657 if (!tx.IsCoinStake() || !IsFromMe(tx))
2658 return; // only disconnecting coinstake requires marking input unspent
2661 BOOST_FOREACH(const CTxIn& txin, tx.vin)
2663 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
2664 if (mi != mapWallet.end())
2666 CWalletTx& prev = (*mi).second;
2667 if (txin.prevout.n < prev.vout.size() && IsMine(prev.vout[txin.prevout.n]))
2669 prev.MarkUnspent(txin.prevout.n);
2676 CPubKey CReserveKey::GetReservedKey()
2681 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
2683 vchPubKey = keypool.vchPubKey;
2686 printf("CReserveKey::GetReservedKey(): Warning: Using default key instead of a new key, top up your keypool!");
2687 vchPubKey = pwallet->vchDefaultKey;
2690 assert(vchPubKey.IsValid());
2694 void CReserveKey::KeepKey()
2697 pwallet->KeepKey(nIndex);
2699 vchPubKey = CPubKey();
2702 void CReserveKey::ReturnKey()
2705 pwallet->ReturnKey(nIndex);
2707 vchPubKey = CPubKey();
2710 void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
2714 CWalletDB walletdb(strWalletFile);
2716 LOCK2(cs_main, cs_wallet);
2717 BOOST_FOREACH(const int64_t& id, setKeyPool)
2720 if (!walletdb.ReadPool(id, keypool))
2721 throw runtime_error("GetAllReserveKeyHashes() : read failed");
2722 assert(keypool.vchPubKey.IsValid());
2723 CKeyID keyID = keypool.vchPubKey.GetID();
2724 if (!HaveKey(keyID))
2725 throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
2726 setAddress.insert(keyID);
2730 void CWallet::UpdatedTransaction(const uint256 &hashTx)
2734 // Only notify UI if this transaction is in this wallet
2735 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
2736 if (mi != mapWallet.end())
2738 NotifyTransactionChanged(this, hashTx, CT_UPDATED);
2739 vMintingWalletUpdated.push_back(hashTx);
2744 void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const {
2745 mapKeyBirth.clear();
2747 // get birth times for keys with metadata
2748 for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++)
2749 if (it->second.nCreateTime)
2750 mapKeyBirth[it->first] = it->second.nCreateTime;
2752 // map in which we'll infer heights of other keys
2753 CBlockIndex *pindexMax = FindBlockByHeight(std::max(0, nBestHeight - 144)); // the tip can be reorganised; use a 144-block safety margin
2754 std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
2755 std::set<CKeyID> setKeys;
2757 BOOST_FOREACH(const CKeyID &keyid, setKeys) {
2758 if (mapKeyBirth.count(keyid) == 0)
2759 mapKeyFirstBlock[keyid] = pindexMax;
2763 // if there are no such keys, we're done
2764 if (mapKeyFirstBlock.empty())
2767 // find first block that affects those keys, if there are any left
2768 std::vector<CKeyID> vAffected;
2769 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
2770 // iterate over all wallet transactions...
2771 const CWalletTx &wtx = (*it).second;
2772 std::map<uint256, CBlockIndex*>::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
2773 if (blit != mapBlockIndex.end() && blit->second->IsInMainChain()) {
2774 // ... which are already in a block
2775 int nHeight = blit->second->nHeight;
2776 BOOST_FOREACH(const CTxOut &txout, wtx.vout) {
2777 // iterate over all their outputs
2778 ::ExtractAffectedKeys(*this, txout.scriptPubKey, vAffected);
2779 BOOST_FOREACH(const CKeyID &keyid, vAffected) {
2780 // ... and all their affected keys
2781 std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
2782 if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
2783 rit->second = blit->second;
2790 // Extract block timestamps for those keys
2791 for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
2792 mapKeyBirth[it->first] = it->second->nTime - 7200; // block times can be 2h off
2795 void CWallet::ClearOrphans()
2797 list<uint256> orphans;
2800 for(map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2802 const CWalletTx *wtx = &(*it).second;
2803 if((wtx->IsCoinBase() || wtx->IsCoinStake()) && !wtx->IsInMainChain())
2805 orphans.push_back(wtx->GetHash());
2809 for(list<uint256>::const_iterator it = orphans.begin(); it != orphans.end(); ++it)
2810 EraseFromWallet(*it);
2813 bool CWallet::ExtractAddress(const CScript& scriptPubKey, std::string& addressRet)
2815 vector<valtype> vSolutions;
2816 txnouttype whichType;
2817 if (!Solver(scriptPubKey, whichType, vSolutions))
2820 if (whichType == TX_PUBKEY)
2822 addressRet = CBitcoinAddress(CPubKey(vSolutions[0]).GetID()).ToString();
2825 if (whichType == TX_PUBKEY_DROP)
2828 CMalleableKeyView view;
2829 if (!CheckOwnership(CPubKey(vSolutions[0]), CPubKey(vSolutions[1]), view))
2832 addressRet = view.GetMalleablePubKey().ToString();
2835 else if (whichType == TX_PUBKEYHASH)
2837 addressRet = CBitcoinAddress(CKeyID(uint160(vSolutions[0]))).ToString();
2840 else if (whichType == TX_SCRIPTHASH)
2842 addressRet = CBitcoinAddress(CScriptID(uint160(vSolutions[0]))).ToString();
2845 // Multisig txns have more than one address...