1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
10 #include "ui_interface.h"
13 #include "coincontrol.h"
14 #include <boost/algorithm/string/replace.hpp>
21 bool fCoinsDataActual;
23 //////////////////////////////////////////////////////////////////////////////
28 struct CompareValueOnly
30 bool operator()(const pair<int64_t, pair<const CWalletTx*, unsigned int> >& t1,
31 const pair<int64_t, pair<const CWalletTx*, unsigned int> >& t2) const
33 return t1.first < t2.first;
37 CPubKey CWallet::GenerateNewKey()
39 bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
43 key.MakeNewKey(fCompressed);
45 // Compressed public keys were introduced in version 0.6.0
47 SetMinVersion(FEATURE_COMPRPUBKEY);
49 CPubKey pubkey = key.GetPubKey();
51 // Create new metadata
52 int64_t nCreationTime = GetTime();
53 mapKeyMetadata[pubkey.GetID()] = CKeyMetadata(nCreationTime);
54 if (!nTimeFirstKey || nCreationTime < nTimeFirstKey)
55 nTimeFirstKey = nCreationTime;
58 throw std::runtime_error("CWallet::GenerateNewKey() : AddKey failed");
59 return key.GetPubKey();
62 bool CWallet::AddKey(const CKey& key)
64 CPubKey pubkey = key.GetPubKey();
65 if (!CCryptoKeyStore::AddKey(key))
70 return CWalletDB(strWalletFile).WriteKey(pubkey, key.GetPrivKey(), mapKeyMetadata[pubkey.GetID()]);
74 bool CWallet::AddCryptedKey(const CPubKey &vchPubKey, const vector<unsigned char> &vchCryptedSecret)
76 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
79 // check if we need to remove from watch-only
81 script.SetDestination(vchPubKey.GetID());
82 if (HaveWatchOnly(script))
83 RemoveWatchOnly(script);
89 if (pwalletdbEncryption)
90 return pwalletdbEncryption->WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]);
92 return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]);
97 bool CWallet::LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &meta)
99 if (meta.nCreateTime && (!nTimeFirstKey || meta.nCreateTime < nTimeFirstKey))
100 nTimeFirstKey = meta.nCreateTime;
102 mapKeyMetadata[pubkey.GetID()] = meta;
106 bool CWallet::AddCScript(const CScript& redeemScript)
108 if (!CCryptoKeyStore::AddCScript(redeemScript))
112 return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript);
115 bool CWallet::LoadCScript(const CScript& redeemScript)
117 /* A sanity check was added in commit 5ed0a2b to avoid adding redeemScripts
118 * that never can be redeemed. However, old wallets may still contain
119 * these. Do not add them to the wallet and warn. */
120 if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
122 std::string strAddr = CBitcoinAddress(redeemScript.GetID()).ToString();
123 printf("LoadCScript() : Warning: This wallet contains a redeemScript of size %" PRIszu " which exceeds maximum size %i thus can never be redeemed. Do not use address %s.\n",
124 redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr.c_str());
128 return CCryptoKeyStore::AddCScript(redeemScript);
132 bool CWallet::AddWatchOnly(const CScript &dest)
134 if (!CCryptoKeyStore::AddWatchOnly(dest))
136 nTimeFirstKey = 1; // No birthday information for watch-only keys.
137 NotifyWatchonlyChanged(true);
140 return CWalletDB(strWalletFile).WriteWatchOnly(dest);
143 bool CWallet::RemoveWatchOnly(const CScript &dest)
146 if (!CCryptoKeyStore::RemoveWatchOnly(dest))
148 if (!HaveWatchOnly())
149 NotifyWatchonlyChanged(false);
151 if (!CWalletDB(strWalletFile).EraseWatchOnly(dest))
157 bool CWallet::LoadWatchOnly(const CScript &dest)
159 return CCryptoKeyStore::AddWatchOnly(dest);
162 // ppcoin: optional setting to unlock wallet for block minting only;
163 // serves to disable the trivial sendmoney when OS account compromised
164 bool fWalletUnlockMintOnly = false;
166 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
172 CKeyingMaterial vMasterKey;
176 BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
178 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
180 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
182 if (CCryptoKeyStore::Unlock(vMasterKey))
189 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
191 bool fWasLocked = IsLocked();
198 CKeyingMaterial vMasterKey;
199 BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
201 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
203 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
205 if (CCryptoKeyStore::Unlock(vMasterKey))
207 int64_t nStartTime = GetTimeMillis();
208 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
209 pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
211 nStartTime = GetTimeMillis();
212 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
213 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
215 if (pMasterKey.second.nDeriveIterations < 25000)
216 pMasterKey.second.nDeriveIterations = 25000;
218 printf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
220 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
222 if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
224 CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
235 void CWallet::SetBestChain(const CBlockLocator& loc)
237 CWalletDB walletdb(strWalletFile);
238 walletdb.WriteBestBlock(loc);
241 // This class implements an addrIncoming entry that causes pre-0.4
242 // clients to crash on startup if reading a private-key-encrypted wallet.
243 class CCorruptAddress
248 if (nType & SER_DISK)
253 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
255 if (nWalletVersion >= nVersion)
258 // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
259 if (fExplicit && nVersion > nWalletMaxVersion)
260 nVersion = FEATURE_LATEST;
262 nWalletVersion = nVersion;
264 if (nVersion > nWalletMaxVersion)
265 nWalletMaxVersion = nVersion;
269 CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile);
270 if (nWalletVersion >= 40000)
272 // Versions prior to 0.4.0 did not support the "minversion" record.
273 // Use a CCorruptAddress to make them crash instead.
274 CCorruptAddress corruptAddress;
275 pwalletdb->WriteSetting("addrIncoming", corruptAddress);
277 if (nWalletVersion > 40000)
278 pwalletdb->WriteMinVersion(nWalletVersion);
286 bool CWallet::SetMaxVersion(int nVersion)
288 // cannot downgrade below current version
289 if (nWalletVersion > nVersion)
292 nWalletMaxVersion = nVersion;
297 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
302 CKeyingMaterial vMasterKey;
303 RandAddSeedPerfmon();
305 vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
306 RAND_bytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
308 CMasterKey kMasterKey;
310 RandAddSeedPerfmon();
311 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
312 RAND_bytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
315 int64_t nStartTime = GetTimeMillis();
316 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
317 kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
319 nStartTime = GetTimeMillis();
320 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
321 kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
323 if (kMasterKey.nDeriveIterations < 25000)
324 kMasterKey.nDeriveIterations = 25000;
326 printf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
328 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
330 if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
335 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
338 pwalletdbEncryption = new CWalletDB(strWalletFile);
339 if (!pwalletdbEncryption->TxnBegin())
341 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
344 if (!EncryptKeys(vMasterKey))
347 pwalletdbEncryption->TxnAbort();
348 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.
351 // Encryption was introduced in version 0.4.0
352 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
356 if (!pwalletdbEncryption->TxnCommit())
357 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.
359 delete pwalletdbEncryption;
360 pwalletdbEncryption = NULL;
364 Unlock(strWalletPassphrase);
368 // Need to completely rewrite the wallet file; if we don't, bdb might keep
369 // bits of the unencrypted private key in slack space in the database file.
370 CDB::Rewrite(strWalletFile);
373 NotifyStatusChanged(this);
378 bool CWallet::DecryptWallet(const SecureString& strWalletPassphrase)
384 CKeyingMaterial vMasterKey;
388 BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
390 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
392 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
394 if (!CCryptoKeyStore::Unlock(vMasterKey))
400 pwalletdbDecryption = new CWalletDB(strWalletFile);
401 if (!pwalletdbDecryption->TxnBegin())
405 if (!DecryptKeys(vMasterKey))
408 pwalletdbDecryption->TxnAbort();
409 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.
414 // Overwrite crypted keys
415 KeyMap::const_iterator mi = mapKeys.begin();
416 while (mi != mapKeys.end())
419 key.SetSecret((*mi).second.first, (*mi).second.second);
420 pwalletdbDecryption->EraseCryptedKey(key.GetPubKey());
421 pwalletdbDecryption->WriteKey(key.GetPubKey(), key.GetPrivKey(), mapKeyMetadata[(*mi).first]);
426 MasterKeyMap::const_iterator mk = mapMasterKeys.begin();
427 while (mk != mapMasterKeys.end())
429 pwalletdbDecryption->EraseMasterKey((*mk).first);
433 if (!pwalletdbDecryption->TxnCommit())
434 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.
436 delete pwalletdbDecryption;
437 pwalletdbDecryption = NULL;
440 // Need to completely rewrite the wallet file; if we don't, bdb might keep
441 // encrypted private keys in the database file which can be a reason of consistency issues.
442 CDB::Rewrite(strWalletFile);
444 NotifyStatusChanged(this);
449 int64_t CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
451 int64_t nRet = nOrderPosNext++;
453 pwalletdb->WriteOrderPosNext(nOrderPosNext);
455 CWalletDB(strWalletFile).WriteOrderPosNext(nOrderPosNext);
460 CWallet::TxItems CWallet::OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount)
462 CWalletDB walletdb(strWalletFile);
464 // First: get all CWalletTx and CAccountingEntry into a sorted-by-order multimap.
467 // Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry
468 // would make this much faster for applications that do this a lot.
469 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
471 CWalletTx* wtx = &((*it).second);
472 txOrdered.insert(make_pair(wtx->nOrderPos, TxPair(wtx, (CAccountingEntry*)0)));
475 walletdb.ListAccountCreditDebit(strAccount, acentries);
476 BOOST_FOREACH(CAccountingEntry& entry, acentries)
478 txOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
484 void CWallet::WalletUpdateSpent(const CTransaction &tx, bool fBlock)
486 // Anytime a signature is successfully verified, it's proof the outpoint is spent.
487 // Update the wallet spent flag if it doesn't know due to wallet.dat being
488 // restored from backup or the user making copies of wallet.dat.
491 BOOST_FOREACH(const CTxIn& txin, tx.vin)
493 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
494 if (mi != mapWallet.end())
496 CWalletTx& wtx = (*mi).second;
497 if (txin.prevout.n >= wtx.vout.size())
498 printf("WalletUpdateSpent: bad wtx %s\n", wtx.GetHash().ToString().c_str());
499 else if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n]))
501 printf("WalletUpdateSpent found spent coin %snvc %s\n", FormatMoney(wtx.GetCredit(MINE_ALL)).c_str(), wtx.GetHash().ToString().c_str());
502 wtx.MarkSpent(txin.prevout.n);
504 NotifyTransactionChanged(this, txin.prevout.hash, CT_UPDATED);
505 vMintingWalletUpdated.push_back(txin.prevout.hash);
512 uint256 hash = tx.GetHash();
513 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hash);
514 CWalletTx& wtx = (*mi).second;
516 BOOST_FOREACH(const CTxOut& txout, tx.vout)
520 wtx.MarkUnspent(&txout - &tx.vout[0]);
522 NotifyTransactionChanged(this, hash, CT_UPDATED);
523 vMintingWalletUpdated.push_back(hash);
531 void CWallet::MarkDirty()
535 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
536 item.second.MarkDirty();
540 bool CWallet::AddToWallet(const CWalletTx& wtxIn)
542 uint256 hash = wtxIn.GetHash();
545 // Inserts only if not already there, returns tx inserted or tx found
546 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
547 CWalletTx& wtx = (*ret.first).second;
548 wtx.BindWallet(this);
549 bool fInsertedNew = ret.second;
552 wtx.nTimeReceived = GetAdjustedTime();
553 wtx.nOrderPos = IncOrderPosNext();
555 wtx.nTimeSmart = wtx.nTimeReceived;
556 if (wtxIn.hashBlock != 0)
558 if (mapBlockIndex.count(wtxIn.hashBlock))
560 unsigned int latestNow = wtx.nTimeReceived;
561 unsigned int latestEntry = 0;
563 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
564 int64_t latestTolerated = latestNow + 300;
565 std::list<CAccountingEntry> acentries;
566 TxItems txOrdered = OrderedTxItems(acentries);
567 for (TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
569 CWalletTx *const pwtx = (*it).second.first;
572 CAccountingEntry *const pacentry = (*it).second.second;
576 nSmartTime = pwtx->nTimeSmart;
578 nSmartTime = pwtx->nTimeReceived;
581 nSmartTime = pacentry->nTime;
582 if (nSmartTime <= latestTolerated)
584 latestEntry = nSmartTime;
585 if (nSmartTime > latestNow)
586 latestNow = nSmartTime;
592 unsigned int& blocktime = mapBlockIndex[wtxIn.hashBlock]->nTime;
593 wtx.nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
596 printf("AddToWallet() : found %s in block %s not in index\n",
597 wtxIn.GetHash().ToString().substr(0,10).c_str(),
598 wtxIn.hashBlock.ToString().c_str());
602 bool fUpdated = false;
606 if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
608 wtx.hashBlock = wtxIn.hashBlock;
611 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
613 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
614 wtx.nIndex = wtxIn.nIndex;
617 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
619 wtx.fFromMe = wtxIn.fFromMe;
622 fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);
626 printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
629 if (fInsertedNew || fUpdated)
630 if (!wtx.WriteToDisk())
633 // If default receiving address gets used, replace it with a new one
634 CScript scriptDefaultKey;
635 scriptDefaultKey.SetDestination(vchDefaultKey.GetID());
636 BOOST_FOREACH(const CTxOut& txout, wtx.vout)
638 if (txout.scriptPubKey == scriptDefaultKey)
640 CPubKey newDefaultKey;
641 if (GetKeyFromPool(newDefaultKey, false))
643 SetDefaultKey(newDefaultKey);
644 SetAddressBookName(vchDefaultKey.GetID(), "");
649 // since AddToWallet is called directly for self-originating transactions, check for consumption of own coins
650 WalletUpdateSpent(wtx, (wtxIn.hashBlock != 0));
652 // Notify UI of new or updated transaction
653 NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
654 vMintingWalletUpdated.push_back(hash);
655 // notify an external script when a wallet transaction comes in or is updated
656 std::string strCmd = GetArg("-walletnotify", "");
658 if ( !strCmd.empty())
660 boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
661 boost::thread t(runCommand, strCmd); // thread runs free
668 // Add a transaction to the wallet, or update it.
669 // pblock is optional, but should be provided if the transaction is known to be in a block.
670 // If fUpdate is true, existing transactions will be updated.
671 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fFindBlock)
673 uint256 hash = tx.GetHash();
676 bool fExisted = mapWallet.count(hash);
677 if (fExisted && !fUpdate) return false;
678 if (fExisted || IsMine(tx) || IsFromMe(tx))
680 CWalletTx wtx(this,tx);
681 // Get merkle branch if transaction was found in a block
683 wtx.SetMerkleBranch(pblock);
684 return AddToWallet(wtx);
687 WalletUpdateSpent(tx);
692 bool CWallet::EraseFromWallet(uint256 hash)
698 if (mapWallet.erase(hash))
699 CWalletDB(strWalletFile).EraseTx(hash);
705 isminetype CWallet::IsMine(const CTxIn &txin) const
709 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
710 if (mi != mapWallet.end())
712 const CWalletTx& prev = (*mi).second;
713 if (txin.prevout.n < prev.vout.size())
714 return IsMine(prev.vout[txin.prevout.n]);
720 int64_t CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
724 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
725 if (mi != mapWallet.end())
727 const CWalletTx& prev = (*mi).second;
728 if (txin.prevout.n < prev.vout.size())
729 if (IsMine(prev.vout[txin.prevout.n]) & filter)
730 return prev.vout[txin.prevout.n].nValue;
736 bool CWallet::IsChange(const CTxOut& txout) const
738 // TODO: fix handling of 'change' outputs. The assumption is that any
739 // payment to a script that is ours, but isn't in the address book
740 // is change. That assumption is likely to break when we implement multisignature
741 // wallets that return change back into a multi-signature-protected address;
742 // a better way of identifying which outputs are 'the send' and which are
743 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
744 // which output, if any, was change).
745 if (::IsMine(*this, txout.scriptPubKey))
747 CTxDestination address;
748 if (!ExtractDestination(txout.scriptPubKey, address))
752 if (!mapAddressBook.count(address))
758 int64_t CWalletTx::GetTxTime() const
763 int CWalletTx::GetRequestCount() const
765 // Returns -1 if it wasn't being tracked
768 LOCK(pwallet->cs_wallet);
769 if (IsCoinBase() || IsCoinStake())
774 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
775 if (mi != pwallet->mapRequestCount.end())
776 nRequests = (*mi).second;
781 // Did anyone request this transaction?
782 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
783 if (mi != pwallet->mapRequestCount.end())
785 nRequests = (*mi).second;
787 // How about the block it's in?
788 if (nRequests == 0 && hashBlock != 0)
790 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
791 if (mi != pwallet->mapRequestCount.end())
792 nRequests = (*mi).second;
794 nRequests = 1; // If it's in someone else's block it must have got out
802 void CWalletTx::GetAmounts(int64_t& nGeneratedImmature, int64_t& nGeneratedMature, list<pair<CTxDestination, int64_t> >& listReceived,
803 list<pair<CTxDestination, int64_t> >& listSent, int64_t& nFee, string& strSentAccount, const isminefilter& filter) const
805 nGeneratedImmature = nGeneratedMature = nFee = 0;
806 listReceived.clear();
808 strSentAccount = strFromAccount;
810 if (IsCoinBase() || IsCoinStake())
812 if (GetBlocksToMaturity() > 0)
813 nGeneratedImmature = pwallet->GetCredit(*this, filter);
815 nGeneratedMature = GetCredit(filter);
820 int64_t nDebit = GetDebit(filter);
821 if (nDebit > 0) // debit>0 means we signed/sent this transaction
823 int64_t nValueOut = GetValueOut();
824 nFee = nDebit - nValueOut;
828 BOOST_FOREACH(const CTxOut& txout, vout)
830 isminetype fIsMine = pwallet->IsMine(txout);
831 // Only need to handle txouts if AT LEAST one of these is true:
832 // 1) they debit from us (sent)
833 // 2) the output is to us (received)
836 // Don't report 'change' txouts
837 if (pwallet->IsChange(txout))
840 else if (!(fIsMine & filter))
843 // In either case, we need to get the destination address
844 CTxDestination address;
845 if (!ExtractDestination(txout.scriptPubKey, address))
847 printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
848 this->GetHash().ToString().c_str());
849 address = CNoDestination();
852 // If we are debited by the transaction, add the output as a "sent" entry
854 listSent.push_back(make_pair(address, txout.nValue));
856 // If we are receiving the output, add it as a "received" entry
857 if (fIsMine & filter)
858 listReceived.push_back(make_pair(address, txout.nValue));
863 void CWalletTx::GetAccountAmounts(const string& strAccount, int64_t& nGenerated, int64_t& nReceived,
864 int64_t& nSent, int64_t& nFee, const isminefilter& filter) const
866 nGenerated = nReceived = nSent = nFee = 0;
868 int64_t allGeneratedImmature, allGeneratedMature, allFee;
869 allGeneratedImmature = allGeneratedMature = allFee = 0;
870 string strSentAccount;
871 list<pair<CTxDestination, int64_t> > listReceived;
872 list<pair<CTxDestination, int64_t> > listSent;
873 GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount, filter);
875 if (strAccount == "")
876 nGenerated = allGeneratedMature;
877 if (strAccount == strSentAccount)
879 BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64_t)& s, listSent)
884 LOCK(pwallet->cs_wallet);
885 BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64_t)& r, listReceived)
887 if (pwallet->mapAddressBook.count(r.first))
889 map<CTxDestination, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);
890 if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)
891 nReceived += r.second;
893 else if (strAccount.empty())
895 nReceived += r.second;
901 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
905 const int COPY_DEPTH = 3;
906 if (SetMerkleBranch() < COPY_DEPTH)
908 vector<uint256> vWorkQueue;
909 BOOST_FOREACH(const CTxIn& txin, vin)
910 vWorkQueue.push_back(txin.prevout.hash);
912 // This critsect is OK because txdb is already open
914 LOCK(pwallet->cs_wallet);
915 map<uint256, const CMerkleTx*> mapWalletPrev;
916 set<uint256> setAlreadyDone;
917 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
919 uint256 hash = vWorkQueue[i];
920 if (setAlreadyDone.count(hash))
922 setAlreadyDone.insert(hash);
925 map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
926 if (mi != pwallet->mapWallet.end())
929 BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev)
930 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
932 else if (mapWalletPrev.count(hash))
934 tx = *mapWalletPrev[hash];
936 else if (!fClient && txdb.ReadDiskTx(hash, tx))
942 printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
946 int nDepth = tx.SetMerkleBranch();
947 vtxPrev.push_back(tx);
949 if (nDepth < COPY_DEPTH)
951 BOOST_FOREACH(const CTxIn& txin, tx.vin)
952 vWorkQueue.push_back(txin.prevout.hash);
958 reverse(vtxPrev.begin(), vtxPrev.end());
961 bool CWalletTx::WriteToDisk()
963 return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
966 // Scan the block chain (starting in pindexStart) for transactions
967 // from or to us. If fUpdate is true, found transactions that already
968 // exist in the wallet will be updated.
969 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
973 CBlockIndex* pindex = pindexStart;
979 block.ReadFromDisk(pindex, true);
980 BOOST_FOREACH(CTransaction& tx, block.vtx)
982 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
985 pindex = pindex->pnext;
991 int CWallet::ScanForWalletTransaction(const uint256& hashTx)
994 tx.ReadFromDisk(COutPoint(hashTx, 0));
995 if (AddToWalletIfInvolvingMe(tx, NULL, true, true))
1000 void CWallet::ReacceptWalletTransactions()
1003 bool fRepeat = true;
1008 vector<CDiskTxPos> vMissingTx;
1009 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1011 CWalletTx& wtx = item.second;
1012 if ((wtx.IsCoinBase() && wtx.IsSpent(0)) || (wtx.IsCoinStake() && wtx.IsSpent(1)))
1016 bool fUpdated = false;
1017 if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
1019 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
1020 if (txindex.vSpent.size() != wtx.vout.size())
1022 printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %" PRIszu " != wtx.vout.size() %" PRIszu "\n", txindex.vSpent.size(), wtx.vout.size());
1025 for (unsigned int i = 0; i < txindex.vSpent.size(); i++)
1029 if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i]))
1033 vMissingTx.push_back(txindex.vSpent[i]);
1038 printf("ReacceptWalletTransactions found spent coin %snvc %s\n", FormatMoney(wtx.GetCredit(MINE_ALL)).c_str(), wtx.GetHash().ToString().c_str());
1045 // Re-accept any txes of ours that aren't already in a block
1046 if (!(wtx.IsCoinBase() || wtx.IsCoinStake()))
1047 wtx.AcceptWalletTransaction(txdb, false);
1050 if (!vMissingTx.empty())
1052 // TODO: optimize this to scan just part of the block chain?
1053 if (ScanForWalletTransactions(pindexGenesisBlock))
1054 fRepeat = true; // Found missing transactions: re-do re-accept.
1059 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
1061 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
1063 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
1065 uint256 hash = tx.GetHash();
1066 if (!txdb.ContainsTx(hash))
1067 RelayTransaction((CTransaction)tx, hash);
1070 if (!(IsCoinBase() || IsCoinStake()))
1072 uint256 hash = GetHash();
1073 if (!txdb.ContainsTx(hash))
1075 printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
1076 RelayTransaction((CTransaction)*this, hash);
1081 void CWalletTx::RelayWalletTransaction()
1084 RelayWalletTransaction(txdb);
1087 void CWallet::ResendWalletTransactions()
1089 // Do this infrequently and randomly to avoid giving away
1090 // that these are our transactions.
1091 static int64_t nNextTime;
1092 if (GetTime() < nNextTime)
1094 bool fFirst = (nNextTime == 0);
1095 nNextTime = GetTime() + GetRand(30 * 60);
1099 // Only do it if there's been a new block since last time
1100 static int64_t nLastTime;
1101 if (nTimeBestReceived < nLastTime)
1103 nLastTime = GetTime();
1105 // Rebroadcast any of our txes that aren't in a block yet
1106 printf("ResendWalletTransactions()\n");
1110 // Sort them in chronological order
1111 multimap<unsigned int, CWalletTx*> mapSorted;
1112 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1114 CWalletTx& wtx = item.second;
1115 // Don't rebroadcast until it's had plenty of time that
1116 // it should have gotten in already by now.
1117 if (nTimeBestReceived - (int64_t)wtx.nTimeReceived > 5 * 60)
1118 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
1120 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
1122 CWalletTx& wtx = *item.second;
1123 if (wtx.CheckTransaction())
1124 wtx.RelayWalletTransaction(txdb);
1126 printf("ResendWalletTransactions() : CheckTransaction failed for transaction %s\n", wtx.GetHash().ToString().c_str());
1136 //////////////////////////////////////////////////////////////////////////////
1142 int64_t CWallet::GetBalance() const
1147 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1149 const CWalletTx* pcoin = &(*it).second;
1150 if (pcoin->IsTrusted())
1151 nTotal += pcoin->GetAvailableCredit();
1158 int64_t CWallet::GetWatchOnlyBalance() const
1163 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1165 const CWalletTx* pcoin = &(*it).second;
1166 if (pcoin->IsTrusted())
1167 nTotal += pcoin->GetAvailableWatchCredit();
1174 int64_t CWallet::GetUnconfirmedBalance() const
1179 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1181 const CWalletTx* pcoin = &(*it).second;
1182 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
1183 nTotal += pcoin->GetAvailableCredit();
1189 int64_t CWallet::GetUnconfirmedWatchOnlyBalance() const
1194 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1196 const CWalletTx* pcoin = &(*it).second;
1197 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
1198 nTotal += pcoin->GetAvailableWatchCredit();
1204 int64_t CWallet::GetImmatureBalance() const
1209 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1211 const CWalletTx* pcoin = &(*it).second;
1212 nTotal += pcoin->GetImmatureCredit();
1218 int64_t CWallet::GetImmatureWatchOnlyBalance() const
1223 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1225 const CWalletTx* pcoin = &(*it).second;
1226 nTotal += pcoin->GetImmatureWatchOnlyCredit();
1232 // populate vCoins with vector of spendable COutputs
1233 void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl) const
1239 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1241 const CWalletTx* pcoin = &(*it).second;
1243 if (!pcoin->IsFinal())
1246 if (fOnlyConfirmed && !pcoin->IsTrusted())
1249 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
1252 if(pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0)
1255 for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
1256 isminetype mine = IsMine(pcoin->vout[i]);
1257 if (!(pcoin->IsSpent(i)) && mine != MINE_NO &&
1258 pcoin->vout[i].nValue >= nMinimumInputValue &&
1259 (!coinControl || !coinControl->HasSelected() || coinControl->IsSelected((*it).first, i)))
1261 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain(), mine == MINE_SPENDABLE));
1268 void CWallet::AvailableCoinsMinConf(vector<COutput>& vCoins, int nConf, int64_t nMinValue, int64_t nMaxValue) const
1274 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1276 const CWalletTx* pcoin = &(*it).second;
1278 if (!pcoin->IsFinal())
1281 if(pcoin->GetDepthInMainChain() < nConf)
1284 for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
1285 isminetype mine = IsMine(pcoin->vout[i]);
1287 // ignore coin if it was already spent or we don't own it
1288 if (pcoin->IsSpent(i) || mine == MINE_NO)
1291 // if coin value is between required limits then add new item to vector
1292 if (pcoin->vout[i].nValue >= nMinValue && pcoin->vout[i].nValue < nMaxValue)
1293 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain(), mine == MINE_SPENDABLE));
1299 static void ApproximateBestSubset(vector<pair<int64_t, pair<const CWalletTx*,unsigned int> > >vValue, int64_t nTotalLower, int64_t nTargetValue,
1300 vector<char>& vfBest, int64_t& nBest, int iterations = 1000)
1302 vector<char> vfIncluded;
1304 vfBest.assign(vValue.size(), true);
1305 nBest = nTotalLower;
1307 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
1309 vfIncluded.assign(vValue.size(), false);
1311 bool fReachedTarget = false;
1312 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
1314 for (unsigned int i = 0; i < vValue.size(); i++)
1316 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
1318 nTotal += vValue[i].first;
1319 vfIncluded[i] = true;
1320 if (nTotal >= nTargetValue)
1322 fReachedTarget = true;
1326 vfBest = vfIncluded;
1328 nTotal -= vValue[i].first;
1329 vfIncluded[i] = false;
1337 int64_t CWallet::GetStake() const
1341 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1343 const CWalletTx* pcoin = &(*it).second;
1344 if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1345 nTotal += CWallet::GetCredit(*pcoin, MINE_ALL);
1350 int64_t CWallet::GetWatchOnlyStake() const
1354 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1356 const CWalletTx* pcoin = &(*it).second;
1357 if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1358 nTotal += CWallet::GetCredit(*pcoin, MINE_WATCH_ONLY);
1363 int64_t CWallet::GetNewMint() const
1367 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1369 const CWalletTx* pcoin = &(*it).second;
1370 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1371 nTotal += CWallet::GetCredit(*pcoin, MINE_ALL);
1376 int64_t CWallet::GetWatchOnlyNewMint() const
1380 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1382 const CWalletTx* pcoin = &(*it).second;
1383 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1384 nTotal += CWallet::GetCredit(*pcoin, MINE_WATCH_ONLY);
1389 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
1391 setCoinsRet.clear();
1394 // List of values less than target
1395 pair<int64_t, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
1396 coinLowestLarger.first = std::numeric_limits<int64_t>::max();
1397 coinLowestLarger.second.first = NULL;
1398 vector<pair<int64_t, pair<const CWalletTx*,unsigned int> > > vValue;
1399 int64_t nTotalLower = 0;
1401 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
1403 BOOST_FOREACH(const COutput &output, vCoins)
1405 if (!output.fSpendable)
1408 const CWalletTx *pcoin = output.tx;
1410 if (output.nDepth < (pcoin->IsFromMe(MINE_ALL) ? nConfMine : nConfTheirs))
1415 // Follow the timestamp rules
1416 if (pcoin->nTime > nSpendTime)
1419 int64_t n = pcoin->vout[i].nValue;
1421 pair<int64_t,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1423 if (n == nTargetValue)
1425 setCoinsRet.insert(coin.second);
1426 nValueRet += coin.first;
1429 else if (n < nTargetValue + CENT)
1431 vValue.push_back(coin);
1434 else if (n < coinLowestLarger.first)
1436 coinLowestLarger = coin;
1440 if (nTotalLower == nTargetValue)
1442 for (unsigned int i = 0; i < vValue.size(); ++i)
1444 setCoinsRet.insert(vValue[i].second);
1445 nValueRet += vValue[i].first;
1450 if (nTotalLower < nTargetValue)
1452 if (coinLowestLarger.second.first == NULL)
1454 setCoinsRet.insert(coinLowestLarger.second);
1455 nValueRet += coinLowestLarger.first;
1459 // Solve subset sum by stochastic approximation
1460 sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
1461 vector<char> vfBest;
1464 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);
1465 if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT)
1466 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000);
1468 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
1469 // or the next bigger coin is closer), return the bigger coin
1470 if (coinLowestLarger.second.first &&
1471 ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest))
1473 setCoinsRet.insert(coinLowestLarger.second);
1474 nValueRet += coinLowestLarger.first;
1477 for (unsigned int i = 0; i < vValue.size(); i++)
1480 setCoinsRet.insert(vValue[i].second);
1481 nValueRet += vValue[i].first;
1484 if (fDebug && GetBoolArg("-printpriority"))
1487 printf("SelectCoins() best subset: ");
1488 for (unsigned int i = 0; i < vValue.size(); i++)
1490 printf("%s ", FormatMoney(vValue[i].first).c_str());
1491 printf("total %s\n", FormatMoney(nBest).c_str());
1498 bool CWallet::SelectCoins(int64_t nTargetValue, unsigned int nSpendTime, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64_t& nValueRet, const CCoinControl* coinControl) const
1500 vector<COutput> vCoins;
1501 AvailableCoins(vCoins, true, coinControl);
1503 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
1504 if (coinControl && coinControl->HasSelected())
1506 BOOST_FOREACH(const COutput& out, vCoins)
1510 nValueRet += out.tx->vout[out.i].nValue;
1511 setCoinsRet.insert(make_pair(out.tx, out.i));
1513 return (nValueRet >= nTargetValue);
1516 return (SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 6, vCoins, setCoinsRet, nValueRet) ||
1517 SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 1, vCoins, setCoinsRet, nValueRet) ||
1518 SelectCoinsMinConf(nTargetValue, nSpendTime, 0, 1, vCoins, setCoinsRet, nValueRet));
1521 // Select some coins without random shuffle or best subset approximation
1522 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
1524 vector<COutput> vCoins;
1525 AvailableCoinsMinConf(vCoins, nMinConf, nMinValue, nMaxValue);
1527 setCoinsRet.clear();
1530 BOOST_FOREACH(COutput output, vCoins)
1532 if(!output.fSpendable)
1534 const CWalletTx *pcoin = output.tx;
1537 // Ignore immature coins
1538 if (pcoin->GetBlocksToMaturity() > 0)
1541 // Stop if we've chosen enough inputs
1542 if (nValueRet >= nTargetValue)
1545 // Follow the timestamp rules
1546 if (pcoin->nTime > nSpendTime)
1549 int64_t n = pcoin->vout[i].nValue;
1551 pair<int64_t,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1553 if (n >= nTargetValue)
1555 // If input value is greater or equal to target then simply insert
1556 // it into the current subset and exit
1557 setCoinsRet.insert(coin.second);
1558 nValueRet += coin.first;
1561 else if (n < nTargetValue + CENT)
1563 setCoinsRet.insert(coin.second);
1564 nValueRet += coin.first;
1571 bool CWallet::CreateTransaction(const vector<pair<CScript, int64_t> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl* coinControl)
1574 BOOST_FOREACH (const PAIRTYPE(CScript, int64_t)& s, vecSend)
1580 if (vecSend.empty() || nValue < 0)
1583 wtxNew.BindWallet(this);
1586 LOCK2(cs_main, cs_wallet);
1587 // txdb must be opened before the mapWallet lock
1590 nFeeRet = nTransactionFee;
1594 wtxNew.vout.clear();
1595 wtxNew.fFromMe = true;
1597 int64_t nTotalValue = nValue + nFeeRet;
1598 double dPriority = 0;
1599 // vouts to the payees
1600 BOOST_FOREACH (const PAIRTYPE(CScript, int64_t)& s, vecSend)
1601 wtxNew.vout.push_back(CTxOut(s.second, s.first));
1603 // Choose coins to use
1604 set<pair<const CWalletTx*,unsigned int> > setCoins;
1605 int64_t nValueIn = 0;
1606 if (!SelectCoins(nTotalValue, wtxNew.nTime, setCoins, nValueIn, coinControl))
1608 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1610 int64_t nCredit = pcoin.first->vout[pcoin.second].nValue;
1611 dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
1614 int64_t nChange = nValueIn - nValue - nFeeRet;
1617 // Fill a vout to ourself
1618 // TODO: pass in scriptChange instead of reservekey so
1619 // change transaction isn't always pay-to-bitcoin-address
1620 CScript scriptChange;
1622 // coin control: send change to custom address
1623 if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange))
1624 scriptChange.SetDestination(coinControl->destChange);
1626 // no coin control: send change to newly generated address
1629 // Note: We use a new key here to keep it from being obvious which side is the change.
1630 // The drawback is that by not reusing a previous key, the change may be lost if a
1631 // backup is restored, if the backup doesn't have the new private key for the change.
1632 // If we reused the old key, it would be possible to add code to look for and
1633 // rediscover unknown transactions that were written with keys of ours to recover
1634 // post-backup change.
1636 // Reserve a new key pair from key pool
1637 CPubKey vchPubKey = reservekey.GetReservedKey();
1639 scriptChange.SetDestination(vchPubKey.GetID());
1642 // Insert change txn at random position:
1643 vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
1644 wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
1647 reservekey.ReturnKey();
1650 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1651 wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
1655 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1656 if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
1660 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
1661 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1663 dPriority /= nBytes;
1665 // Check that enough fee is included
1666 bool fAllowFree = CTransaction::AllowFree(dPriority);
1667 int64_t nPayFee = nTransactionFee * (1 + (int64_t)nBytes / 1000);
1668 int64_t nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
1670 if (nFeeRet < max(nPayFee, nMinFee))
1672 nFeeRet = max(nPayFee, nMinFee);
1676 // Fill vtxPrev by copying from previous transactions vtxPrev
1677 wtxNew.AddSupportingTransactions(txdb);
1678 wtxNew.fTimeReceivedIsTxTime = true;
1687 bool CWallet::CreateTransaction(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl* coinControl)
1689 vector< pair<CScript, int64_t> > vecSend;
1690 vecSend.push_back(make_pair(scriptPubKey, nValue));
1691 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, coinControl);
1694 void CWallet::GetStakeWeightFromValue(const int64_t& nTime, const int64_t& nValue, uint64_t& nWeight)
1696 int64_t nTimeWeight = GetWeight(nTime, (int64_t)GetTime());
1698 // If time weight is lower or equal to zero then weight is zero.
1699 if (nTimeWeight <= 0)
1705 CBigNum bnCoinDayWeight = CBigNum(nValue) * nTimeWeight / COIN / (24 * 60 * 60);
1706 nWeight = bnCoinDayWeight.getuint64();
1710 // NovaCoin: get current stake miner statistics
1711 void CWallet::GetStakeStats(float &nKernelsRate, float &nCoinDaysRate)
1713 static uint64_t nLastKernels = 0, nLastCoinDays = 0;
1714 static float nLastKernelsRate = 0, nLastCoinDaysRate = 0;
1715 static int64_t nLastTime = GetTime();
1717 if (nKernelsTried < nLastKernels)
1722 nLastTime = GetTime();
1725 int64_t nInterval = GetTime() - nLastTime;
1726 //if (nKernelsTried > 1000 && nInterval > 5)
1729 nKernelsRate = nLastKernelsRate = ( nKernelsTried - nLastKernels ) / (float) nInterval;
1730 nCoinDaysRate = nLastCoinDaysRate = ( nCoinDaysTried - nLastCoinDays ) / (float) nInterval;
1732 nLastKernels = nKernelsTried;
1733 nLastCoinDays = nCoinDaysTried;
1734 nLastTime = GetTime();
1738 nKernelsRate = nLastKernelsRate;
1739 nCoinDaysRate = nLastCoinDaysRate;
1743 bool CWallet::MergeCoins(const int64_t& nAmount, const int64_t& nMinValue, const int64_t& nOutputValue, list<uint256>& listMerged)
1745 int64_t nBalance = GetBalance();
1747 if (nAmount > nBalance)
1751 int64_t nValueIn = 0;
1752 set<pair<const CWalletTx*,unsigned int> > setCoins;
1754 // Simple coins selection - no randomization
1755 if (!SelectCoinsSimple(nAmount, nMinValue, nOutputValue, GetTime(), 1, setCoins, nValueIn))
1758 if (setCoins.empty())
1762 vector<const CWalletTx*> vwtxPrev;
1764 // Reserve a new key pair from key pool
1765 CReserveKey reservekey(this);
1766 CPubKey vchPubKey = reservekey.GetReservedKey();
1769 CScript scriptOutput;
1770 scriptOutput.SetDestination(vchPubKey.GetID());
1773 wtxNew.vout.push_back(CTxOut(0, scriptOutput));
1776 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1778 int64_t nCredit = pcoin.first->vout[pcoin.second].nValue;
1780 // Add current coin to inputs list and add its credit to transaction output
1781 wtxNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1782 wtxNew.vout[0].nValue += nCredit;
1783 vwtxPrev.push_back(pcoin.first);
1786 // Replaced with estimation for performance purposes
1788 for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
1789 const CWalletTx *txin = vwtxPrev[i];
1791 // Sign scripts to get actual transaction size for fee calculation
1792 if (!SignSignature(*this, *txin, wtxNew, i))
1797 // Assuming that average scriptsig size is 110 bytes
1798 int64_t nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION) + wtxNew.vin.size() * 110;
1799 dWeight += (double)nCredit * pcoin.first->GetDepthInMainChain();
1801 double dFinalPriority = dWeight /= nBytes;
1802 bool fAllowFree = CTransaction::AllowFree(dFinalPriority);
1804 // Get actual transaction fee according to its estimated size and priority
1805 int64_t nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
1807 // Prepare transaction for commit if sum is enough ot its size is too big
1808 if (nBytes >= MAX_BLOCK_SIZE_GEN/6 || wtxNew.vout[0].nValue >= nOutputValue)
1810 wtxNew.vout[0].nValue -= nMinFee; // Set actual fee
1812 for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
1813 const CWalletTx *txin = vwtxPrev[i];
1816 if (!SignSignature(*this, *txin, wtxNew, i))
1820 // Try to commit, return false on failure
1821 if (!CommitTransaction(wtxNew, reservekey))
1824 listMerged.push_back(wtxNew.GetHash()); // Add to hashes list
1826 dWeight = 0; // Reset all temporary values
1829 wtxNew.vout.push_back(CTxOut(0, scriptOutput));
1833 // Create transactions if there are some unhandled coins left
1834 if (wtxNew.vout[0].nValue > 0) {
1835 int64_t nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION) + wtxNew.vin.size() * 110;
1837 double dFinalPriority = dWeight /= nBytes;
1838 bool fAllowFree = CTransaction::AllowFree(dFinalPriority);
1840 // Get actual transaction fee according to its size and priority
1841 int64_t nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
1843 wtxNew.vout[0].nValue -= nMinFee; // Set actual fee
1845 if (wtxNew.vout[0].nValue <= 0)
1848 for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
1849 const CWalletTx *txin = vwtxPrev[i];
1851 // Sign all scripts again
1852 if (!SignSignature(*this, *txin, wtxNew, i))
1856 // Try to commit, return false on failure
1857 if (!CommitTransaction(wtxNew, reservekey))
1860 listMerged.push_back(wtxNew.GetHash()); // Add to hashes list
1867 bool CWallet::CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, uint32_t nSearchInterval, CTransaction& txNew, CKey& key)
1869 // The following combine threshold is important to security
1870 // Should not be adjusted if you don't understand the consequences
1871 int64_t nCombineThreshold = GetProofOfWorkReward(GetLastBlockIndex(pindexBest, false)->nBits) / 3;
1873 CBigNum bnTargetPerCoinDay;
1874 bnTargetPerCoinDay.SetCompact(nBits);
1879 // Mark coin stake transaction
1880 CScript scriptEmpty;
1881 scriptEmpty.clear();
1882 txNew.vout.push_back(CTxOut(0, scriptEmpty));
1884 // Choose coins to use
1885 int64_t nBalance = GetBalance();
1886 int64_t nReserveBalance = 0;
1888 if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
1889 return error("CreateCoinStake : invalid reserve balance amount");
1891 if (nBalance <= nReserveBalance)
1894 vector<const CWalletTx*> vwtxPrev;
1898 LOCK2(cs_main, cs_wallet);
1899 // Cache outputs unless best block or wallet transaction set changed
1900 if (!fCoinsDataActual)
1903 int64_t nValueIn = 0;
1905 if (!SelectCoinsSimple(nBalance - nReserveBalance, MIN_TX_FEE, MAX_MONEY, txNew.nTime, nCoinbaseMaturity * 10, setCoins, nValueIn))
1908 if (setCoins.empty())
1914 for(CoinsSet::iterator pcoin = setCoins.begin(); pcoin != setCoins.end(); pcoin++)
1916 // Load transaction index item
1917 if (!txdb.ReadTxIndex(pcoin->first->GetHash(), txindex))
1920 // Read block header
1921 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
1924 uint64_t nStakeModifier = 0;
1925 if (!GetKernelStakeModifier(block.GetHash(), nStakeModifier))
1929 // (txid, vout.n) => ((txindex, (tx, vout.n)), (block, modifier))
1930 mapMeta[make_pair(pcoin->first->GetHash(), pcoin->second)] = make_pair(make_pair(txindex, *pcoin), make_pair(block, nStakeModifier));
1933 printf("Load coin: %s\n", pcoin->first->GetHash().GetHex().c_str());
1938 printf("Stake miner: %" PRIszu " meta items loaded for %" PRIszu " coins\n", mapMeta.size(), setCoins.size());
1940 fCoinsDataActual = true;
1946 int64_t nCredit = 0;
1947 CScript scriptPubKeyKernel;
1949 unsigned int nTimeTx, nBlockTime;
1950 COutPoint prevoutStake;
1951 CoinsSet::value_type kernelcoin;
1953 if (ScanForStakeKernelHash(mapMeta, nBits, txNew.nTime, nSearchInterval, kernelcoin, nTimeTx, nBlockTime, nKernelsTried, nCoinDaysTried))
1956 if (fDebug && GetBoolArg("-printcoinstake"))
1957 printf("CreateCoinStake : kernel found\n");
1958 vector<valtype> vSolutions;
1959 txnouttype whichType;
1960 CScript scriptPubKeyOut;
1961 scriptPubKeyKernel = kernelcoin.first->vout[kernelcoin.second].scriptPubKey;
1962 if (!Solver(scriptPubKeyKernel, whichType, vSolutions))
1964 if (fDebug && GetBoolArg("-printcoinstake"))
1965 printf("CreateCoinStake : failed to parse kernel\n");
1968 if (fDebug && GetBoolArg("-printcoinstake"))
1969 printf("CreateCoinStake : parsed kernel type=%d\n", whichType);
1970 if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH)
1972 if (fDebug && GetBoolArg("-printcoinstake"))
1973 printf("CreateCoinStake : no support for kernel type=%d\n", whichType);
1974 return false; // only support pay to public key and pay to address
1976 if (whichType == TX_PUBKEYHASH) // pay to address type
1978 // convert to pay to public key type
1979 if (!keystore.GetKey(uint160(vSolutions[0]), key))
1981 if (fDebug && GetBoolArg("-printcoinstake"))
1982 printf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1983 return false; // unable to find corresponding public key
1985 scriptPubKeyOut << key.GetPubKey() << OP_CHECKSIG;
1987 if (whichType == TX_PUBKEY)
1989 valtype& vchPubKey = vSolutions[0];
1990 if (!keystore.GetKey(Hash160(vchPubKey), key))
1992 if (fDebug && GetBoolArg("-printcoinstake"))
1993 printf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1994 return false; // unable to find corresponding public key
1996 if (key.GetPubKey() != vchPubKey)
1998 if (fDebug && GetBoolArg("-printcoinstake"))
1999 printf("CreateCoinStake : invalid key for kernel type=%d\n", whichType);
2000 return false; // keys mismatch
2003 scriptPubKeyOut = scriptPubKeyKernel;
2006 txNew.nTime = nTimeTx;
2007 txNew.vin.push_back(CTxIn(kernelcoin.first->GetHash(), kernelcoin.second));
2008 nCredit += kernelcoin.first->vout[kernelcoin.second].nValue;
2009 vwtxPrev.push_back(kernelcoin.first);
2010 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
2012 if (GetWeight((int64_t)nBlockTime, (int64_t)txNew.nTime) < nStakeMaxAge)
2013 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut)); //split stake
2014 if (fDebug && GetBoolArg("-printcoinstake"))
2015 printf("CreateCoinStake : added kernel type=%d\n", whichType);
2018 if (nCredit == 0 || nCredit > nBalance - nReserveBalance)
2021 // (txid, vout.n) => ((txindex, (tx, vout.n)), (block, modifier))
2022 for(MetaMap::const_iterator meta_item = mapMeta.begin(); meta_item != mapMeta.end(); meta_item++)
2025 CoinsSet::value_type pcoin = meta_item->second.first.second;
2027 // Attempt to add more inputs
2028 // Only add coins of the same key/address as kernel
2029 if (txNew.vout.size() == 2 && ((pcoin.first->vout[pcoin.second].scriptPubKey == scriptPubKeyKernel || pcoin.first->vout[pcoin.second].scriptPubKey == txNew.vout[1].scriptPubKey))
2030 && pcoin.first->GetHash() != txNew.vin[0].prevout.hash)
2032 int64_t nTimeWeight = GetWeight((int64_t)pcoin.first->nTime, (int64_t)txNew.nTime);
2034 // Stop adding more inputs if already too many inputs
2035 if (txNew.vin.size() >= 100)
2037 // Stop adding more inputs if value is already pretty significant
2038 if (nCredit > nCombineThreshold)
2040 // Stop adding inputs if reached reserve limit
2041 if (nCredit + pcoin.first->vout[pcoin.second].nValue > nBalance - nReserveBalance)
2043 // Do not add additional significant input
2044 if (pcoin.first->vout[pcoin.second].nValue > nCombineThreshold)
2046 // Do not add input that is still too young
2047 if (nTimeWeight < nStakeMaxAge)
2050 txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
2051 nCredit += pcoin.first->vout[pcoin.second].nValue;
2052 vwtxPrev.push_back(pcoin.first);
2056 // Calculate coin age reward
2060 if (!txNew.GetCoinAge(txdb, nCoinAge))
2061 return error("CreateCoinStake : failed to calculate coin age");
2063 int64_t nReward = GetProofOfStakeReward(nCoinAge, nBits, txNew.nTime);
2064 // Refuse to create mint that has zero or negative reward
2071 int64_t nMinFee = 0;
2074 // Set output amount
2075 if (txNew.vout.size() == 3)
2077 txNew.vout[1].nValue = ((nCredit - nMinFee) / 2 / CENT) * CENT;
2078 txNew.vout[2].nValue = nCredit - nMinFee - txNew.vout[1].nValue;
2081 txNew.vout[1].nValue = nCredit - nMinFee;
2085 BOOST_FOREACH(const CWalletTx* pcoin, vwtxPrev)
2087 if (!SignSignature(*this, *pcoin, txNew, nIn++))
2088 return error("CreateCoinStake : failed to sign coinstake");
2092 unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION);
2093 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
2094 return error("CreateCoinStake : exceeded coinstake size limit");
2096 // Check enough fee is paid
2097 if (nMinFee < txNew.GetMinFee(1, false, GMF_BLOCK, nBytes) - CENT)
2099 nMinFee = txNew.GetMinFee(1, false, GMF_BLOCK, nBytes) - CENT;
2100 continue; // try signing again
2104 if (fDebug && GetBoolArg("-printfee"))
2105 printf("CreateCoinStake : fee for coinstake %s\n", FormatMoney(nMinFee).c_str());
2110 // Successfully generated coinstake
2115 // Call after CreateTransaction unless you want to abort
2116 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
2119 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
2121 // Track how many getdata requests our transaction gets
2122 mapRequestCount[wtxNew.GetHash()] = 0;
2124 // Try to broadcast before saving
2125 if (!wtxNew.AcceptToMemoryPool())
2127 // This must not fail. The transaction has already been signed.
2128 printf("CommitTransaction() : Error: Transaction not valid");
2132 wtxNew.RelayWalletTransaction();
2135 LOCK2(cs_main, cs_wallet);
2137 // This is only to keep the database open to defeat the auto-flush for the
2138 // duration of this scope. This is the only place where this optimization
2139 // maybe makes sense; please don't do it anywhere else.
2140 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
2142 // Take key pair from key pool so it won't be used again
2143 reservekey.KeepKey();
2145 // Add tx to wallet, because if it has change it's also ours,
2146 // otherwise just for transaction history.
2147 AddToWallet(wtxNew);
2149 // Mark old coins as spent
2150 set<CWalletTx*> setCoins;
2151 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
2153 CWalletTx &coin = mapWallet[txin.prevout.hash];
2154 coin.BindWallet(this);
2155 coin.MarkSpent(txin.prevout.n);
2157 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
2158 vMintingWalletUpdated.push_back(coin.GetHash());
2171 string CWallet::SendMoney(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, bool fAskFee)
2173 CReserveKey reservekey(this);
2174 int64_t nFeeRequired;
2178 string strError = _("Error: Wallet locked, unable to create transaction ");
2179 printf("SendMoney() : %s", strError.c_str());
2182 if (fWalletUnlockMintOnly)
2184 string strError = _("Error: Wallet unlocked for block minting only, unable to create transaction.");
2185 printf("SendMoney() : %s", strError.c_str());
2188 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
2191 if (nValue + nFeeRequired > GetBalance())
2192 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());
2194 strError = _("Error: Transaction creation failed ");
2195 printf("SendMoney() : %s", strError.c_str());
2199 if (fAskFee && !uiInterface.ThreadSafeAskFee(nFeeRequired, _("Sending...")))
2202 if (!CommitTransaction(wtxNew, reservekey))
2203 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.");
2210 string CWallet::SendMoneyToDestination(const CTxDestination& address, int64_t nValue, CWalletTx& wtxNew, bool fAskFee)
2214 return _("Invalid amount");
2215 if (nValue + nTransactionFee > GetBalance())
2216 return _("Insufficient funds");
2218 // Parse Bitcoin address
2219 CScript scriptPubKey;
2220 scriptPubKey.SetDestination(address);
2222 return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
2228 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
2232 fFirstRunRet = false;
2233 DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
2234 if (nLoadWalletRet == DB_NEED_REWRITE)
2236 if (CDB::Rewrite(strWalletFile, "\x04pool"))
2239 // Note: can't top-up keypool here, because wallet is locked.
2240 // User will be prompted to unlock wallet the next operation
2241 // the requires a new key.
2245 if (nLoadWalletRet != DB_LOAD_OK)
2246 return nLoadWalletRet;
2247 fFirstRunRet = !vchDefaultKey.IsValid();
2249 NewThread(ThreadFlushWalletDB, &strWalletFile);
2254 bool CWallet::SetAddressBookName(const CTxDestination& address, const string& strName)
2256 std::map<CTxDestination, std::string>::iterator mi = mapAddressBook.find(address);
2257 mapAddressBook[address] = strName;
2258 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address), (mi == mapAddressBook.end()) ? CT_NEW : CT_UPDATED);
2261 return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName);
2264 bool CWallet::DelAddressBookName(const CTxDestination& address)
2266 mapAddressBook.erase(address);
2267 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address), CT_DELETED);
2270 return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString());
2274 void CWallet::PrintWallet(const CBlock& block)
2278 if (block.IsProofOfStake() && mapWallet.count(block.vtx[1].GetHash()))
2280 CWalletTx& wtx = mapWallet[block.vtx[1].GetHash()];
2281 printf(" PoS: %d %d %" PRId64 "", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit(MINE_ALL));
2283 else if (mapWallet.count(block.vtx[0].GetHash()))
2285 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
2286 printf(" PoW: %d %d %" PRId64 "", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit(MINE_ALL));
2292 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
2296 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
2297 if (mi != mapWallet.end())
2306 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
2310 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
2313 vchDefaultKey = vchPubKey;
2317 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
2319 if (!pwallet->fFileBacked)
2321 strWalletFileOut = pwallet->strWalletFile;
2326 // Mark old keypool keys as used,
2327 // and generate all new keys
2329 bool CWallet::NewKeyPool(unsigned int nSize)
2333 CWalletDB walletdb(strWalletFile);
2334 BOOST_FOREACH(int64_t nIndex, setKeyPool)
2335 walletdb.ErasePool(nIndex);
2345 nKeys = max<uint64_t>(GetArg("-keypool", 100), 0);
2347 for (uint64_t i = 0; i < nKeys; i++)
2349 uint64_t nIndex = i+1;
2350 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
2351 setKeyPool.insert(nIndex);
2353 printf("CWallet::NewKeyPool wrote %" PRIu64 " new keys\n", nKeys);
2358 bool CWallet::TopUpKeyPool(unsigned int nSize)
2366 CWalletDB walletdb(strWalletFile);
2369 uint64_t nTargetSize;
2371 nTargetSize = nSize;
2373 nTargetSize = max<uint64_t>(GetArg("-keypool", 100), 0);
2375 while (setKeyPool.size() < (nTargetSize + 1))
2378 if (!setKeyPool.empty())
2379 nEnd = *(--setKeyPool.end()) + 1;
2380 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
2381 throw runtime_error("TopUpKeyPool() : writing generated key failed");
2382 setKeyPool.insert(nEnd);
2383 printf("keypool added key %" PRIu64 ", size=%" PRIszu "\n", nEnd, setKeyPool.size());
2389 void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool)
2392 keypool.vchPubKey = CPubKey();
2399 // Get the oldest key
2400 if(setKeyPool.empty())
2403 CWalletDB walletdb(strWalletFile);
2405 nIndex = *(setKeyPool.begin());
2406 setKeyPool.erase(setKeyPool.begin());
2407 if (!walletdb.ReadPool(nIndex, keypool))
2408 throw runtime_error("ReserveKeyFromKeyPool() : read failed");
2409 if (!HaveKey(keypool.vchPubKey.GetID()))
2410 throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
2411 assert(keypool.vchPubKey.IsValid());
2412 if (fDebug && GetBoolArg("-printkeypool"))
2413 printf("keypool reserve %" PRId64 "\n", nIndex);
2417 int64_t CWallet::AddReserveKey(const CKeyPool& keypool)
2420 LOCK2(cs_main, cs_wallet);
2421 CWalletDB walletdb(strWalletFile);
2423 int64_t nIndex = 1 + *(--setKeyPool.end());
2424 if (!walletdb.WritePool(nIndex, keypool))
2425 throw runtime_error("AddReserveKey() : writing added key failed");
2426 setKeyPool.insert(nIndex);
2432 void CWallet::KeepKey(int64_t nIndex)
2434 // Remove from key pool
2437 CWalletDB walletdb(strWalletFile);
2438 walletdb.ErasePool(nIndex);
2441 printf("keypool keep %" PRId64 "\n", nIndex);
2444 void CWallet::ReturnKey(int64_t nIndex)
2446 // Return to key pool
2449 setKeyPool.insert(nIndex);
2452 printf("keypool return %" PRId64 "\n", nIndex);
2455 bool CWallet::GetKeyFromPool(CPubKey& result, bool fAllowReuse)
2461 ReserveKeyFromKeyPool(nIndex, keypool);
2464 if (fAllowReuse && vchDefaultKey.IsValid())
2466 result = vchDefaultKey;
2469 if (IsLocked()) return false;
2470 result = GenerateNewKey();
2474 result = keypool.vchPubKey;
2479 int64_t CWallet::GetOldestKeyPoolTime()
2483 ReserveKeyFromKeyPool(nIndex, keypool);
2487 return keypool.nTime;
2490 std::map<CTxDestination, int64_t> CWallet::GetAddressBalances()
2492 map<CTxDestination, int64_t> balances;
2496 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2498 CWalletTx *pcoin = &walletEntry.second;
2500 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
2503 if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0)
2506 int nDepth = pcoin->GetDepthInMainChain();
2507 if (nDepth < (pcoin->IsFromMe(MINE_ALL) ? 0 : 1))
2510 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2512 CTxDestination addr;
2513 if (!IsMine(pcoin->vout[i]))
2515 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr))
2518 int64_t n = pcoin->IsSpent(i) ? 0 : pcoin->vout[i].nValue;
2520 if (!balances.count(addr))
2522 balances[addr] += n;
2530 set< set<CTxDestination> > CWallet::GetAddressGroupings()
2532 set< set<CTxDestination> > groupings;
2533 set<CTxDestination> grouping;
2535 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2537 CWalletTx *pcoin = &walletEntry.second;
2539 if (pcoin->vin.size() > 0 && IsMine(pcoin->vin[0]))
2541 // group all input addresses with each other
2542 BOOST_FOREACH(CTxIn txin, pcoin->vin)
2544 CTxDestination address;
2545 if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
2547 grouping.insert(address);
2550 // group change with input addresses
2551 BOOST_FOREACH(CTxOut txout, pcoin->vout)
2552 if (IsChange(txout))
2554 CWalletTx tx = mapWallet[pcoin->vin[0].prevout.hash];
2555 CTxDestination txoutAddr;
2556 if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
2558 grouping.insert(txoutAddr);
2560 groupings.insert(grouping);
2564 // group lone addrs by themselves
2565 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2566 if (IsMine(pcoin->vout[i]))
2568 CTxDestination address;
2569 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address))
2571 grouping.insert(address);
2572 groupings.insert(grouping);
2577 set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
2578 map< CTxDestination, set<CTxDestination>* > setmap; // map addresses to the unique group containing it
2579 BOOST_FOREACH(set<CTxDestination> grouping, groupings)
2581 // make a set of all the groups hit by this new group
2582 set< set<CTxDestination>* > hits;
2583 map< CTxDestination, set<CTxDestination>* >::iterator it;
2584 BOOST_FOREACH(CTxDestination address, grouping)
2585 if ((it = setmap.find(address)) != setmap.end())
2586 hits.insert((*it).second);
2588 // merge all hit groups into a new single group and delete old groups
2589 set<CTxDestination>* merged = new set<CTxDestination>(grouping);
2590 BOOST_FOREACH(set<CTxDestination>* hit, hits)
2592 merged->insert(hit->begin(), hit->end());
2593 uniqueGroupings.erase(hit);
2596 uniqueGroupings.insert(merged);
2599 BOOST_FOREACH(CTxDestination element, *merged)
2600 setmap[element] = merged;
2603 set< set<CTxDestination> > ret;
2604 BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings)
2606 ret.insert(*uniqueGrouping);
2607 delete uniqueGrouping;
2613 // ppcoin: check 'spent' consistency between wallet and txindex
2614 // ppcoin: fix wallet spent state according to txindex
2615 void CWallet::FixSpentCoins(int& nMismatchFound, int64_t& nBalanceInQuestion, bool fCheckOnly)
2618 nBalanceInQuestion = 0;
2621 vector<CWalletTx*> vCoins;
2622 vCoins.reserve(mapWallet.size());
2623 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2624 vCoins.push_back(&(*it).second);
2627 BOOST_FOREACH(CWalletTx* pcoin, vCoins)
2629 // Find the corresponding transaction index
2631 if (!txdb.ReadTxIndex(pcoin->GetHash(), txindex))
2633 for (unsigned int n=0; n < pcoin->vout.size(); n++)
2635 if (IsMine(pcoin->vout[n]) && pcoin->IsSpent(n) && (txindex.vSpent.size() <= n || txindex.vSpent[n].IsNull()))
2637 printf("FixSpentCoins found lost coin %sppc %s[%d], %s\n",
2638 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2640 nBalanceInQuestion += pcoin->vout[n].nValue;
2643 pcoin->MarkUnspent(n);
2644 pcoin->WriteToDisk();
2647 else if (IsMine(pcoin->vout[n]) && !pcoin->IsSpent(n) && (txindex.vSpent.size() > n && !txindex.vSpent[n].IsNull()))
2649 printf("FixSpentCoins found spent coin %sppc %s[%d], %s\n",
2650 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2652 nBalanceInQuestion += pcoin->vout[n].nValue;
2655 pcoin->MarkSpent(n);
2656 pcoin->WriteToDisk();
2662 if(IsMine((CTransaction)*pcoin) && (pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetDepthInMainChain() == 0)
2664 printf("FixSpentCoins %s tx %s\n", fCheckOnly ? "found" : "removed", pcoin->GetHash().ToString().c_str());
2667 EraseFromWallet(pcoin->GetHash());
2673 // ppcoin: disable transaction (only for coinstake)
2674 void CWallet::DisableTransaction(const CTransaction &tx)
2676 if (!tx.IsCoinStake() || !IsFromMe(tx))
2677 return; // only disconnecting coinstake requires marking input unspent
2680 BOOST_FOREACH(const CTxIn& txin, tx.vin)
2682 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
2683 if (mi != mapWallet.end())
2685 CWalletTx& prev = (*mi).second;
2686 if (txin.prevout.n < prev.vout.size() && IsMine(prev.vout[txin.prevout.n]))
2688 prev.MarkUnspent(txin.prevout.n);
2695 CPubKey CReserveKey::GetReservedKey()
2700 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
2702 vchPubKey = keypool.vchPubKey;
2705 printf("CReserveKey::GetReservedKey(): Warning: Using default key instead of a new key, top up your keypool!");
2706 vchPubKey = pwallet->vchDefaultKey;
2709 assert(vchPubKey.IsValid());
2713 void CReserveKey::KeepKey()
2716 pwallet->KeepKey(nIndex);
2718 vchPubKey = CPubKey();
2721 void CReserveKey::ReturnKey()
2724 pwallet->ReturnKey(nIndex);
2726 vchPubKey = CPubKey();
2729 void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
2733 CWalletDB walletdb(strWalletFile);
2735 LOCK2(cs_main, cs_wallet);
2736 BOOST_FOREACH(const int64_t& id, setKeyPool)
2739 if (!walletdb.ReadPool(id, keypool))
2740 throw runtime_error("GetAllReserveKeyHashes() : read failed");
2741 assert(keypool.vchPubKey.IsValid());
2742 CKeyID keyID = keypool.vchPubKey.GetID();
2743 if (!HaveKey(keyID))
2744 throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
2745 setAddress.insert(keyID);
2749 void CWallet::UpdatedTransaction(const uint256 &hashTx)
2753 // Only notify UI if this transaction is in this wallet
2754 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
2755 if (mi != mapWallet.end())
2757 NotifyTransactionChanged(this, hashTx, CT_UPDATED);
2758 vMintingWalletUpdated.push_back(hashTx);
2763 void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const {
2764 mapKeyBirth.clear();
2766 // get birth times for keys with metadata
2767 for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++)
2768 if (it->second.nCreateTime)
2769 mapKeyBirth[it->first] = it->second.nCreateTime;
2771 // map in which we'll infer heights of other keys
2772 CBlockIndex *pindexMax = FindBlockByHeight(std::max(0, nBestHeight - 144)); // the tip can be reorganised; use a 144-block safety margin
2773 std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
2774 std::set<CKeyID> setKeys;
2776 BOOST_FOREACH(const CKeyID &keyid, setKeys) {
2777 if (mapKeyBirth.count(keyid) == 0)
2778 mapKeyFirstBlock[keyid] = pindexMax;
2782 // if there are no such keys, we're done
2783 if (mapKeyFirstBlock.empty())
2786 // find first block that affects those keys, if there are any left
2787 std::vector<CKeyID> vAffected;
2788 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
2789 // iterate over all wallet transactions...
2790 const CWalletTx &wtx = (*it).second;
2791 std::map<uint256, CBlockIndex*>::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
2792 if (blit != mapBlockIndex.end() && blit->second->IsInMainChain()) {
2793 // ... which are already in a block
2794 int nHeight = blit->second->nHeight;
2795 BOOST_FOREACH(const CTxOut &txout, wtx.vout) {
2796 // iterate over all their outputs
2797 ::ExtractAffectedKeys(*this, txout.scriptPubKey, vAffected);
2798 BOOST_FOREACH(const CKeyID &keyid, vAffected) {
2799 // ... and all their affected keys
2800 std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
2801 if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
2802 rit->second = blit->second;
2809 // Extract block timestamps for those keys
2810 for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
2811 mapKeyBirth[it->first] = it->second->nTime - 7200; // block times can be 2h off
2814 void CWallet::ClearOrphans()
2816 list<uint256> orphans;
2819 for(map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2821 const CWalletTx *wtx = &(*it).second;
2822 if((wtx->IsCoinBase() || wtx->IsCoinStake()) && !wtx->IsInMainChain())
2824 orphans.push_back(wtx->GetHash());
2828 for(list<uint256>::const_iterator it = orphans.begin(); it != orphans.end(); ++it)
2829 EraseFromWallet(*it);