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>
17 extern int nStakeMaxAge;
19 bool fCoinsDataActual;
21 //////////////////////////////////////////////////////////////////////////////
26 struct CompareValueOnly
28 bool operator()(const pair<int64, pair<const CWalletTx*, unsigned int> >& t1,
29 const pair<int64, 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 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 bool CWallet::AddKey(const CKey& key)
62 CPubKey pubkey = key.GetPubKey();
64 if (!CCryptoKeyStore::AddKey(key))
69 return CWalletDB(strWalletFile).WriteKey(pubkey, key.GetPrivKey(), mapKeyMetadata[pubkey.GetID()]);
73 bool CWallet::AddCryptedKey(const CPubKey &vchPubKey, const vector<unsigned char> &vchCryptedSecret)
75 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
81 if (pwalletdbEncryption)
82 return pwalletdbEncryption->WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]);
84 return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]);
89 bool CWallet::LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &meta)
91 if (meta.nCreateTime && (!nTimeFirstKey || meta.nCreateTime < nTimeFirstKey))
92 nTimeFirstKey = meta.nCreateTime;
94 mapKeyMetadata[pubkey.GetID()] = meta;
98 bool CWallet::AddCScript(const CScript& redeemScript)
100 if (!CCryptoKeyStore::AddCScript(redeemScript))
104 return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript);
107 bool CWallet::AddWatchOnly(const CScript &dest)
109 if (!CCryptoKeyStore::AddWatchOnly(dest))
111 nTimeFirstKey = 1; // No birthday information for watch-only keys.
114 return CWalletDB(strWalletFile).WriteWatchOnly(dest);
117 bool CWallet::LoadWatchOnly(const CScript &dest)
119 return CCryptoKeyStore::AddWatchOnly(dest);
122 // ppcoin: optional setting to unlock wallet for block minting only;
123 // serves to disable the trivial sendmoney when OS account compromised
124 bool fWalletUnlockMintOnly = false;
126 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
132 CKeyingMaterial vMasterKey;
136 BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
138 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
140 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
142 if (CCryptoKeyStore::Unlock(vMasterKey))
149 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
151 bool fWasLocked = IsLocked();
158 CKeyingMaterial vMasterKey;
159 BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
161 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
163 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
165 if (CCryptoKeyStore::Unlock(vMasterKey))
167 int64 nStartTime = GetTimeMillis();
168 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
169 pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
171 nStartTime = GetTimeMillis();
172 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
173 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
175 if (pMasterKey.second.nDeriveIterations < 25000)
176 pMasterKey.second.nDeriveIterations = 25000;
178 printf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
180 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
182 if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
184 CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
195 void CWallet::SetBestChain(const CBlockLocator& loc)
197 CWalletDB walletdb(strWalletFile);
198 walletdb.WriteBestBlock(loc);
201 // This class implements an addrIncoming entry that causes pre-0.4
202 // clients to crash on startup if reading a private-key-encrypted wallet.
203 class CCorruptAddress
208 if (nType & SER_DISK)
213 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
215 if (nWalletVersion >= nVersion)
218 // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
219 if (fExplicit && nVersion > nWalletMaxVersion)
220 nVersion = FEATURE_LATEST;
222 nWalletVersion = nVersion;
224 if (nVersion > nWalletMaxVersion)
225 nWalletMaxVersion = nVersion;
229 CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile);
230 if (nWalletVersion >= 40000)
232 // Versions prior to 0.4.0 did not support the "minversion" record.
233 // Use a CCorruptAddress to make them crash instead.
234 CCorruptAddress corruptAddress;
235 pwalletdb->WriteSetting("addrIncoming", corruptAddress);
237 if (nWalletVersion > 40000)
238 pwalletdb->WriteMinVersion(nWalletVersion);
246 bool CWallet::SetMaxVersion(int nVersion)
248 // cannot downgrade below current version
249 if (nWalletVersion > nVersion)
252 nWalletMaxVersion = nVersion;
257 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
262 CKeyingMaterial vMasterKey;
263 RandAddSeedPerfmon();
265 vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
266 RAND_bytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
268 CMasterKey kMasterKey(nDerivationMethodIndex);
270 RandAddSeedPerfmon();
271 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
272 RAND_bytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
275 int64 nStartTime = GetTimeMillis();
276 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
277 kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
279 nStartTime = GetTimeMillis();
280 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
281 kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
283 if (kMasterKey.nDeriveIterations < 25000)
284 kMasterKey.nDeriveIterations = 25000;
286 printf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
288 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
290 if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
295 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
298 pwalletdbEncryption = new CWalletDB(strWalletFile);
299 if (!pwalletdbEncryption->TxnBegin())
301 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
304 if (!EncryptKeys(vMasterKey))
307 pwalletdbEncryption->TxnAbort();
308 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.
311 // Encryption was introduced in version 0.4.0
312 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
316 if (!pwalletdbEncryption->TxnCommit())
317 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.
319 delete pwalletdbEncryption;
320 pwalletdbEncryption = NULL;
324 Unlock(strWalletPassphrase);
328 // Need to completely rewrite the wallet file; if we don't, bdb might keep
329 // bits of the unencrypted private key in slack space in the database file.
330 CDB::Rewrite(strWalletFile);
333 NotifyStatusChanged(this);
338 int64 CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
340 int64 nRet = nOrderPosNext++;
342 pwalletdb->WriteOrderPosNext(nOrderPosNext);
344 CWalletDB(strWalletFile).WriteOrderPosNext(nOrderPosNext);
349 CWallet::TxItems CWallet::OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount)
351 CWalletDB walletdb(strWalletFile);
353 // First: get all CWalletTx and CAccountingEntry into a sorted-by-order multimap.
356 // Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry
357 // would make this much faster for applications that do this a lot.
358 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
360 CWalletTx* wtx = &((*it).second);
361 txOrdered.insert(make_pair(wtx->nOrderPos, TxPair(wtx, (CAccountingEntry*)0)));
364 walletdb.ListAccountCreditDebit(strAccount, acentries);
365 BOOST_FOREACH(CAccountingEntry& entry, acentries)
367 txOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
373 void CWallet::WalletUpdateSpent(const CTransaction &tx, bool fBlock)
375 // Anytime a signature is successfully verified, it's proof the outpoint is spent.
376 // Update the wallet spent flag if it doesn't know due to wallet.dat being
377 // restored from backup or the user making copies of wallet.dat.
380 BOOST_FOREACH(const CTxIn& txin, tx.vin)
382 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
383 if (mi != mapWallet.end())
385 CWalletTx& wtx = (*mi).second;
386 if (txin.prevout.n >= wtx.vout.size())
387 printf("WalletUpdateSpent: bad wtx %s\n", wtx.GetHash().ToString().c_str());
388 else if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n]))
390 printf("WalletUpdateSpent found spent coin %snvc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
391 wtx.MarkSpent(txin.prevout.n);
393 NotifyTransactionChanged(this, txin.prevout.hash, CT_UPDATED);
400 uint256 hash = tx.GetHash();
401 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hash);
402 CWalletTx& wtx = (*mi).second;
404 BOOST_FOREACH(const CTxOut& txout, tx.vout)
408 wtx.MarkUnspent(&txout - &tx.vout[0]);
410 NotifyTransactionChanged(this, hash, CT_UPDATED);
418 void CWallet::MarkDirty()
422 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
423 item.second.MarkDirty();
427 bool CWallet::AddToWallet(const CWalletTx& wtxIn)
429 uint256 hash = wtxIn.GetHash();
432 // Inserts only if not already there, returns tx inserted or tx found
433 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
434 CWalletTx& wtx = (*ret.first).second;
435 wtx.BindWallet(this);
436 bool fInsertedNew = ret.second;
439 wtx.nTimeReceived = GetAdjustedTime();
440 wtx.nOrderPos = IncOrderPosNext();
442 wtx.nTimeSmart = wtx.nTimeReceived;
443 if (wtxIn.hashBlock != 0)
445 if (mapBlockIndex.count(wtxIn.hashBlock))
447 unsigned int latestNow = wtx.nTimeReceived;
448 unsigned int latestEntry = 0;
450 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
451 int64 latestTolerated = latestNow + 300;
452 std::list<CAccountingEntry> acentries;
453 TxItems txOrdered = OrderedTxItems(acentries);
454 for (TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
456 CWalletTx *const pwtx = (*it).second.first;
459 CAccountingEntry *const pacentry = (*it).second.second;
463 nSmartTime = pwtx->nTimeSmart;
465 nSmartTime = pwtx->nTimeReceived;
468 nSmartTime = pacentry->nTime;
469 if (nSmartTime <= latestTolerated)
471 latestEntry = nSmartTime;
472 if (nSmartTime > latestNow)
473 latestNow = nSmartTime;
479 unsigned int& blocktime = mapBlockIndex[wtxIn.hashBlock]->nTime;
480 wtx.nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
483 printf("AddToWallet() : found %s in block %s not in index\n",
484 wtxIn.GetHash().ToString().substr(0,10).c_str(),
485 wtxIn.hashBlock.ToString().c_str());
489 bool fUpdated = false;
493 if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
495 wtx.hashBlock = wtxIn.hashBlock;
498 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
500 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
501 wtx.nIndex = wtxIn.nIndex;
504 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
506 wtx.fFromMe = wtxIn.fFromMe;
509 fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);
513 printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
516 if (fInsertedNew || fUpdated)
517 if (!wtx.WriteToDisk())
520 // If default receiving address gets used, replace it with a new one
521 CScript scriptDefaultKey;
522 scriptDefaultKey.SetDestination(vchDefaultKey.GetID());
523 BOOST_FOREACH(const CTxOut& txout, wtx.vout)
525 if (txout.scriptPubKey == scriptDefaultKey)
527 CPubKey newDefaultKey;
528 if (GetKeyFromPool(newDefaultKey, false))
530 SetDefaultKey(newDefaultKey);
531 SetAddressBookName(vchDefaultKey.GetID(), "");
536 // since AddToWallet is called directly for self-originating transactions, check for consumption of own coins
537 WalletUpdateSpent(wtx, (wtxIn.hashBlock != 0));
539 // Notify UI of new or updated transaction
540 NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
542 // notify an external script when a wallet transaction comes in or is updated
543 std::string strCmd = GetArg("-walletnotify", "");
545 if ( !strCmd.empty())
547 boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
548 boost::thread t(runCommand, strCmd); // thread runs free
555 // Add a transaction to the wallet, or update it.
556 // pblock is optional, but should be provided if the transaction is known to be in a block.
557 // If fUpdate is true, existing transactions will be updated.
558 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fFindBlock)
560 uint256 hash = tx.GetHash();
563 bool fExisted = mapWallet.count(hash);
564 if (fExisted && !fUpdate) return false;
565 if (fExisted || IsMine(tx) || IsFromMe(tx))
567 CWalletTx wtx(this,tx);
568 // Get merkle branch if transaction was found in a block
570 wtx.SetMerkleBranch(pblock);
571 return AddToWallet(wtx);
574 WalletUpdateSpent(tx);
579 bool CWallet::EraseFromWallet(uint256 hash)
585 if (mapWallet.erase(hash))
586 CWalletDB(strWalletFile).EraseTx(hash);
592 isminetype CWallet::IsMine(const CTxIn &txin) const
596 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
597 if (mi != mapWallet.end())
599 const CWalletTx& prev = (*mi).second;
600 if (txin.prevout.n < prev.vout.size())
601 return IsMine(prev.vout[txin.prevout.n]);
607 int64 CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
611 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
612 if (mi != mapWallet.end())
614 const CWalletTx& prev = (*mi).second;
615 if (txin.prevout.n < prev.vout.size())
616 if (IsMine(prev.vout[txin.prevout.n]) & filter)
617 return prev.vout[txin.prevout.n].nValue;
623 bool CWallet::IsChange(const CTxOut& txout) const
625 // TODO: fix handling of 'change' outputs. The assumption is that any
626 // payment to a script that is ours, but isn't in the address book
627 // is change. That assumption is likely to break when we implement multisignature
628 // wallets that return change back into a multi-signature-protected address;
629 // a better way of identifying which outputs are 'the send' and which are
630 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
631 // which output, if any, was change).
632 if (::IsMine(*this, txout.scriptPubKey))
634 CTxDestination address;
635 if (!ExtractDestination(txout.scriptPubKey, address))
639 if (!mapAddressBook.count(address))
645 int64 CWalletTx::GetTxTime() const
647 int64 n = nTimeSmart;
648 return n ? n : nTimeReceived;
651 int CWalletTx::GetRequestCount() const
653 // Returns -1 if it wasn't being tracked
656 LOCK(pwallet->cs_wallet);
657 if (IsCoinBase() || IsCoinStake())
662 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
663 if (mi != pwallet->mapRequestCount.end())
664 nRequests = (*mi).second;
669 // Did anyone request this transaction?
670 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
671 if (mi != pwallet->mapRequestCount.end())
673 nRequests = (*mi).second;
675 // How about the block it's in?
676 if (nRequests == 0 && hashBlock != 0)
678 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
679 if (mi != pwallet->mapRequestCount.end())
680 nRequests = (*mi).second;
682 nRequests = 1; // If it's in someone else's block it must have got out
690 void CWalletTx::GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, list<pair<CTxDestination, int64> >& listReceived,
691 list<pair<CTxDestination, int64> >& listSent, int64& nFee, string& strSentAccount, const isminefilter& filter) const
693 nGeneratedImmature = nGeneratedMature = nFee = 0;
694 listReceived.clear();
696 strSentAccount = strFromAccount;
698 if (IsCoinBase() || IsCoinStake())
700 if (GetBlocksToMaturity() > 0)
701 nGeneratedImmature = pwallet->GetCredit(*this, filter);
703 nGeneratedMature = GetCredit(filter);
708 int64 nDebit = GetDebit(filter);
709 if (nDebit > 0) // debit>0 means we signed/sent this transaction
711 int64 nValueOut = GetValueOut();
712 nFee = nDebit - nValueOut;
716 BOOST_FOREACH(const CTxOut& txout, vout)
718 isminetype fIsMine = pwallet->IsMine(txout);
719 // Only need to handle txouts if AT LEAST one of these is true:
720 // 1) they debit from us (sent)
721 // 2) the output is to us (received)
724 // Don't report 'change' txouts
725 if (pwallet->IsChange(txout))
728 else if (!(fIsMine & filter))
731 // In either case, we need to get the destination address
732 CTxDestination address;
733 if (!ExtractDestination(txout.scriptPubKey, address))
735 printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
736 this->GetHash().ToString().c_str());
737 address = CNoDestination();
740 // If we are debited by the transaction, add the output as a "sent" entry
742 listSent.push_back(make_pair(address, txout.nValue));
744 // If we are receiving the output, add it as a "received" entry
745 if (fIsMine & filter)
746 listReceived.push_back(make_pair(address, txout.nValue));
751 void CWalletTx::GetAccountAmounts(const string& strAccount, int64& nGenerated, int64& nReceived,
752 int64& nSent, int64& nFee, const isminefilter& filter) const
754 nGenerated = nReceived = nSent = nFee = 0;
756 int64 allGeneratedImmature, allGeneratedMature, allFee;
757 allGeneratedImmature = allGeneratedMature = allFee = 0;
758 string strSentAccount;
759 list<pair<CTxDestination, int64> > listReceived;
760 list<pair<CTxDestination, int64> > listSent;
761 GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount, filter);
763 if (strAccount == "")
764 nGenerated = allGeneratedMature;
765 if (strAccount == strSentAccount)
767 BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& s, listSent)
772 LOCK(pwallet->cs_wallet);
773 BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listReceived)
775 if (pwallet->mapAddressBook.count(r.first))
777 map<CTxDestination, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);
778 if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)
779 nReceived += r.second;
781 else if (strAccount.empty())
783 nReceived += r.second;
789 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
793 const int COPY_DEPTH = 3;
794 if (SetMerkleBranch() < COPY_DEPTH)
796 vector<uint256> vWorkQueue;
797 BOOST_FOREACH(const CTxIn& txin, vin)
798 vWorkQueue.push_back(txin.prevout.hash);
800 // This critsect is OK because txdb is already open
802 LOCK(pwallet->cs_wallet);
803 map<uint256, const CMerkleTx*> mapWalletPrev;
804 set<uint256> setAlreadyDone;
805 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
807 uint256 hash = vWorkQueue[i];
808 if (setAlreadyDone.count(hash))
810 setAlreadyDone.insert(hash);
813 map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
814 if (mi != pwallet->mapWallet.end())
817 BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev)
818 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
820 else if (mapWalletPrev.count(hash))
822 tx = *mapWalletPrev[hash];
824 else if (!fClient && txdb.ReadDiskTx(hash, tx))
830 printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
834 int nDepth = tx.SetMerkleBranch();
835 vtxPrev.push_back(tx);
837 if (nDepth < COPY_DEPTH)
839 BOOST_FOREACH(const CTxIn& txin, tx.vin)
840 vWorkQueue.push_back(txin.prevout.hash);
846 reverse(vtxPrev.begin(), vtxPrev.end());
849 bool CWalletTx::WriteToDisk()
851 return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
854 // Scan the block chain (starting in pindexStart) for transactions
855 // from or to us. If fUpdate is true, found transactions that already
856 // exist in the wallet will be updated.
857 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
861 CBlockIndex* pindex = pindexStart;
867 block.ReadFromDisk(pindex, true);
868 BOOST_FOREACH(CTransaction& tx, block.vtx)
870 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
873 pindex = pindex->pnext;
879 int CWallet::ScanForWalletTransaction(const uint256& hashTx)
882 tx.ReadFromDisk(COutPoint(hashTx, 0));
883 if (AddToWalletIfInvolvingMe(tx, NULL, true, true))
888 void CWallet::ReacceptWalletTransactions()
896 vector<CDiskTxPos> vMissingTx;
897 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
899 CWalletTx& wtx = item.second;
900 if ((wtx.IsCoinBase() && wtx.IsSpent(0)) || (wtx.IsCoinStake() && wtx.IsSpent(1)))
904 bool fUpdated = false;
905 if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
907 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
908 if (txindex.vSpent.size() != wtx.vout.size())
910 printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %"PRIszu" != wtx.vout.size() %"PRIszu"\n", txindex.vSpent.size(), wtx.vout.size());
913 for (unsigned int i = 0; i < txindex.vSpent.size(); i++)
917 if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i]))
921 vMissingTx.push_back(txindex.vSpent[i]);
926 printf("ReacceptWalletTransactions found spent coin %snvc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
933 // Re-accept any txes of ours that aren't already in a block
934 if (!(wtx.IsCoinBase() || wtx.IsCoinStake()))
935 wtx.AcceptWalletTransaction(txdb, false);
938 if (!vMissingTx.empty())
940 // TODO: optimize this to scan just part of the block chain?
941 if (ScanForWalletTransactions(pindexGenesisBlock))
942 fRepeat = true; // Found missing transactions: re-do re-accept.
947 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
949 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
951 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
953 uint256 hash = tx.GetHash();
954 if (!txdb.ContainsTx(hash))
955 RelayTransaction((CTransaction)tx, hash);
958 if (!(IsCoinBase() || IsCoinStake()))
960 uint256 hash = GetHash();
961 if (!txdb.ContainsTx(hash))
963 printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
964 RelayTransaction((CTransaction)*this, hash);
969 void CWalletTx::RelayWalletTransaction()
972 RelayWalletTransaction(txdb);
975 void CWallet::ResendWalletTransactions()
977 // Do this infrequently and randomly to avoid giving away
978 // that these are our transactions.
979 static int64 nNextTime;
980 if (GetTime() < nNextTime)
982 bool fFirst = (nNextTime == 0);
983 nNextTime = GetTime() + GetRand(30 * 60);
987 // Only do it if there's been a new block since last time
988 static int64 nLastTime;
989 if (nTimeBestReceived < nLastTime)
991 nLastTime = GetTime();
993 // Rebroadcast any of our txes that aren't in a block yet
994 printf("ResendWalletTransactions()\n");
998 // Sort them in chronological order
999 multimap<unsigned int, CWalletTx*> mapSorted;
1000 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1002 CWalletTx& wtx = item.second;
1003 // Don't rebroadcast until it's had plenty of time that
1004 // it should have gotten in already by now.
1005 if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
1006 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
1008 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
1010 CWalletTx& wtx = *item.second;
1011 if (wtx.CheckTransaction())
1012 wtx.RelayWalletTransaction(txdb);
1014 printf("ResendWalletTransactions() : CheckTransaction failed for transaction %s\n", wtx.GetHash().ToString().c_str());
1024 //////////////////////////////////////////////////////////////////////////////
1030 int64 CWallet::GetBalance() const
1035 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1037 const CWalletTx* pcoin = &(*it).second;
1038 if (pcoin->IsTrusted())
1039 nTotal += pcoin->GetAvailableCredit();
1046 int64 CWallet::GetWatchOnlyBalance() const
1051 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1053 const CWalletTx* pcoin = &(*it).second;
1054 if (pcoin->IsTrusted())
1055 nTotal += pcoin->GetAvailableWatchCredit();
1062 int64 CWallet::GetUnconfirmedBalance() const
1067 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1069 const CWalletTx* pcoin = &(*it).second;
1070 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
1071 nTotal += pcoin->GetAvailableCredit();
1077 int64 CWallet::GetUnconfirmedWatchOnlyBalance() const
1082 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1084 const CWalletTx* pcoin = &(*it).second;
1085 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
1086 nTotal += pcoin->GetAvailableWatchCredit();
1092 int64 CWallet::GetImmatureBalance() const
1097 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1099 const CWalletTx* pcoin = &(*it).second;
1100 nTotal += pcoin->GetImmatureCredit();
1106 int64 CWallet::GetImmatureWatchOnlyBalance() const
1111 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1113 const CWalletTx* pcoin = &(*it).second;
1114 nTotal += pcoin->GetImmatureWatchOnlyCredit();
1120 // populate vCoins with vector of spendable COutputs
1121 void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl) const
1127 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1129 const CWalletTx* pcoin = &(*it).second;
1131 if (!pcoin->IsFinal())
1134 if (fOnlyConfirmed && !pcoin->IsTrusted())
1137 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
1140 if(pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0)
1143 for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
1144 isminetype mine = IsMine(pcoin->vout[i]);
1145 if (!(pcoin->IsSpent(i)) && mine != MINE_NO &&
1146 pcoin->vout[i].nValue >= nMinimumInputValue &&
1147 (!coinControl || !coinControl->HasSelected() || coinControl->IsSelected((*it).first, i)))
1149 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain(), mine == MINE_SPENDABLE));
1156 void CWallet::AvailableCoinsMinConf(vector<COutput>& vCoins, int nConf) const
1162 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1164 const CWalletTx* pcoin = &(*it).second;
1166 if (!pcoin->IsFinal())
1169 if(pcoin->GetDepthInMainChain() < nConf)
1172 for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
1173 isminetype mine = IsMine(pcoin->vout[i]);
1175 if (!(pcoin->IsSpent(i)) && mine != MINE_NO && pcoin->vout[i].nValue >= nMinimumInputValue)
1176 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain(), mine == MINE_SPENDABLE));
1182 static void ApproximateBestSubset(vector<pair<int64, pair<const CWalletTx*,unsigned int> > >vValue, int64 nTotalLower, int64 nTargetValue,
1183 vector<char>& vfBest, int64& nBest, int iterations = 1000)
1185 vector<char> vfIncluded;
1187 vfBest.assign(vValue.size(), true);
1188 nBest = nTotalLower;
1190 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
1192 vfIncluded.assign(vValue.size(), false);
1194 bool fReachedTarget = false;
1195 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
1197 for (unsigned int i = 0; i < vValue.size(); i++)
1199 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
1201 nTotal += vValue[i].first;
1202 vfIncluded[i] = true;
1203 if (nTotal >= nTargetValue)
1205 fReachedTarget = true;
1209 vfBest = vfIncluded;
1211 nTotal -= vValue[i].first;
1212 vfIncluded[i] = false;
1220 int64 CWallet::GetStake() const
1224 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1226 const CWalletTx* pcoin = &(*it).second;
1227 if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1228 nTotal += CWallet::GetCredit(*pcoin, MINE_ALL);
1233 int64 CWallet::GetWatchOnlyStake() const
1237 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1239 const CWalletTx* pcoin = &(*it).second;
1240 if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1241 nTotal += CWallet::GetCredit(*pcoin, MINE_WATCH_ONLY);
1246 int64 CWallet::GetNewMint() const
1250 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1252 const CWalletTx* pcoin = &(*it).second;
1253 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1254 nTotal += CWallet::GetCredit(*pcoin, MINE_ALL);
1259 int64 CWallet::GetWatchOnlyNewMint() const
1263 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1265 const CWalletTx* pcoin = &(*it).second;
1266 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1267 nTotal += CWallet::GetCredit(*pcoin, MINE_WATCH_ONLY);
1272 bool CWallet::SelectCoinsMinConf(int64 nTargetValue, unsigned int nSpendTime, int nConfMine, int nConfTheirs, vector<COutput> vCoins, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
1274 setCoinsRet.clear();
1277 // List of values less than target
1278 pair<int64, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
1279 coinLowestLarger.first = std::numeric_limits<int64>::max();
1280 coinLowestLarger.second.first = NULL;
1281 vector<pair<int64, pair<const CWalletTx*,unsigned int> > > vValue;
1282 int64 nTotalLower = 0;
1284 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
1286 BOOST_FOREACH(const COutput &output, vCoins)
1288 if (!output.fSpendable)
1291 const CWalletTx *pcoin = output.tx;
1293 if (output.nDepth < (pcoin->IsFromMe(MINE_ALL) ? nConfMine : nConfTheirs))
1298 // Follow the timestamp rules
1299 if (pcoin->nTime > nSpendTime)
1302 int64 n = pcoin->vout[i].nValue;
1304 pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1306 if (n == nTargetValue)
1308 setCoinsRet.insert(coin.second);
1309 nValueRet += coin.first;
1312 else if (n < nTargetValue + CENT)
1314 vValue.push_back(coin);
1317 else if (n < coinLowestLarger.first)
1319 coinLowestLarger = coin;
1323 if (nTotalLower == nTargetValue)
1325 for (unsigned int i = 0; i < vValue.size(); ++i)
1327 setCoinsRet.insert(vValue[i].second);
1328 nValueRet += vValue[i].first;
1333 if (nTotalLower < nTargetValue)
1335 if (coinLowestLarger.second.first == NULL)
1337 setCoinsRet.insert(coinLowestLarger.second);
1338 nValueRet += coinLowestLarger.first;
1342 // Solve subset sum by stochastic approximation
1343 sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
1344 vector<char> vfBest;
1347 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);
1348 if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT)
1349 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000);
1351 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
1352 // or the next bigger coin is closer), return the bigger coin
1353 if (coinLowestLarger.second.first &&
1354 ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest))
1356 setCoinsRet.insert(coinLowestLarger.second);
1357 nValueRet += coinLowestLarger.first;
1360 for (unsigned int i = 0; i < vValue.size(); i++)
1363 setCoinsRet.insert(vValue[i].second);
1364 nValueRet += vValue[i].first;
1367 if (fDebug && GetBoolArg("-printpriority"))
1370 printf("SelectCoins() best subset: ");
1371 for (unsigned int i = 0; i < vValue.size(); i++)
1373 printf("%s ", FormatMoney(vValue[i].first).c_str());
1374 printf("total %s\n", FormatMoney(nBest).c_str());
1381 bool CWallet::SelectCoins(int64 nTargetValue, unsigned int nSpendTime, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet, const CCoinControl* coinControl) const
1383 vector<COutput> vCoins;
1384 AvailableCoins(vCoins, true, coinControl);
1386 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
1387 if (coinControl && coinControl->HasSelected())
1389 BOOST_FOREACH(const COutput& out, vCoins)
1393 nValueRet += out.tx->vout[out.i].nValue;
1394 setCoinsRet.insert(make_pair(out.tx, out.i));
1396 return (nValueRet >= nTargetValue);
1399 return (SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 6, vCoins, setCoinsRet, nValueRet) ||
1400 SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 1, vCoins, setCoinsRet, nValueRet) ||
1401 SelectCoinsMinConf(nTargetValue, nSpendTime, 0, 1, vCoins, setCoinsRet, nValueRet));
1404 // Select some coins without random shuffle or best subset approximation
1405 bool CWallet::SelectCoinsSimple(int64 nTargetValue, unsigned int nSpendTime, int nMinConf, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
1407 vector<COutput> vCoins;
1408 AvailableCoinsMinConf(vCoins, nMinConf);
1410 setCoinsRet.clear();
1413 BOOST_FOREACH(COutput output, vCoins)
1415 if(!output.fSpendable)
1417 const CWalletTx *pcoin = output.tx;
1420 // Ignore immature coins
1421 if (pcoin->GetBlocksToMaturity() > 0)
1424 // Stop if we've chosen enough inputs
1425 if (nValueRet >= nTargetValue)
1428 // Follow the timestamp rules
1429 if (pcoin->nTime > nSpendTime)
1432 int64 n = pcoin->vout[i].nValue;
1434 pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1436 if (n >= nTargetValue)
1438 // If input value is greater or equal to target then simply insert
1439 // it into the current subset and exit
1440 setCoinsRet.insert(coin.second);
1441 nValueRet += coin.first;
1444 else if (n < nTargetValue + CENT)
1446 setCoinsRet.insert(coin.second);
1447 nValueRet += coin.first;
1454 bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, const CCoinControl* coinControl)
1457 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1463 if (vecSend.empty() || nValue < 0)
1466 wtxNew.BindWallet(this);
1469 LOCK2(cs_main, cs_wallet);
1470 // txdb must be opened before the mapWallet lock
1473 nFeeRet = nTransactionFee;
1477 wtxNew.vout.clear();
1478 wtxNew.fFromMe = true;
1480 int64 nTotalValue = nValue + nFeeRet;
1481 double dPriority = 0;
1482 // vouts to the payees
1483 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1484 wtxNew.vout.push_back(CTxOut(s.second, s.first));
1486 // Choose coins to use
1487 set<pair<const CWalletTx*,unsigned int> > setCoins;
1489 if (!SelectCoins(nTotalValue, wtxNew.nTime, setCoins, nValueIn, coinControl))
1491 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1493 int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
1494 dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
1497 int64 nChange = nValueIn - nValue - nFeeRet;
1498 // if sub-cent change is required, the fee must be raised to at least MIN_TX_FEE
1499 // or until nChange becomes zero
1500 // NOTE: this depends on the exact behaviour of GetMinFee
1501 if (wtxNew.nTime < FEE_SWITCH_TIME && !fTestNet)
1503 if (nFeeRet < MIN_TX_FEE && nChange > 0 && nChange < CENT)
1505 int64 nMoveToFee = min(nChange, MIN_TX_FEE - nFeeRet);
1506 nChange -= nMoveToFee;
1507 nFeeRet += nMoveToFee;
1510 // sub-cent change is moved to fee
1511 if (nChange > 0 && nChange < CENT)
1520 // Fill a vout to ourself
1521 // TODO: pass in scriptChange instead of reservekey so
1522 // change transaction isn't always pay-to-bitcoin-address
1523 CScript scriptChange;
1525 // coin control: send change to custom address
1526 if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange))
1527 scriptChange.SetDestination(coinControl->destChange);
1529 // no coin control: send change to newly generated address
1532 // Note: We use a new key here to keep it from being obvious which side is the change.
1533 // The drawback is that by not reusing a previous key, the change may be lost if a
1534 // backup is restored, if the backup doesn't have the new private key for the change.
1535 // If we reused the old key, it would be possible to add code to look for and
1536 // rediscover unknown transactions that were written with keys of ours to recover
1537 // post-backup change.
1539 // Reserve a new key pair from key pool
1540 CPubKey vchPubKey = reservekey.GetReservedKey();
1542 scriptChange.SetDestination(vchPubKey.GetID());
1545 // Insert change txn at random position:
1546 vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
1547 wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
1550 reservekey.ReturnKey();
1553 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1554 wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
1558 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1559 if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
1563 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
1564 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1566 dPriority /= nBytes;
1568 // Check that enough fee is included
1569 int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
1570 bool fAllowFree = CTransaction::AllowFree(dPriority);
1572 // Disable free transactions until 1 July 2014
1573 if (!fTestNet && wtxNew.nTime < FEE_SWITCH_TIME)
1578 int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
1580 if (nFeeRet < max(nPayFee, nMinFee))
1582 nFeeRet = max(nPayFee, nMinFee);
1586 // Fill vtxPrev by copying from previous transactions vtxPrev
1587 wtxNew.AddSupportingTransactions(txdb);
1588 wtxNew.fTimeReceivedIsTxTime = true;
1597 bool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, const CCoinControl* coinControl)
1599 vector< pair<CScript, int64> > vecSend;
1600 vecSend.push_back(make_pair(scriptPubKey, nValue));
1601 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, coinControl);
1604 void CWallet::GetStakeWeightFromValue(const int64& nTime, const int64& nValue, uint64& nWeight)
1606 int64 nTimeWeight = GetWeight(nTime, (int64)GetTime());
1608 // If time weight is lower or equal to zero then weight is zero.
1609 if (nTimeWeight <= 0)
1615 CBigNum bnCoinDayWeight = CBigNum(nValue) * nTimeWeight / COIN / (24 * 60 * 60);
1616 nWeight = bnCoinDayWeight.getuint64();
1620 // NovaCoin: get current stake weight
1621 bool CWallet::GetStakeWeight(const CKeyStore& keystore, uint64& nMinWeight, uint64& nMaxWeight, uint64& nWeight)
1623 // Choose coins to use
1624 int64 nBalance = GetBalance();
1625 int64 nReserveBalance = 0;
1627 if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
1629 error("GetStakeWeight : invalid reserve balance amount");
1633 if (nBalance <= nReserveBalance)
1636 vector<const CWalletTx*> vwtxPrev;
1638 static set<pair<const CWalletTx*,unsigned int> > setCoins;
1639 static uint256 hashPrevBlock;
1641 // Cache outputs unless best block or wallet transaction set changed
1642 if (!fCoinsDataActual || setCoins.size() == 0)
1645 if (!SelectCoinsSimple(nBalance - nReserveBalance, GetAdjustedTime(), nCoinbaseMaturity * 10, setCoins, nValueIn))
1648 if (setCoins.empty())
1651 fCoinsDataActual = true;
1655 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1657 int64 nTimeWeight = GetWeight((int64)pcoin.first->nTime, (int64)GetTime());
1658 CBigNum bnCoinDayWeight = CBigNum(pcoin.first->vout[pcoin.second].nValue) * nTimeWeight / COIN / (24 * 60 * 60);
1660 // Weight is greater than zero
1661 if (nTimeWeight > 0)
1663 nWeight += bnCoinDayWeight.getuint64();
1666 // Weight is greater than zero, but the maximum value isn't reached yet
1667 if (nTimeWeight > 0 && nTimeWeight < nStakeMaxAge)
1669 nMinWeight += bnCoinDayWeight.getuint64();
1672 // Maximum weight was reached
1673 if (nTimeWeight == nStakeMaxAge)
1675 nMaxWeight += bnCoinDayWeight.getuint64();
1682 bool CWallet::MergeCoins(const int64& nAmount, const int64& nMaxValue, const int64& nOutputValue, list<uint256>& listMerged)
1684 int64 nBalance = GetBalance();
1686 if (nAmount > nBalance)
1691 set<pair<const CWalletTx*,unsigned int> > setCoins;
1693 // Simple coins selection - no randomization
1694 if (!SelectCoinsSimple(nAmount, GetTime(), 1, setCoins, nValueIn))
1697 if (setCoins.empty())
1701 vector<const CWalletTx*> vwtxPrev;
1703 // Reserve a new key pair from key pool
1704 CReserveKey reservekey(this);
1705 CPubKey vchPubKey = reservekey.GetReservedKey();
1708 CScript scriptOutput;
1709 scriptOutput.SetDestination(vchPubKey.GetID());
1712 wtxNew.vout.push_back(CTxOut(0, scriptOutput));
1715 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1717 int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
1719 // Ignore coin if credit is too high
1720 if (nCredit >= nMaxValue)
1723 // Add current coin to inputs list and add its credit to transaction output
1724 wtxNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1725 wtxNew.vout[0].nValue += nCredit;
1726 vwtxPrev.push_back(pcoin.first);
1729 // Replaced with estimation for performance purposes
1731 for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
1732 const CWalletTx *txin = vwtxPrev[i];
1734 // Sign scripts to get actual transaction size for fee calculation
1735 if (!SignSignature(*this, *txin, wtxNew, i))
1740 // Assuming that average scriptsig size is 110 bytes
1741 int64 nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION) + wtxNew.vin.size() * 110;
1742 dWeight += (double)nCredit * pcoin.first->GetDepthInMainChain();
1744 double dFinalPriority = dWeight /= nBytes;
1745 bool fAllowFree = CTransaction::AllowFree(dFinalPriority);
1747 // Get actual transaction fee according to its estimated size and priority
1748 int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
1750 // Prepare transaction for commit if sum is enough ot its size is too big
1751 if (nBytes >= MAX_BLOCK_SIZE_GEN/6 || wtxNew.vout[0].nValue >= nOutputValue)
1753 wtxNew.vout[0].nValue -= nMinFee; // Set actual fee
1755 for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
1756 const CWalletTx *txin = vwtxPrev[i];
1759 if (!SignSignature(*this, *txin, wtxNew, i))
1763 // Try to commit, return false on failure
1764 if (!CommitTransaction(wtxNew, reservekey))
1767 listMerged.push_back(wtxNew.GetHash()); // Add to hashes list
1769 dWeight = 0; // Reset all temporary values
1772 wtxNew.vout.push_back(CTxOut(0, scriptOutput));
1776 // Create transactions if there are some unhandled coins left
1777 if (wtxNew.vout[0].nValue > 0) {
1778 int64 nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION) + wtxNew.vin.size() * 110;
1780 double dFinalPriority = dWeight /= nBytes;
1781 bool fAllowFree = CTransaction::AllowFree(dFinalPriority);
1783 // Get actual transaction fee according to its size and priority
1784 int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
1786 wtxNew.vout[0].nValue -= nMinFee; // Set actual fee
1788 if (wtxNew.vout[0].nValue <= 0)
1791 for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
1792 const CWalletTx *txin = vwtxPrev[i];
1794 // Sign all scripts again
1795 if (!SignSignature(*this, *txin, wtxNew, i))
1799 // Try to commit, return false on failure
1800 if (!CommitTransaction(wtxNew, reservekey))
1803 listMerged.push_back(wtxNew.GetHash()); // Add to hashes list
1810 bool CWallet::CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int64 nSearchInterval, CTransaction& txNew, CKey& key)
1812 // The following combine threshold is important to security
1813 // Should not be adjusted if you don't understand the consequences
1814 int64 nCombineThreshold = GetProofOfWorkReward(GetLastBlockIndex(pindexBest, false)->nBits) / 3;
1816 CBigNum bnTargetPerCoinDay;
1817 bnTargetPerCoinDay.SetCompact(nBits);
1822 // Mark coin stake transaction
1823 CScript scriptEmpty;
1824 scriptEmpty.clear();
1825 txNew.vout.push_back(CTxOut(0, scriptEmpty));
1827 // Choose coins to use
1828 int64 nBalance = GetBalance();
1829 int64 nReserveBalance = 0;
1831 if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
1832 return error("CreateCoinStake : invalid reserve balance amount");
1834 if (nBalance <= nReserveBalance)
1837 vector<const CWalletTx*> vwtxPrev;
1839 static CoinsSet setCoins;
1840 static MetaMap mapMeta;
1844 LOCK2(cs_main, cs_wallet);
1845 // Cache outputs unless best block or wallet transaction set changed
1846 if (!fCoinsDataActual || setCoins.size() == 0)
1852 if (!SelectCoinsSimple(nBalance - nReserveBalance, txNew.nTime, nCoinbaseMaturity * 10, setCoins, nValueIn))
1855 if (setCoins.empty())
1861 for(CoinsSet::iterator pcoin = setCoins.begin(); pcoin != setCoins.end(); pcoin++)
1863 // Load transaction index item
1864 if (!txdb.ReadTxIndex(pcoin->first->GetHash(), txindex))
1867 // Read block header
1868 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
1871 uint64 nStakeModifier = 0;
1873 if (!GetKernelStakeModifier(block.GetHash(), nStakeModifier))
1877 mapMeta[pcoin->first->GetHash()] = make_pair(txindex, make_pair(block, nStakeModifier));
1880 printf("Load coin: %s\n", pcoin->first->GetHash().GetHex().c_str());
1885 printf("Stake miner: %zu meta items loaded for %zu coins\n", mapMeta.size(), setCoins.size());
1887 fCoinsDataActual = true;
1892 CScript scriptPubKeyKernel;
1894 KernelSearchSettings settings;
1895 settings.nBits = nBits;
1896 settings.nTime = txNew.nTime;
1897 settings.nOffset = 0;
1898 settings.nLimit = setCoins.size();
1899 settings.nSearchInterval = nSearchInterval;
1901 unsigned int nTimeTx, nBlockTime;
1902 COutPoint prevoutStake;
1903 CoinsSet::value_type kernelcoin;
1905 if (ScanForStakeKernelHash(setCoins, mapMeta, settings, kernelcoin, nTimeTx, nBlockTime))
1908 if (fDebug && GetBoolArg("-printcoinstake"))
1909 printf("CreateCoinStake : kernel found\n");
1910 vector<valtype> vSolutions;
1911 txnouttype whichType;
1912 CScript scriptPubKeyOut;
1913 scriptPubKeyKernel = kernelcoin.first->vout[kernelcoin.second].scriptPubKey;
1914 if (!Solver(scriptPubKeyKernel, whichType, vSolutions))
1916 if (fDebug && GetBoolArg("-printcoinstake"))
1917 printf("CreateCoinStake : failed to parse kernel\n");
1920 if (fDebug && GetBoolArg("-printcoinstake"))
1921 printf("CreateCoinStake : parsed kernel type=%d\n", whichType);
1922 if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH)
1924 if (fDebug && GetBoolArg("-printcoinstake"))
1925 printf("CreateCoinStake : no support for kernel type=%d\n", whichType);
1926 return false; // only support pay to public key and pay to address
1928 if (whichType == TX_PUBKEYHASH) // pay to address type
1930 // convert to pay to public key type
1931 if (!keystore.GetKey(uint160(vSolutions[0]), key))
1933 if (fDebug && GetBoolArg("-printcoinstake"))
1934 printf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1935 return false; // unable to find corresponding public key
1937 scriptPubKeyOut << key.GetPubKey() << OP_CHECKSIG;
1939 if (whichType == TX_PUBKEY)
1941 valtype& vchPubKey = vSolutions[0];
1942 if (!keystore.GetKey(Hash160(vchPubKey), key))
1944 if (fDebug && GetBoolArg("-printcoinstake"))
1945 printf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1946 return false; // unable to find corresponding public key
1948 if (key.GetPubKey() != vchPubKey)
1950 if (fDebug && GetBoolArg("-printcoinstake"))
1951 printf("CreateCoinStake : invalid key for kernel type=%d\n", whichType);
1952 return false; // keys mismatch
1955 scriptPubKeyOut = scriptPubKeyKernel;
1958 txNew.nTime = nTimeTx;
1959 txNew.vin.push_back(CTxIn(kernelcoin.first->GetHash(), kernelcoin.second));
1960 nCredit += kernelcoin.first->vout[kernelcoin.second].nValue;
1961 vwtxPrev.push_back(kernelcoin.first);
1962 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
1964 if (GetWeight((int64)nBlockTime, (int64)txNew.nTime) < nStakeMaxAge)
1965 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut)); //split stake
1966 if (fDebug && GetBoolArg("-printcoinstake"))
1967 printf("CreateCoinStake : added kernel type=%d\n", whichType);
1970 if (nCredit == 0 || nCredit > nBalance - nReserveBalance)
1973 for(CoinsSet::const_iterator pcoin = setCoins.begin(); pcoin != setCoins.end(); pcoin++)
1975 // Attempt to add more inputs
1976 // Only add coins of the same key/address as kernel
1977 if (txNew.vout.size() == 2 && ((pcoin->first->vout[pcoin->second].scriptPubKey == scriptPubKeyKernel || pcoin->first->vout[pcoin->second].scriptPubKey == txNew.vout[1].scriptPubKey))
1978 && pcoin->first->GetHash() != txNew.vin[0].prevout.hash)
1980 int64 nTimeWeight = GetWeight((int64)pcoin->first->nTime, (int64)txNew.nTime);
1982 // Stop adding more inputs if already too many inputs
1983 if (txNew.vin.size() >= 100)
1985 // Stop adding more inputs if value is already pretty significant
1986 if (nCredit > nCombineThreshold)
1988 // Stop adding inputs if reached reserve limit
1989 if (nCredit + pcoin->first->vout[pcoin->second].nValue > nBalance - nReserveBalance)
1991 // Do not add additional significant input
1992 if (pcoin->first->vout[pcoin->second].nValue > nCombineThreshold)
1994 // Do not add input that is still too young
1995 if (nTimeWeight < nStakeMaxAge)
1998 txNew.vin.push_back(CTxIn(pcoin->first->GetHash(), pcoin->second));
1999 nCredit += pcoin->first->vout[pcoin->second].nValue;
2000 vwtxPrev.push_back(pcoin->first);
2004 // Calculate coin age reward
2008 if (!txNew.GetCoinAge(txdb, nCoinAge))
2009 return error("CreateCoinStake : failed to calculate coin age");
2010 nCredit += GetProofOfStakeReward(nCoinAge, nBits, txNew.nTime);
2016 // Set output amount
2017 if (txNew.vout.size() == 3)
2019 txNew.vout[1].nValue = ((nCredit - nMinFee) / 2 / CENT) * CENT;
2020 txNew.vout[2].nValue = nCredit - nMinFee - txNew.vout[1].nValue;
2023 txNew.vout[1].nValue = nCredit - nMinFee;
2027 BOOST_FOREACH(const CWalletTx* pcoin, vwtxPrev)
2029 if (!SignSignature(*this, *pcoin, txNew, nIn++))
2030 return error("CreateCoinStake : failed to sign coinstake");
2034 unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION);
2035 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
2036 return error("CreateCoinStake : exceeded coinstake size limit");
2038 // Check enough fee is paid
2039 if (nMinFee < txNew.GetMinFee(1, false, GMF_BLOCK, nBytes) - CENT)
2041 nMinFee = txNew.GetMinFee(1, false, GMF_BLOCK, nBytes) - CENT;
2042 continue; // try signing again
2046 if (fDebug && GetBoolArg("-printfee"))
2047 printf("CreateCoinStake : fee for coinstake %s\n", FormatMoney(nMinFee).c_str());
2052 // Successfully generated coinstake
2057 // Call after CreateTransaction unless you want to abort
2058 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
2061 LOCK2(cs_main, cs_wallet);
2062 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
2064 // This is only to keep the database open to defeat the auto-flush for the
2065 // duration of this scope. This is the only place where this optimization
2066 // maybe makes sense; please don't do it anywhere else.
2067 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
2069 // Take key pair from key pool so it won't be used again
2070 reservekey.KeepKey();
2072 // Add tx to wallet, because if it has change it's also ours,
2073 // otherwise just for transaction history.
2074 AddToWallet(wtxNew);
2076 // Mark old coins as spent
2077 set<CWalletTx*> setCoins;
2078 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
2080 CWalletTx &coin = mapWallet[txin.prevout.hash];
2081 coin.BindWallet(this);
2082 coin.MarkSpent(txin.prevout.n);
2084 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
2091 // Track how many getdata requests our transaction gets
2092 mapRequestCount[wtxNew.GetHash()] = 0;
2095 if (!wtxNew.AcceptToMemoryPool())
2097 // This must not fail. The transaction has already been signed and recorded.
2098 printf("CommitTransaction() : Error: Transaction not valid");
2101 wtxNew.RelayWalletTransaction();
2109 string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
2111 CReserveKey reservekey(this);
2116 string strError = _("Error: Wallet locked, unable to create transaction ");
2117 printf("SendMoney() : %s", strError.c_str());
2120 if (fWalletUnlockMintOnly)
2122 string strError = _("Error: Wallet unlocked for block minting only, unable to create transaction.");
2123 printf("SendMoney() : %s", strError.c_str());
2126 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
2129 if (nValue + nFeeRequired > GetBalance())
2130 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());
2132 strError = _("Error: Transaction creation failed ");
2133 printf("SendMoney() : %s", strError.c_str());
2137 if (fAskFee && !uiInterface.ThreadSafeAskFee(nFeeRequired, _("Sending...")))
2140 if (!CommitTransaction(wtxNew, reservekey))
2141 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.");
2148 string CWallet::SendMoneyToDestination(const CTxDestination& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
2152 return _("Invalid amount");
2153 if (nValue + nTransactionFee > GetBalance())
2154 return _("Insufficient funds");
2156 // Parse Bitcoin address
2157 CScript scriptPubKey;
2158 scriptPubKey.SetDestination(address);
2160 return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
2166 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
2170 fFirstRunRet = false;
2171 DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
2172 if (nLoadWalletRet == DB_NEED_REWRITE)
2174 if (CDB::Rewrite(strWalletFile, "\x04pool"))
2177 // Note: can't top-up keypool here, because wallet is locked.
2178 // User will be prompted to unlock wallet the next operation
2179 // the requires a new key.
2183 if (nLoadWalletRet != DB_LOAD_OK)
2184 return nLoadWalletRet;
2185 fFirstRunRet = !vchDefaultKey.IsValid();
2187 NewThread(ThreadFlushWalletDB, &strWalletFile);
2192 bool CWallet::SetAddressBookName(const CTxDestination& address, const string& strName)
2194 std::map<CTxDestination, std::string>::iterator mi = mapAddressBook.find(address);
2195 mapAddressBook[address] = strName;
2196 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address), (mi == mapAddressBook.end()) ? CT_NEW : CT_UPDATED);
2199 return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName);
2202 bool CWallet::DelAddressBookName(const CTxDestination& address)
2204 mapAddressBook.erase(address);
2205 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address), CT_DELETED);
2208 return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString());
2212 void CWallet::PrintWallet(const CBlock& block)
2216 if (block.IsProofOfWork() && mapWallet.count(block.vtx[0].GetHash()))
2218 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
2219 printf(" mine: %d %d %"PRI64d"", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
2221 if (block.IsProofOfStake() && mapWallet.count(block.vtx[1].GetHash()))
2223 CWalletTx& wtx = mapWallet[block.vtx[1].GetHash()];
2224 printf(" stake: %d %d %"PRI64d"", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
2231 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
2235 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
2236 if (mi != mapWallet.end())
2245 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
2249 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
2252 vchDefaultKey = vchPubKey;
2256 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
2258 if (!pwallet->fFileBacked)
2260 strWalletFileOut = pwallet->strWalletFile;
2265 // Mark old keypool keys as used,
2266 // and generate all new keys
2268 bool CWallet::NewKeyPool()
2272 CWalletDB walletdb(strWalletFile);
2273 BOOST_FOREACH(int64 nIndex, setKeyPool)
2274 walletdb.ErasePool(nIndex);
2280 int64 nKeys = max(GetArg("-keypool", 100), (int64)0);
2281 for (int i = 0; i < nKeys; i++)
2284 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
2285 setKeyPool.insert(nIndex);
2287 printf("CWallet::NewKeyPool wrote %"PRI64d" new keys\n", nKeys);
2292 bool CWallet::TopUpKeyPool(unsigned int nSize)
2300 CWalletDB walletdb(strWalletFile);
2303 unsigned int nTargetSize;
2305 nTargetSize = nSize;
2307 nTargetSize = max(GetArg("-keypool", 100), 0LL);
2309 while (setKeyPool.size() < (nTargetSize + 1))
2312 if (!setKeyPool.empty())
2313 nEnd = *(--setKeyPool.end()) + 1;
2314 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
2315 throw runtime_error("TopUpKeyPool() : writing generated key failed");
2316 setKeyPool.insert(nEnd);
2317 printf("keypool added key %"PRI64d", size=%"PRIszu"\n", nEnd, setKeyPool.size());
2323 void CWallet::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool)
2326 keypool.vchPubKey = CPubKey();
2333 // Get the oldest key
2334 if(setKeyPool.empty())
2337 CWalletDB walletdb(strWalletFile);
2339 nIndex = *(setKeyPool.begin());
2340 setKeyPool.erase(setKeyPool.begin());
2341 if (!walletdb.ReadPool(nIndex, keypool))
2342 throw runtime_error("ReserveKeyFromKeyPool() : read failed");
2343 if (!HaveKey(keypool.vchPubKey.GetID()))
2344 throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
2345 assert(keypool.vchPubKey.IsValid());
2346 if (fDebug && GetBoolArg("-printkeypool"))
2347 printf("keypool reserve %"PRI64d"\n", nIndex);
2351 int64 CWallet::AddReserveKey(const CKeyPool& keypool)
2354 LOCK2(cs_main, cs_wallet);
2355 CWalletDB walletdb(strWalletFile);
2357 int64 nIndex = 1 + *(--setKeyPool.end());
2358 if (!walletdb.WritePool(nIndex, keypool))
2359 throw runtime_error("AddReserveKey() : writing added key failed");
2360 setKeyPool.insert(nIndex);
2366 void CWallet::KeepKey(int64 nIndex)
2368 // Remove from key pool
2371 CWalletDB walletdb(strWalletFile);
2372 walletdb.ErasePool(nIndex);
2375 printf("keypool keep %"PRI64d"\n", nIndex);
2378 void CWallet::ReturnKey(int64 nIndex)
2380 // Return to key pool
2383 setKeyPool.insert(nIndex);
2386 printf("keypool return %"PRI64d"\n", nIndex);
2389 bool CWallet::GetKeyFromPool(CPubKey& result, bool fAllowReuse)
2395 ReserveKeyFromKeyPool(nIndex, keypool);
2398 if (fAllowReuse && vchDefaultKey.IsValid())
2400 result = vchDefaultKey;
2403 if (IsLocked()) return false;
2404 result = GenerateNewKey();
2408 result = keypool.vchPubKey;
2413 int64 CWallet::GetOldestKeyPoolTime()
2417 ReserveKeyFromKeyPool(nIndex, keypool);
2421 return keypool.nTime;
2424 std::map<CTxDestination, int64> CWallet::GetAddressBalances()
2426 map<CTxDestination, int64> balances;
2430 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2432 CWalletTx *pcoin = &walletEntry.second;
2434 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
2437 if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0)
2440 int nDepth = pcoin->GetDepthInMainChain();
2441 if (nDepth < (pcoin->IsFromMe(MINE_ALL) ? 0 : 1))
2444 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2446 CTxDestination addr;
2447 if (!IsMine(pcoin->vout[i]))
2449 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr))
2452 int64 n = pcoin->IsSpent(i) ? 0 : pcoin->vout[i].nValue;
2454 if (!balances.count(addr))
2456 balances[addr] += n;
2464 set< set<CTxDestination> > CWallet::GetAddressGroupings()
2466 set< set<CTxDestination> > groupings;
2467 set<CTxDestination> grouping;
2469 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2471 CWalletTx *pcoin = &walletEntry.second;
2473 if (pcoin->vin.size() > 0 && IsMine(pcoin->vin[0]))
2475 // group all input addresses with each other
2476 BOOST_FOREACH(CTxIn txin, pcoin->vin)
2478 CTxDestination address;
2479 if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
2481 grouping.insert(address);
2484 // group change with input addresses
2485 BOOST_FOREACH(CTxOut txout, pcoin->vout)
2486 if (IsChange(txout))
2488 CWalletTx tx = mapWallet[pcoin->vin[0].prevout.hash];
2489 CTxDestination txoutAddr;
2490 if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
2492 grouping.insert(txoutAddr);
2494 groupings.insert(grouping);
2498 // group lone addrs by themselves
2499 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2500 if (IsMine(pcoin->vout[i]))
2502 CTxDestination address;
2503 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address))
2505 grouping.insert(address);
2506 groupings.insert(grouping);
2511 set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
2512 map< CTxDestination, set<CTxDestination>* > setmap; // map addresses to the unique group containing it
2513 BOOST_FOREACH(set<CTxDestination> grouping, groupings)
2515 // make a set of all the groups hit by this new group
2516 set< set<CTxDestination>* > hits;
2517 map< CTxDestination, set<CTxDestination>* >::iterator it;
2518 BOOST_FOREACH(CTxDestination address, grouping)
2519 if ((it = setmap.find(address)) != setmap.end())
2520 hits.insert((*it).second);
2522 // merge all hit groups into a new single group and delete old groups
2523 set<CTxDestination>* merged = new set<CTxDestination>(grouping);
2524 BOOST_FOREACH(set<CTxDestination>* hit, hits)
2526 merged->insert(hit->begin(), hit->end());
2527 uniqueGroupings.erase(hit);
2530 uniqueGroupings.insert(merged);
2533 BOOST_FOREACH(CTxDestination element, *merged)
2534 setmap[element] = merged;
2537 set< set<CTxDestination> > ret;
2538 BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings)
2540 ret.insert(*uniqueGrouping);
2541 delete uniqueGrouping;
2547 // ppcoin: check 'spent' consistency between wallet and txindex
2548 // ppcoin: fix wallet spent state according to txindex
2549 void CWallet::FixSpentCoins(int& nMismatchFound, int64& nBalanceInQuestion, bool fCheckOnly)
2552 nBalanceInQuestion = 0;
2555 vector<CWalletTx*> vCoins;
2556 vCoins.reserve(mapWallet.size());
2557 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2558 vCoins.push_back(&(*it).second);
2561 BOOST_FOREACH(CWalletTx* pcoin, vCoins)
2563 // Find the corresponding transaction index
2565 if (!txdb.ReadTxIndex(pcoin->GetHash(), txindex))
2567 for (unsigned int n=0; n < pcoin->vout.size(); n++)
2569 if (IsMine(pcoin->vout[n]) && pcoin->IsSpent(n) && (txindex.vSpent.size() <= n || txindex.vSpent[n].IsNull()))
2571 printf("FixSpentCoins found lost coin %sppc %s[%d], %s\n",
2572 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2574 nBalanceInQuestion += pcoin->vout[n].nValue;
2577 pcoin->MarkUnspent(n);
2578 pcoin->WriteToDisk();
2581 else if (IsMine(pcoin->vout[n]) && !pcoin->IsSpent(n) && (txindex.vSpent.size() > n && !txindex.vSpent[n].IsNull()))
2583 printf("FixSpentCoins found spent coin %sppc %s[%d], %s\n",
2584 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2586 nBalanceInQuestion += pcoin->vout[n].nValue;
2589 pcoin->MarkSpent(n);
2590 pcoin->WriteToDisk();
2596 if(IsMine((CTransaction)*pcoin) && (pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetDepthInMainChain() == 0)
2598 printf("FixSpentCoins %s tx %s\n", fCheckOnly ? "found" : "removed", pcoin->GetHash().ToString().c_str());
2601 EraseFromWallet(pcoin->GetHash());
2607 // ppcoin: disable transaction (only for coinstake)
2608 void CWallet::DisableTransaction(const CTransaction &tx)
2610 if (!tx.IsCoinStake() || !IsFromMe(tx))
2611 return; // only disconnecting coinstake requires marking input unspent
2614 BOOST_FOREACH(const CTxIn& txin, tx.vin)
2616 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
2617 if (mi != mapWallet.end())
2619 CWalletTx& prev = (*mi).second;
2620 if (txin.prevout.n < prev.vout.size() && IsMine(prev.vout[txin.prevout.n]))
2622 prev.MarkUnspent(txin.prevout.n);
2629 CPubKey CReserveKey::GetReservedKey()
2634 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
2636 vchPubKey = keypool.vchPubKey;
2639 printf("CReserveKey::GetReservedKey(): Warning: Using default key instead of a new key, top up your keypool!");
2640 vchPubKey = pwallet->vchDefaultKey;
2643 assert(vchPubKey.IsValid());
2647 void CReserveKey::KeepKey()
2650 pwallet->KeepKey(nIndex);
2652 vchPubKey = CPubKey();
2655 void CReserveKey::ReturnKey()
2658 pwallet->ReturnKey(nIndex);
2660 vchPubKey = CPubKey();
2663 void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
2667 CWalletDB walletdb(strWalletFile);
2669 LOCK2(cs_main, cs_wallet);
2670 BOOST_FOREACH(const int64& id, setKeyPool)
2673 if (!walletdb.ReadPool(id, keypool))
2674 throw runtime_error("GetAllReserveKeyHashes() : read failed");
2675 assert(keypool.vchPubKey.IsValid());
2676 CKeyID keyID = keypool.vchPubKey.GetID();
2677 if (!HaveKey(keyID))
2678 throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
2679 setAddress.insert(keyID);
2683 void CWallet::UpdatedTransaction(const uint256 &hashTx)
2687 // Only notify UI if this transaction is in this wallet
2688 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
2689 if (mi != mapWallet.end())
2690 NotifyTransactionChanged(this, hashTx, CT_UPDATED);
2694 void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64> &mapKeyBirth) const {
2695 mapKeyBirth.clear();
2697 // get birth times for keys with metadata
2698 for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++)
2699 if (it->second.nCreateTime)
2700 mapKeyBirth[it->first] = it->second.nCreateTime;
2702 // map in which we'll infer heights of other keys
2703 CBlockIndex *pindexMax = FindBlockByHeight(std::max(0, nBestHeight - 144)); // the tip can be reorganised; use a 144-block safety margin
2704 std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
2705 std::set<CKeyID> setKeys;
2707 BOOST_FOREACH(const CKeyID &keyid, setKeys) {
2708 if (mapKeyBirth.count(keyid) == 0)
2709 mapKeyFirstBlock[keyid] = pindexMax;
2713 // if there are no such keys, we're done
2714 if (mapKeyFirstBlock.empty())
2717 // find first block that affects those keys, if there are any left
2718 std::vector<CKeyID> vAffected;
2719 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
2720 // iterate over all wallet transactions...
2721 const CWalletTx &wtx = (*it).second;
2722 std::map<uint256, CBlockIndex*>::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
2723 if (blit != mapBlockIndex.end() && blit->second->IsInMainChain()) {
2724 // ... which are already in a block
2725 int nHeight = blit->second->nHeight;
2726 BOOST_FOREACH(const CTxOut &txout, wtx.vout) {
2727 // iterate over all their outputs
2728 ::ExtractAffectedKeys(*this, txout.scriptPubKey, vAffected);
2729 BOOST_FOREACH(const CKeyID &keyid, vAffected) {
2730 // ... and all their affected keys
2731 std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
2732 if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
2733 rit->second = blit->second;
2740 // Extract block timestamps for those keys
2741 for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
2742 mapKeyBirth[it->first] = it->second->nTime - 7200; // block times can be 2h off