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 //////////////////////////////////////////////////////////////////////////////
24 struct CompareValueOnly
26 bool operator()(const pair<int64, pair<const CWalletTx*, unsigned int> >& t1,
27 const pair<int64, pair<const CWalletTx*, unsigned int> >& t2) const
29 return t1.first < t2.first;
33 CPubKey CWallet::GenerateNewKey()
35 bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
39 key.MakeNewKey(fCompressed);
41 // Compressed public keys were introduced in version 0.6.0
43 SetMinVersion(FEATURE_COMPRPUBKEY);
45 CPubKey pubkey = key.GetPubKey();
47 // Create new metadata
48 int64 nCreationTime = GetTime();
49 mapKeyMetadata[pubkey.GetID()] = CKeyMetadata(nCreationTime);
50 if (!nTimeFirstKey || nCreationTime < nTimeFirstKey)
51 nTimeFirstKey = nCreationTime;
54 throw std::runtime_error("CWallet::GenerateNewKey() : AddKey failed");
55 return key.GetPubKey();
58 bool CWallet::AddKey(const CKey& key)
60 CPubKey pubkey = key.GetPubKey();
62 if (!CCryptoKeyStore::AddKey(key))
67 return CWalletDB(strWalletFile).WriteKey(pubkey, key.GetPrivKey(), mapKeyMetadata[pubkey.GetID()]);
71 bool CWallet::AddCryptedKey(const CPubKey &vchPubKey, const vector<unsigned char> &vchCryptedSecret)
73 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
79 if (pwalletdbEncryption)
80 return pwalletdbEncryption->WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]);
82 return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]);
87 bool CWallet::LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &meta)
89 if (meta.nCreateTime && (!nTimeFirstKey || meta.nCreateTime < nTimeFirstKey))
90 nTimeFirstKey = meta.nCreateTime;
92 mapKeyMetadata[pubkey.GetID()] = meta;
96 bool CWallet::AddCScript(const CScript& redeemScript)
98 if (!CCryptoKeyStore::AddCScript(redeemScript))
102 return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript);
105 // ppcoin: optional setting to unlock wallet for block minting only;
106 // serves to disable the trivial sendmoney when OS account compromised
107 bool fWalletUnlockMintOnly = false;
109 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
115 CKeyingMaterial vMasterKey;
119 BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
121 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
123 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
125 if (CCryptoKeyStore::Unlock(vMasterKey))
132 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
134 bool fWasLocked = IsLocked();
141 CKeyingMaterial vMasterKey;
142 BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
144 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
146 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
148 if (CCryptoKeyStore::Unlock(vMasterKey))
150 int64 nStartTime = GetTimeMillis();
151 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
152 pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
154 nStartTime = GetTimeMillis();
155 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
156 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
158 if (pMasterKey.second.nDeriveIterations < 25000)
159 pMasterKey.second.nDeriveIterations = 25000;
161 printf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
163 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
165 if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
167 CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
178 void CWallet::SetBestChain(const CBlockLocator& loc)
180 CWalletDB walletdb(strWalletFile);
181 walletdb.WriteBestBlock(loc);
184 // This class implements an addrIncoming entry that causes pre-0.4
185 // clients to crash on startup if reading a private-key-encrypted wallet.
186 class CCorruptAddress
191 if (nType & SER_DISK)
196 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
198 if (nWalletVersion >= nVersion)
201 // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
202 if (fExplicit && nVersion > nWalletMaxVersion)
203 nVersion = FEATURE_LATEST;
205 nWalletVersion = nVersion;
207 if (nVersion > nWalletMaxVersion)
208 nWalletMaxVersion = nVersion;
212 CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile);
213 if (nWalletVersion >= 40000)
215 // Versions prior to 0.4.0 did not support the "minversion" record.
216 // Use a CCorruptAddress to make them crash instead.
217 CCorruptAddress corruptAddress;
218 pwalletdb->WriteSetting("addrIncoming", corruptAddress);
220 if (nWalletVersion > 40000)
221 pwalletdb->WriteMinVersion(nWalletVersion);
229 bool CWallet::SetMaxVersion(int nVersion)
231 // cannot downgrade below current version
232 if (nWalletVersion > nVersion)
235 nWalletMaxVersion = nVersion;
240 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
245 CKeyingMaterial vMasterKey;
246 RandAddSeedPerfmon();
248 vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
249 RAND_bytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
251 CMasterKey kMasterKey(nDerivationMethodIndex);
253 RandAddSeedPerfmon();
254 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
255 RAND_bytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
258 int64 nStartTime = GetTimeMillis();
259 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
260 kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
262 nStartTime = GetTimeMillis();
263 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
264 kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
266 if (kMasterKey.nDeriveIterations < 25000)
267 kMasterKey.nDeriveIterations = 25000;
269 printf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
271 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
273 if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
278 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
281 pwalletdbEncryption = new CWalletDB(strWalletFile);
282 if (!pwalletdbEncryption->TxnBegin())
284 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
287 if (!EncryptKeys(vMasterKey))
290 pwalletdbEncryption->TxnAbort();
291 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.
294 // Encryption was introduced in version 0.4.0
295 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
299 if (!pwalletdbEncryption->TxnCommit())
300 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.
302 delete pwalletdbEncryption;
303 pwalletdbEncryption = NULL;
307 Unlock(strWalletPassphrase);
311 // Need to completely rewrite the wallet file; if we don't, bdb might keep
312 // bits of the unencrypted private key in slack space in the database file.
313 CDB::Rewrite(strWalletFile);
316 NotifyStatusChanged(this);
321 int64 CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
323 int64 nRet = nOrderPosNext++;
325 pwalletdb->WriteOrderPosNext(nOrderPosNext);
327 CWalletDB(strWalletFile).WriteOrderPosNext(nOrderPosNext);
332 CWallet::TxItems CWallet::OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount)
334 CWalletDB walletdb(strWalletFile);
336 // First: get all CWalletTx and CAccountingEntry into a sorted-by-order multimap.
339 // Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry
340 // would make this much faster for applications that do this a lot.
341 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
343 CWalletTx* wtx = &((*it).second);
344 txOrdered.insert(make_pair(wtx->nOrderPos, TxPair(wtx, (CAccountingEntry*)0)));
347 walletdb.ListAccountCreditDebit(strAccount, acentries);
348 BOOST_FOREACH(CAccountingEntry& entry, acentries)
350 txOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
356 void CWallet::WalletUpdateSpent(const CTransaction &tx, bool fBlock)
358 // Anytime a signature is successfully verified, it's proof the outpoint is spent.
359 // Update the wallet spent flag if it doesn't know due to wallet.dat being
360 // restored from backup or the user making copies of wallet.dat.
363 BOOST_FOREACH(const CTxIn& txin, tx.vin)
365 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
366 if (mi != mapWallet.end())
368 CWalletTx& wtx = (*mi).second;
369 if (txin.prevout.n >= wtx.vout.size())
370 printf("WalletUpdateSpent: bad wtx %s\n", wtx.GetHash().ToString().c_str());
371 else if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n]))
373 printf("WalletUpdateSpent found spent coin %snvc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
374 wtx.MarkSpent(txin.prevout.n);
376 NotifyTransactionChanged(this, txin.prevout.hash, CT_UPDATED);
383 uint256 hash = tx.GetHash();
384 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hash);
385 CWalletTx& wtx = (*mi).second;
387 BOOST_FOREACH(const CTxOut& txout, tx.vout)
391 wtx.MarkUnspent(&txout - &tx.vout[0]);
393 NotifyTransactionChanged(this, hash, CT_UPDATED);
401 void CWallet::MarkDirty()
405 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
406 item.second.MarkDirty();
410 bool CWallet::AddToWallet(const CWalletTx& wtxIn)
412 uint256 hash = wtxIn.GetHash();
415 // Inserts only if not already there, returns tx inserted or tx found
416 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
417 CWalletTx& wtx = (*ret.first).second;
418 wtx.BindWallet(this);
419 bool fInsertedNew = ret.second;
422 wtx.nTimeReceived = GetAdjustedTime();
423 wtx.nOrderPos = IncOrderPosNext();
425 wtx.nTimeSmart = wtx.nTimeReceived;
426 if (wtxIn.hashBlock != 0)
428 if (mapBlockIndex.count(wtxIn.hashBlock))
430 unsigned int latestNow = wtx.nTimeReceived;
431 unsigned int latestEntry = 0;
433 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
434 int64 latestTolerated = latestNow + 300;
435 std::list<CAccountingEntry> acentries;
436 TxItems txOrdered = OrderedTxItems(acentries);
437 for (TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
439 CWalletTx *const pwtx = (*it).second.first;
442 CAccountingEntry *const pacentry = (*it).second.second;
446 nSmartTime = pwtx->nTimeSmart;
448 nSmartTime = pwtx->nTimeReceived;
451 nSmartTime = pacentry->nTime;
452 if (nSmartTime <= latestTolerated)
454 latestEntry = nSmartTime;
455 if (nSmartTime > latestNow)
456 latestNow = nSmartTime;
462 unsigned int& blocktime = mapBlockIndex[wtxIn.hashBlock]->nTime;
463 wtx.nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
466 printf("AddToWallet() : found %s in block %s not in index\n",
467 wtxIn.GetHash().ToString().substr(0,10).c_str(),
468 wtxIn.hashBlock.ToString().c_str());
472 bool fUpdated = false;
476 if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
478 wtx.hashBlock = wtxIn.hashBlock;
481 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
483 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
484 wtx.nIndex = wtxIn.nIndex;
487 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
489 wtx.fFromMe = wtxIn.fFromMe;
492 fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);
496 printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
499 if (fInsertedNew || fUpdated)
500 if (!wtx.WriteToDisk())
503 // If default receiving address gets used, replace it with a new one
504 CScript scriptDefaultKey;
505 scriptDefaultKey.SetDestination(vchDefaultKey.GetID());
506 BOOST_FOREACH(const CTxOut& txout, wtx.vout)
508 if (txout.scriptPubKey == scriptDefaultKey)
510 CPubKey newDefaultKey;
511 if (GetKeyFromPool(newDefaultKey, false))
513 SetDefaultKey(newDefaultKey);
514 SetAddressBookName(vchDefaultKey.GetID(), "");
519 // since AddToWallet is called directly for self-originating transactions, check for consumption of own coins
520 WalletUpdateSpent(wtx, (wtxIn.hashBlock != 0));
522 // Notify UI of new or updated transaction
523 NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
525 // notify an external script when a wallet transaction comes in or is updated
526 std::string strCmd = GetArg("-walletnotify", "");
528 if ( !strCmd.empty())
530 boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
531 boost::thread t(runCommand, strCmd); // thread runs free
538 // Add a transaction to the wallet, or update it.
539 // pblock is optional, but should be provided if the transaction is known to be in a block.
540 // If fUpdate is true, existing transactions will be updated.
541 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fFindBlock)
543 uint256 hash = tx.GetHash();
546 bool fExisted = mapWallet.count(hash);
547 if (fExisted && !fUpdate) return false;
548 if (fExisted || IsMine(tx) || IsFromMe(tx))
550 CWalletTx wtx(this,tx);
551 // Get merkle branch if transaction was found in a block
553 wtx.SetMerkleBranch(pblock);
554 return AddToWallet(wtx);
557 WalletUpdateSpent(tx);
562 bool CWallet::EraseFromWallet(uint256 hash)
568 if (mapWallet.erase(hash))
569 CWalletDB(strWalletFile).EraseTx(hash);
575 bool CWallet::IsMine(const CTxIn &txin) const
579 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
580 if (mi != mapWallet.end())
582 const CWalletTx& prev = (*mi).second;
583 if (txin.prevout.n < prev.vout.size())
584 if (IsMine(prev.vout[txin.prevout.n]))
591 int64 CWallet::GetDebit(const CTxIn &txin) const
595 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
596 if (mi != mapWallet.end())
598 const CWalletTx& prev = (*mi).second;
599 if (txin.prevout.n < prev.vout.size())
600 if (IsMine(prev.vout[txin.prevout.n]))
601 return prev.vout[txin.prevout.n].nValue;
607 bool CWallet::IsChange(const CTxOut& txout) const
609 CTxDestination address;
611 // TODO: fix handling of 'change' outputs. The assumption is that any
612 // payment to a TX_PUBKEYHASH that is mine but isn't in the address book
613 // is change. That assumption is likely to break when we implement multisignature
614 // wallets that return change back into a multi-signature-protected address;
615 // a better way of identifying which outputs are 'the send' and which are
616 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
617 // which output, if any, was change).
618 if (ExtractDestination(txout.scriptPubKey, address) && ::IsMine(*this, address))
621 if (!mapAddressBook.count(address))
627 int64 CWalletTx::GetTxTime() const
629 int64 n = nTimeSmart;
630 return n ? n : nTimeReceived;
633 int CWalletTx::GetRequestCount() const
635 // Returns -1 if it wasn't being tracked
638 LOCK(pwallet->cs_wallet);
639 if (IsCoinBase() || IsCoinStake())
644 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
645 if (mi != pwallet->mapRequestCount.end())
646 nRequests = (*mi).second;
651 // Did anyone request this transaction?
652 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
653 if (mi != pwallet->mapRequestCount.end())
655 nRequests = (*mi).second;
657 // How about the block it's in?
658 if (nRequests == 0 && hashBlock != 0)
660 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
661 if (mi != pwallet->mapRequestCount.end())
662 nRequests = (*mi).second;
664 nRequests = 1; // If it's in someone else's block it must have got out
672 void CWalletTx::GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, list<pair<CTxDestination, int64> >& listReceived,
673 list<pair<CTxDestination, int64> >& listSent, int64& nFee, string& strSentAccount) const
675 nGeneratedImmature = nGeneratedMature = nFee = 0;
676 listReceived.clear();
678 strSentAccount = strFromAccount;
680 if (IsCoinBase() || IsCoinStake())
682 if (GetBlocksToMaturity() > 0)
683 nGeneratedImmature = pwallet->GetCredit(*this);
685 nGeneratedMature = GetCredit();
690 int64 nDebit = GetDebit();
691 if (nDebit > 0) // debit>0 means we signed/sent this transaction
693 int64 nValueOut = GetValueOut();
694 nFee = nDebit - nValueOut;
698 BOOST_FOREACH(const CTxOut& txout, vout)
700 CTxDestination address;
701 vector<unsigned char> vchPubKey;
702 if (!ExtractDestination(txout.scriptPubKey, address))
704 printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
705 this->GetHash().ToString().c_str());
708 // Don't report 'change' txouts
709 if (nDebit > 0 && pwallet->IsChange(txout))
713 listSent.push_back(make_pair(address, txout.nValue));
715 if (pwallet->IsMine(txout))
716 listReceived.push_back(make_pair(address, txout.nValue));
721 void CWalletTx::GetAccountAmounts(const string& strAccount, int64& nGenerated, int64& nReceived,
722 int64& nSent, int64& nFee) const
724 nGenerated = nReceived = nSent = nFee = 0;
726 int64 allGeneratedImmature, allGeneratedMature, allFee;
727 allGeneratedImmature = allGeneratedMature = allFee = 0;
728 string strSentAccount;
729 list<pair<CTxDestination, int64> > listReceived;
730 list<pair<CTxDestination, int64> > listSent;
731 GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount);
733 if (strAccount == "")
734 nGenerated = allGeneratedMature;
735 if (strAccount == strSentAccount)
737 BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& s, listSent)
742 LOCK(pwallet->cs_wallet);
743 BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listReceived)
745 if (pwallet->mapAddressBook.count(r.first))
747 map<CTxDestination, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);
748 if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)
749 nReceived += r.second;
751 else if (strAccount.empty())
753 nReceived += r.second;
759 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
763 const int COPY_DEPTH = 3;
764 if (SetMerkleBranch() < COPY_DEPTH)
766 vector<uint256> vWorkQueue;
767 BOOST_FOREACH(const CTxIn& txin, vin)
768 vWorkQueue.push_back(txin.prevout.hash);
770 // This critsect is OK because txdb is already open
772 LOCK(pwallet->cs_wallet);
773 map<uint256, const CMerkleTx*> mapWalletPrev;
774 set<uint256> setAlreadyDone;
775 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
777 uint256 hash = vWorkQueue[i];
778 if (setAlreadyDone.count(hash))
780 setAlreadyDone.insert(hash);
783 map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
784 if (mi != pwallet->mapWallet.end())
787 BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev)
788 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
790 else if (mapWalletPrev.count(hash))
792 tx = *mapWalletPrev[hash];
794 else if (!fClient && txdb.ReadDiskTx(hash, tx))
800 printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
804 int nDepth = tx.SetMerkleBranch();
805 vtxPrev.push_back(tx);
807 if (nDepth < COPY_DEPTH)
809 BOOST_FOREACH(const CTxIn& txin, tx.vin)
810 vWorkQueue.push_back(txin.prevout.hash);
816 reverse(vtxPrev.begin(), vtxPrev.end());
819 bool CWalletTx::WriteToDisk()
821 return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
824 // Scan the block chain (starting in pindexStart) for transactions
825 // from or to us. If fUpdate is true, found transactions that already
826 // exist in the wallet will be updated.
827 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
831 CBlockIndex* pindex = pindexStart;
837 block.ReadFromDisk(pindex, true);
838 BOOST_FOREACH(CTransaction& tx, block.vtx)
840 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
843 pindex = pindex->pnext;
849 int CWallet::ScanForWalletTransaction(const uint256& hashTx)
852 tx.ReadFromDisk(COutPoint(hashTx, 0));
853 if (AddToWalletIfInvolvingMe(tx, NULL, true, true))
858 void CWallet::ReacceptWalletTransactions()
866 vector<CDiskTxPos> vMissingTx;
867 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
869 CWalletTx& wtx = item.second;
870 if ((wtx.IsCoinBase() && wtx.IsSpent(0)) || (wtx.IsCoinStake() && wtx.IsSpent(1)))
874 bool fUpdated = false;
875 if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
877 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
878 if (txindex.vSpent.size() != wtx.vout.size())
880 printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %"PRIszu" != wtx.vout.size() %"PRIszu"\n", txindex.vSpent.size(), wtx.vout.size());
883 for (unsigned int i = 0; i < txindex.vSpent.size(); i++)
887 if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i]))
891 vMissingTx.push_back(txindex.vSpent[i]);
896 printf("ReacceptWalletTransactions found spent coin %snvc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
903 // Re-accept any txes of ours that aren't already in a block
904 if (!(wtx.IsCoinBase() || wtx.IsCoinStake()))
905 wtx.AcceptWalletTransaction(txdb, false);
908 if (!vMissingTx.empty())
910 // TODO: optimize this to scan just part of the block chain?
911 if (ScanForWalletTransactions(pindexGenesisBlock))
912 fRepeat = true; // Found missing transactions: re-do re-accept.
917 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
919 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
921 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
923 uint256 hash = tx.GetHash();
924 if (!txdb.ContainsTx(hash))
925 RelayTransaction((CTransaction)tx, hash);
928 if (!(IsCoinBase() || IsCoinStake()))
930 uint256 hash = GetHash();
931 if (!txdb.ContainsTx(hash))
933 printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
934 RelayTransaction((CTransaction)*this, hash);
939 void CWalletTx::RelayWalletTransaction()
942 RelayWalletTransaction(txdb);
945 void CWallet::ResendWalletTransactions()
947 // Do this infrequently and randomly to avoid giving away
948 // that these are our transactions.
949 static int64 nNextTime;
950 if (GetTime() < nNextTime)
952 bool fFirst = (nNextTime == 0);
953 nNextTime = GetTime() + GetRand(30 * 60);
957 // Only do it if there's been a new block since last time
958 static int64 nLastTime;
959 if (nTimeBestReceived < nLastTime)
961 nLastTime = GetTime();
963 // Rebroadcast any of our txes that aren't in a block yet
964 printf("ResendWalletTransactions()\n");
968 // Sort them in chronological order
969 multimap<unsigned int, CWalletTx*> mapSorted;
970 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
972 CWalletTx& wtx = item.second;
973 // Don't rebroadcast until it's had plenty of time that
974 // it should have gotten in already by now.
975 if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
976 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
978 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
980 CWalletTx& wtx = *item.second;
981 if (wtx.CheckTransaction())
982 wtx.RelayWalletTransaction(txdb);
984 printf("ResendWalletTransactions() : CheckTransaction failed for transaction %s\n", wtx.GetHash().ToString().c_str());
994 //////////////////////////////////////////////////////////////////////////////
1000 int64 CWallet::GetBalance() const
1005 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1007 const CWalletTx* pcoin = &(*it).second;
1008 if (pcoin->IsTrusted())
1009 nTotal += pcoin->GetAvailableCredit();
1016 int64 CWallet::GetUnconfirmedBalance() const
1021 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1023 const CWalletTx* pcoin = &(*it).second;
1024 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
1025 nTotal += pcoin->GetAvailableCredit();
1031 int64 CWallet::GetImmatureBalance() const
1036 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1038 const CWalletTx& pcoin = (*it).second;
1039 if (pcoin.IsCoinBase() && pcoin.GetBlocksToMaturity() > 0 && pcoin.IsInMainChain())
1040 nTotal += GetCredit(pcoin);
1046 // populate vCoins with vector of spendable COutputs
1047 void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl) const
1053 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1055 const CWalletTx* pcoin = &(*it).second;
1057 if (!pcoin->IsFinal())
1060 if (fOnlyConfirmed && !pcoin->IsTrusted())
1063 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
1066 if(pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0)
1069 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
1070 if (!(pcoin->IsSpent(i)) && IsMine(pcoin->vout[i]) && pcoin->vout[i].nValue >= nMinimumInputValue &&
1071 (!coinControl || !coinControl->HasSelected() || coinControl->IsSelected((*it).first, i)))
1072 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain()));
1078 void CWallet::AvailableCoinsMinConf(vector<COutput>& vCoins, int nConf) const
1084 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1086 const CWalletTx* pcoin = &(*it).second;
1088 if (!pcoin->IsFinal())
1091 if(pcoin->GetDepthInMainChain() < nConf)
1094 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
1095 if (!(pcoin->IsSpent(i)) && IsMine(pcoin->vout[i]) && pcoin->vout[i].nValue >= nMinimumInputValue)
1096 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain()));
1101 static void ApproximateBestSubset(vector<pair<int64, pair<const CWalletTx*,unsigned int> > >vValue, int64 nTotalLower, int64 nTargetValue,
1102 vector<char>& vfBest, int64& nBest, int iterations = 1000)
1104 vector<char> vfIncluded;
1106 vfBest.assign(vValue.size(), true);
1107 nBest = nTotalLower;
1109 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
1111 vfIncluded.assign(vValue.size(), false);
1113 bool fReachedTarget = false;
1114 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
1116 for (unsigned int i = 0; i < vValue.size(); i++)
1118 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
1120 nTotal += vValue[i].first;
1121 vfIncluded[i] = true;
1122 if (nTotal >= nTargetValue)
1124 fReachedTarget = true;
1128 vfBest = vfIncluded;
1130 nTotal -= vValue[i].first;
1131 vfIncluded[i] = false;
1139 // ppcoin: total coins staked (non-spendable until maturity)
1140 int64 CWallet::GetStake() const
1144 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1146 const CWalletTx* pcoin = &(*it).second;
1147 if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1148 nTotal += CWallet::GetCredit(*pcoin);
1153 int64 CWallet::GetNewMint() const
1157 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1159 const CWalletTx* pcoin = &(*it).second;
1160 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1161 nTotal += CWallet::GetCredit(*pcoin);
1166 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
1168 setCoinsRet.clear();
1171 // List of values less than target
1172 pair<int64, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
1173 coinLowestLarger.first = std::numeric_limits<int64>::max();
1174 coinLowestLarger.second.first = NULL;
1175 vector<pair<int64, pair<const CWalletTx*,unsigned int> > > vValue;
1176 int64 nTotalLower = 0;
1178 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
1180 BOOST_FOREACH(COutput output, vCoins)
1182 const CWalletTx *pcoin = output.tx;
1184 if (output.nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs))
1189 // Follow the timestamp rules
1190 if (pcoin->nTime > nSpendTime)
1193 int64 n = pcoin->vout[i].nValue;
1195 pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1197 if (n == nTargetValue)
1199 setCoinsRet.insert(coin.second);
1200 nValueRet += coin.first;
1203 else if (n < nTargetValue + CENT)
1205 vValue.push_back(coin);
1208 else if (n < coinLowestLarger.first)
1210 coinLowestLarger = coin;
1214 if (nTotalLower == nTargetValue)
1216 for (unsigned int i = 0; i < vValue.size(); ++i)
1218 setCoinsRet.insert(vValue[i].second);
1219 nValueRet += vValue[i].first;
1224 if (nTotalLower < nTargetValue)
1226 if (coinLowestLarger.second.first == NULL)
1228 setCoinsRet.insert(coinLowestLarger.second);
1229 nValueRet += coinLowestLarger.first;
1233 // Solve subset sum by stochastic approximation
1234 sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
1235 vector<char> vfBest;
1238 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);
1239 if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT)
1240 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000);
1242 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
1243 // or the next bigger coin is closer), return the bigger coin
1244 if (coinLowestLarger.second.first &&
1245 ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest))
1247 setCoinsRet.insert(coinLowestLarger.second);
1248 nValueRet += coinLowestLarger.first;
1251 for (unsigned int i = 0; i < vValue.size(); i++)
1254 setCoinsRet.insert(vValue[i].second);
1255 nValueRet += vValue[i].first;
1258 if (fDebug && GetBoolArg("-printpriority"))
1261 printf("SelectCoins() best subset: ");
1262 for (unsigned int i = 0; i < vValue.size(); i++)
1264 printf("%s ", FormatMoney(vValue[i].first).c_str());
1265 printf("total %s\n", FormatMoney(nBest).c_str());
1272 bool CWallet::SelectCoins(int64 nTargetValue, unsigned int nSpendTime, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet, const CCoinControl* coinControl) const
1274 vector<COutput> vCoins;
1275 AvailableCoins(vCoins, true, coinControl);
1277 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
1278 if (coinControl && coinControl->HasSelected())
1280 BOOST_FOREACH(const COutput& out, vCoins)
1282 nValueRet += out.tx->vout[out.i].nValue;
1283 setCoinsRet.insert(make_pair(out.tx, out.i));
1285 return (nValueRet >= nTargetValue);
1288 return (SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 6, vCoins, setCoinsRet, nValueRet) ||
1289 SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 1, vCoins, setCoinsRet, nValueRet) ||
1290 SelectCoinsMinConf(nTargetValue, nSpendTime, 0, 1, vCoins, setCoinsRet, nValueRet));
1293 // Select some coins without random shuffle or best subset approximation
1294 bool CWallet::SelectCoinsSimple(int64 nTargetValue, unsigned int nSpendTime, int nMinConf, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
1296 vector<COutput> vCoins;
1297 AvailableCoinsMinConf(vCoins, nMinConf);
1299 setCoinsRet.clear();
1302 BOOST_FOREACH(COutput output, vCoins)
1304 const CWalletTx *pcoin = output.tx;
1307 // Stop if we've chosen enough inputs
1308 if (nValueRet >= nTargetValue)
1311 // Follow the timestamp rules
1312 if (pcoin->nTime > nSpendTime)
1315 int64 n = pcoin->vout[i].nValue;
1317 pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1319 if (n >= nTargetValue)
1321 // If input value is greater or equal to target then simply insert
1322 // it into the current subset and exit
1323 setCoinsRet.insert(coin.second);
1324 nValueRet += coin.first;
1327 else if (n < nTargetValue + CENT)
1329 setCoinsRet.insert(coin.second);
1330 nValueRet += coin.first;
1337 bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, const CCoinControl* coinControl)
1340 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1346 if (vecSend.empty() || nValue < 0)
1349 wtxNew.BindWallet(this);
1352 LOCK2(cs_main, cs_wallet);
1353 // txdb must be opened before the mapWallet lock
1356 nFeeRet = nTransactionFee;
1360 wtxNew.vout.clear();
1361 wtxNew.fFromMe = true;
1363 int64 nTotalValue = nValue + nFeeRet;
1364 double dPriority = 0;
1365 // vouts to the payees
1366 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1367 wtxNew.vout.push_back(CTxOut(s.second, s.first));
1369 // Choose coins to use
1370 set<pair<const CWalletTx*,unsigned int> > setCoins;
1372 if (!SelectCoins(nTotalValue, wtxNew.nTime, setCoins, nValueIn, coinControl))
1374 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1376 int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
1377 dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
1380 int64 nChange = nValueIn - nValue - nFeeRet;
1381 // if sub-cent change is required, the fee must be raised to at least MIN_TX_FEE
1382 // or until nChange becomes zero
1383 // NOTE: this depends on the exact behaviour of GetMinFee
1384 if (nFeeRet < MIN_TX_FEE && nChange > 0 && nChange < CENT)
1386 int64 nMoveToFee = min(nChange, MIN_TX_FEE - nFeeRet);
1387 nChange -= nMoveToFee;
1388 nFeeRet += nMoveToFee;
1391 // ppcoin: sub-cent change is moved to fee
1392 if (nChange > 0 && nChange < MIN_TXOUT_AMOUNT)
1400 // Fill a vout to ourself
1401 // TODO: pass in scriptChange instead of reservekey so
1402 // change transaction isn't always pay-to-bitcoin-address
1403 CScript scriptChange;
1405 // coin control: send change to custom address
1406 if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange))
1407 scriptChange.SetDestination(coinControl->destChange);
1409 // no coin control: send change to newly generated address
1412 // Note: We use a new key here to keep it from being obvious which side is the change.
1413 // The drawback is that by not reusing a previous key, the change may be lost if a
1414 // backup is restored, if the backup doesn't have the new private key for the change.
1415 // If we reused the old key, it would be possible to add code to look for and
1416 // rediscover unknown transactions that were written with keys of ours to recover
1417 // post-backup change.
1419 // Reserve a new key pair from key pool
1420 CPubKey vchPubKey = reservekey.GetReservedKey();
1422 scriptChange.SetDestination(vchPubKey.GetID());
1425 // Insert change txn at random position:
1426 vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
1427 wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
1430 reservekey.ReturnKey();
1433 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1434 wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
1438 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1439 if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
1443 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
1444 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1446 dPriority /= nBytes;
1448 // Check that enough fee is included
1449 int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
1450 int64 nMinFee = wtxNew.GetMinFee(1, false, GMF_SEND, nBytes);
1452 if (nFeeRet < max(nPayFee, nMinFee))
1454 nFeeRet = max(nPayFee, nMinFee);
1458 // Fill vtxPrev by copying from previous transactions vtxPrev
1459 wtxNew.AddSupportingTransactions(txdb);
1460 wtxNew.fTimeReceivedIsTxTime = true;
1469 bool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, const CCoinControl* coinControl)
1471 vector< pair<CScript, int64> > vecSend;
1472 vecSend.push_back(make_pair(scriptPubKey, nValue));
1473 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, coinControl);
1476 // NovaCoin: get current stake weight
1477 bool CWallet::GetStakeWeight(const CKeyStore& keystore, uint64& nMinWeight, uint64& nMaxWeight, uint64& nWeight)
1479 // Choose coins to use
1480 int64 nBalance = GetBalance();
1481 int64 nReserveBalance = 0;
1483 if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
1485 error("GetStakeWeight : invalid reserve balance amount");
1489 if (nBalance <= nReserveBalance)
1492 vector<const CWalletTx*> vwtxPrev;
1495 * TODO: performance comparison
1497 static set<pair<const CWalletTx*,unsigned int> > setCoins;
1498 static uint256 hashPrevBlock;
1499 static int64 nValueIn = 0;
1501 // Cache outputs unless best block changed
1502 if (hashPrevBlock != pindexBest->GetBlockHash())
1504 if (!SelectCoinsSimple(nBalance - nReserveBalance, GetAdjustedTime(), nCoinbaseMaturity * 10, setCoins, nValueIn))
1507 if (setCoins.empty())
1510 hashPrevBlock == pindexBest->GetBlockHash();
1514 set<pair<const CWalletTx*,unsigned int> > setCoins;
1517 if (!SelectCoinsSimple(nBalance - nReserveBalance, GetTime(), nCoinbaseMaturity * 10, setCoins, nValueIn))
1520 if (setCoins.empty())
1524 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1528 LOCK2(cs_main, cs_wallet);
1529 if (!txdb.ReadTxIndex(pcoin.first->GetHash(), txindex))
1533 int64 nTimeWeight = GetWeight((int64)pcoin.first->nTime, (int64)GetTime());
1534 CBigNum bnCoinDayWeight = CBigNum(pcoin.first->vout[pcoin.second].nValue) * nTimeWeight / COIN / (24 * 60 * 60);
1536 // Weight is greater than zero
1537 if (nTimeWeight > 0)
1539 nWeight += bnCoinDayWeight.getuint64();
1542 // Weight is greater than zero, but the maximum value isn't reached yet
1543 if (nTimeWeight > 0 && nTimeWeight < nStakeMaxAge)
1545 nMinWeight += bnCoinDayWeight.getuint64();
1548 // Maximum weight was reached
1549 if (nTimeWeight == nStakeMaxAge)
1551 nMaxWeight += bnCoinDayWeight.getuint64();
1558 bool CWallet::CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int64 nSearchInterval, CTransaction& txNew, CKey& key)
1560 // The following combine threshold is important to security
1561 // Should not be adjusted if you don't understand the consequences
1562 int64 nCombineThreshold = GetProofOfWorkReward(GetLastBlockIndex(pindexBest, false)->nBits) / 3;
1564 CBigNum bnTargetPerCoinDay;
1565 bnTargetPerCoinDay.SetCompact(nBits);
1570 // Mark coin stake transaction
1571 CScript scriptEmpty;
1572 scriptEmpty.clear();
1573 txNew.vout.push_back(CTxOut(0, scriptEmpty));
1575 // Choose coins to use
1576 int64 nBalance = GetBalance();
1577 int64 nReserveBalance = 0;
1579 if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
1580 return error("CreateCoinStake : invalid reserve balance amount");
1582 if (nBalance <= nReserveBalance)
1585 vector<const CWalletTx*> vwtxPrev;
1588 * TODO: performance comparison
1590 static set<pair<const CWalletTx*,unsigned int> > setCoins;
1591 static uint256 hashPrevBlock;
1592 static int64 nValueIn = 0;
1594 // Cache outputs unless best block changed
1595 if (hashPrevBlock != pindexBest->GetBlockHash())
1597 if (!SelectCoinsSimple(nBalance - nReserveBalance, txNew.nTime, nCoinbaseMaturity * 10, setCoins, nValueIn))
1600 if (setCoins.empty())
1603 hashPrevBlock == pindexBest->GetBlockHash();
1607 set<pair<const CWalletTx*,unsigned int> > setCoins;
1610 // Select coins with suitable depth
1611 if (!SelectCoinsSimple(nBalance - nReserveBalance, txNew.nTime, nCoinbaseMaturity * 10, setCoins, nValueIn))
1614 if (setCoins.empty())
1618 CScript scriptPubKeyKernel;
1620 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1624 LOCK2(cs_main, cs_wallet);
1625 if (!txdb.ReadTxIndex(pcoin.first->GetHash(), txindex))
1629 // Read block header
1632 LOCK2(cs_main, cs_wallet);
1633 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
1637 static int nMaxStakeSearchInterval = 60;
1638 if (block.GetBlockTime() + nStakeMinAge > txNew.nTime - nMaxStakeSearchInterval)
1639 continue; // only count coins meeting min age requirement
1641 bool fKernelFound = false;
1642 for (unsigned int n=0; n<min(nSearchInterval,(int64)nMaxStakeSearchInterval) && !fKernelFound && !fShutdown; n++)
1644 // Search backward in time from the given txNew timestamp
1645 // Search nSearchInterval seconds back up to nMaxStakeSearchInterval
1646 uint256 hashProofOfStake = 0, targetProofOfStake = 0;
1647 COutPoint prevoutStake = COutPoint(pcoin.first->GetHash(), pcoin.second);
1648 if (CheckStakeKernelHash(nBits, block, txindex.pos.nTxPos - txindex.pos.nBlockPos, *pcoin.first, prevoutStake, txNew.nTime - n, hashProofOfStake, targetProofOfStake))
1651 if (fDebug && GetBoolArg("-printcoinstake"))
1652 printf("CreateCoinStake : kernel found\n");
1653 vector<valtype> vSolutions;
1654 txnouttype whichType;
1655 CScript scriptPubKeyOut;
1656 scriptPubKeyKernel = pcoin.first->vout[pcoin.second].scriptPubKey;
1657 if (!Solver(scriptPubKeyKernel, whichType, vSolutions))
1659 if (fDebug && GetBoolArg("-printcoinstake"))
1660 printf("CreateCoinStake : failed to parse kernel\n");
1663 if (fDebug && GetBoolArg("-printcoinstake"))
1664 printf("CreateCoinStake : parsed kernel type=%d\n", whichType);
1665 if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH)
1667 if (fDebug && GetBoolArg("-printcoinstake"))
1668 printf("CreateCoinStake : no support for kernel type=%d\n", whichType);
1669 break; // only support pay to public key and pay to address
1671 if (whichType == TX_PUBKEYHASH) // pay to address type
1673 // convert to pay to public key type
1674 if (!keystore.GetKey(uint160(vSolutions[0]), key))
1676 if (fDebug && GetBoolArg("-printcoinstake"))
1677 printf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1678 break; // unable to find corresponding public key
1680 scriptPubKeyOut << key.GetPubKey() << OP_CHECKSIG;
1682 if (whichType == TX_PUBKEY)
1684 valtype& vchPubKey = vSolutions[0];
1685 if (!keystore.GetKey(Hash160(vchPubKey), key))
1687 if (fDebug && GetBoolArg("-printcoinstake"))
1688 printf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1689 break; // unable to find corresponding public key
1692 if (key.GetPubKey() != vchPubKey)
1694 if (fDebug && GetBoolArg("-printcoinstake"))
1695 printf("CreateCoinStake : invalid key for kernel type=%d\n", whichType);
1696 break; // keys mismatch
1699 scriptPubKeyOut = scriptPubKeyKernel;
1703 txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1704 nCredit += pcoin.first->vout[pcoin.second].nValue;
1705 vwtxPrev.push_back(pcoin.first);
1706 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
1708 if (GetWeight(block.GetBlockTime(), (int64)txNew.nTime) < nStakeMaxAge)
1709 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut)); //split stake
1710 if (fDebug && GetBoolArg("-printcoinstake"))
1711 printf("CreateCoinStake : added kernel type=%d\n", whichType);
1712 fKernelFound = true;
1717 if (fKernelFound || fShutdown)
1718 break; // if kernel is found stop searching
1721 if (nCredit == 0 || nCredit > nBalance - nReserveBalance)
1724 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1726 // Attempt to add more inputs
1727 // Only add coins of the same key/address as kernel
1728 if (txNew.vout.size() == 2 && ((pcoin.first->vout[pcoin.second].scriptPubKey == scriptPubKeyKernel || pcoin.first->vout[pcoin.second].scriptPubKey == txNew.vout[1].scriptPubKey))
1729 && pcoin.first->GetHash() != txNew.vin[0].prevout.hash)
1731 int64 nTimeWeight = GetWeight((int64)pcoin.first->nTime, (int64)txNew.nTime);
1733 // Stop adding more inputs if already too many inputs
1734 if (txNew.vin.size() >= 100)
1736 // Stop adding more inputs if value is already pretty significant
1737 if (nCredit > nCombineThreshold)
1739 // Stop adding inputs if reached reserve limit
1740 if (nCredit + pcoin.first->vout[pcoin.second].nValue > nBalance - nReserveBalance)
1742 // Do not add additional significant input
1743 if (pcoin.first->vout[pcoin.second].nValue > nCombineThreshold)
1745 // Do not add input that is still too young
1746 if (nTimeWeight < nStakeMaxAge)
1749 txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1750 nCredit += pcoin.first->vout[pcoin.second].nValue;
1751 vwtxPrev.push_back(pcoin.first);
1755 // Calculate coin age reward
1759 if (!txNew.GetCoinAge(txdb, nCoinAge))
1760 return error("CreateCoinStake : failed to calculate coin age");
1761 nCredit += GetProofOfStakeReward(nCoinAge, nBits, txNew.nTime);
1767 // Set output amount
1768 if (txNew.vout.size() == 3)
1770 txNew.vout[1].nValue = ((nCredit - nMinFee) / 2 / CENT) * CENT;
1771 txNew.vout[2].nValue = nCredit - nMinFee - txNew.vout[1].nValue;
1774 txNew.vout[1].nValue = nCredit - nMinFee;
1778 BOOST_FOREACH(const CWalletTx* pcoin, vwtxPrev)
1780 if (!SignSignature(*this, *pcoin, txNew, nIn++))
1781 return error("CreateCoinStake : failed to sign coinstake");
1785 unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION);
1786 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1787 return error("CreateCoinStake : exceeded coinstake size limit");
1789 // Check enough fee is paid
1790 if (nMinFee < txNew.GetMinFee() - MIN_TX_FEE)
1792 nMinFee = txNew.GetMinFee() - MIN_TX_FEE;
1793 continue; // try signing again
1797 if (fDebug && GetBoolArg("-printfee"))
1798 printf("CreateCoinStake : fee for coinstake %s\n", FormatMoney(nMinFee).c_str());
1803 // Successfully generated coinstake
1808 // Call after CreateTransaction unless you want to abort
1809 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
1812 LOCK2(cs_main, cs_wallet);
1813 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
1815 // This is only to keep the database open to defeat the auto-flush for the
1816 // duration of this scope. This is the only place where this optimization
1817 // maybe makes sense; please don't do it anywhere else.
1818 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
1820 // Take key pair from key pool so it won't be used again
1821 reservekey.KeepKey();
1823 // Add tx to wallet, because if it has change it's also ours,
1824 // otherwise just for transaction history.
1825 AddToWallet(wtxNew);
1827 // Mark old coins as spent
1828 set<CWalletTx*> setCoins;
1829 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
1831 CWalletTx &coin = mapWallet[txin.prevout.hash];
1832 coin.BindWallet(this);
1833 coin.MarkSpent(txin.prevout.n);
1835 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
1842 // Track how many getdata requests our transaction gets
1843 mapRequestCount[wtxNew.GetHash()] = 0;
1846 if (!wtxNew.AcceptToMemoryPool())
1848 // This must not fail. The transaction has already been signed and recorded.
1849 printf("CommitTransaction() : Error: Transaction not valid");
1852 wtxNew.RelayWalletTransaction();
1860 string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1862 CReserveKey reservekey(this);
1867 string strError = _("Error: Wallet locked, unable to create transaction ");
1868 printf("SendMoney() : %s", strError.c_str());
1871 if (fWalletUnlockMintOnly)
1873 string strError = _("Error: Wallet unlocked for block minting only, unable to create transaction.");
1874 printf("SendMoney() : %s", strError.c_str());
1877 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
1880 if (nValue + nFeeRequired > GetBalance())
1881 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());
1883 strError = _("Error: Transaction creation failed ");
1884 printf("SendMoney() : %s", strError.c_str());
1888 if (fAskFee && !uiInterface.ThreadSafeAskFee(nFeeRequired, _("Sending...")))
1891 if (!CommitTransaction(wtxNew, reservekey))
1892 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.");
1899 string CWallet::SendMoneyToDestination(const CTxDestination& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1903 return _("Invalid amount");
1904 if (nValue + nTransactionFee > GetBalance())
1905 return _("Insufficient funds");
1907 // Parse Bitcoin address
1908 CScript scriptPubKey;
1909 scriptPubKey.SetDestination(address);
1911 return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
1917 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
1921 fFirstRunRet = false;
1922 DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
1923 if (nLoadWalletRet == DB_NEED_REWRITE)
1925 if (CDB::Rewrite(strWalletFile, "\x04pool"))
1928 // Note: can't top-up keypool here, because wallet is locked.
1929 // User will be prompted to unlock wallet the next operation
1930 // the requires a new key.
1934 if (nLoadWalletRet != DB_LOAD_OK)
1935 return nLoadWalletRet;
1936 fFirstRunRet = !vchDefaultKey.IsValid();
1938 NewThread(ThreadFlushWalletDB, &strWalletFile);
1943 bool CWallet::SetAddressBookName(const CTxDestination& address, const string& strName)
1945 std::map<CTxDestination, std::string>::iterator mi = mapAddressBook.find(address);
1946 mapAddressBook[address] = strName;
1947 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address), (mi == mapAddressBook.end()) ? CT_NEW : CT_UPDATED);
1950 return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName);
1953 bool CWallet::DelAddressBookName(const CTxDestination& address)
1955 mapAddressBook.erase(address);
1956 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address), CT_DELETED);
1959 return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString());
1963 void CWallet::PrintWallet(const CBlock& block)
1967 if (block.IsProofOfWork() && mapWallet.count(block.vtx[0].GetHash()))
1969 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
1970 printf(" mine: %d %d %"PRI64d"", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
1972 if (block.IsProofOfStake() && mapWallet.count(block.vtx[1].GetHash()))
1974 CWalletTx& wtx = mapWallet[block.vtx[1].GetHash()];
1975 printf(" stake: %d %d %"PRI64d"", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
1982 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
1986 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
1987 if (mi != mapWallet.end())
1996 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
2000 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
2003 vchDefaultKey = vchPubKey;
2007 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
2009 if (!pwallet->fFileBacked)
2011 strWalletFileOut = pwallet->strWalletFile;
2016 // Mark old keypool keys as used,
2017 // and generate all new keys
2019 bool CWallet::NewKeyPool()
2023 CWalletDB walletdb(strWalletFile);
2024 BOOST_FOREACH(int64 nIndex, setKeyPool)
2025 walletdb.ErasePool(nIndex);
2031 int64 nKeys = max(GetArg("-keypool", 100), (int64)0);
2032 for (int i = 0; i < nKeys; i++)
2035 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
2036 setKeyPool.insert(nIndex);
2038 printf("CWallet::NewKeyPool wrote %"PRI64d" new keys\n", nKeys);
2043 bool CWallet::TopUpKeyPool(unsigned int nSize)
2051 CWalletDB walletdb(strWalletFile);
2054 unsigned int nTargetSize;
2056 nTargetSize = nSize;
2058 nTargetSize = max(GetArg("-keypool", 100), 0LL);
2060 while (setKeyPool.size() < (nTargetSize + 1))
2063 if (!setKeyPool.empty())
2064 nEnd = *(--setKeyPool.end()) + 1;
2065 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
2066 throw runtime_error("TopUpKeyPool() : writing generated key failed");
2067 setKeyPool.insert(nEnd);
2068 printf("keypool added key %"PRI64d", size=%"PRIszu"\n", nEnd, setKeyPool.size());
2074 void CWallet::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool)
2077 keypool.vchPubKey = CPubKey();
2084 // Get the oldest key
2085 if(setKeyPool.empty())
2088 CWalletDB walletdb(strWalletFile);
2090 nIndex = *(setKeyPool.begin());
2091 setKeyPool.erase(setKeyPool.begin());
2092 if (!walletdb.ReadPool(nIndex, keypool))
2093 throw runtime_error("ReserveKeyFromKeyPool() : read failed");
2094 if (!HaveKey(keypool.vchPubKey.GetID()))
2095 throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
2096 assert(keypool.vchPubKey.IsValid());
2097 if (fDebug && GetBoolArg("-printkeypool"))
2098 printf("keypool reserve %"PRI64d"\n", nIndex);
2102 int64 CWallet::AddReserveKey(const CKeyPool& keypool)
2105 LOCK2(cs_main, cs_wallet);
2106 CWalletDB walletdb(strWalletFile);
2108 int64 nIndex = 1 + *(--setKeyPool.end());
2109 if (!walletdb.WritePool(nIndex, keypool))
2110 throw runtime_error("AddReserveKey() : writing added key failed");
2111 setKeyPool.insert(nIndex);
2117 void CWallet::KeepKey(int64 nIndex)
2119 // Remove from key pool
2122 CWalletDB walletdb(strWalletFile);
2123 walletdb.ErasePool(nIndex);
2126 printf("keypool keep %"PRI64d"\n", nIndex);
2129 void CWallet::ReturnKey(int64 nIndex)
2131 // Return to key pool
2134 setKeyPool.insert(nIndex);
2137 printf("keypool return %"PRI64d"\n", nIndex);
2140 bool CWallet::GetKeyFromPool(CPubKey& result, bool fAllowReuse)
2146 ReserveKeyFromKeyPool(nIndex, keypool);
2149 if (fAllowReuse && vchDefaultKey.IsValid())
2151 result = vchDefaultKey;
2154 if (IsLocked()) return false;
2155 result = GenerateNewKey();
2159 result = keypool.vchPubKey;
2164 int64 CWallet::GetOldestKeyPoolTime()
2168 ReserveKeyFromKeyPool(nIndex, keypool);
2172 return keypool.nTime;
2175 std::map<CTxDestination, int64> CWallet::GetAddressBalances()
2177 map<CTxDestination, int64> balances;
2181 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2183 CWalletTx *pcoin = &walletEntry.second;
2185 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
2188 if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0)
2191 int nDepth = pcoin->GetDepthInMainChain();
2192 if (nDepth < (pcoin->IsFromMe() ? 0 : 1))
2195 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2197 CTxDestination addr;
2198 if (!IsMine(pcoin->vout[i]))
2200 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr))
2203 int64 n = pcoin->IsSpent(i) ? 0 : pcoin->vout[i].nValue;
2205 if (!balances.count(addr))
2207 balances[addr] += n;
2215 set< set<CTxDestination> > CWallet::GetAddressGroupings()
2217 set< set<CTxDestination> > groupings;
2218 set<CTxDestination> grouping;
2220 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2222 CWalletTx *pcoin = &walletEntry.second;
2224 if (pcoin->vin.size() > 0 && IsMine(pcoin->vin[0]))
2226 // group all input addresses with each other
2227 BOOST_FOREACH(CTxIn txin, pcoin->vin)
2229 CTxDestination address;
2230 if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
2232 grouping.insert(address);
2235 // group change with input addresses
2236 BOOST_FOREACH(CTxOut txout, pcoin->vout)
2237 if (IsChange(txout))
2239 CWalletTx tx = mapWallet[pcoin->vin[0].prevout.hash];
2240 CTxDestination txoutAddr;
2241 if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
2243 grouping.insert(txoutAddr);
2245 groupings.insert(grouping);
2249 // group lone addrs by themselves
2250 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2251 if (IsMine(pcoin->vout[i]))
2253 CTxDestination address;
2254 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address))
2256 grouping.insert(address);
2257 groupings.insert(grouping);
2262 set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
2263 map< CTxDestination, set<CTxDestination>* > setmap; // map addresses to the unique group containing it
2264 BOOST_FOREACH(set<CTxDestination> grouping, groupings)
2266 // make a set of all the groups hit by this new group
2267 set< set<CTxDestination>* > hits;
2268 map< CTxDestination, set<CTxDestination>* >::iterator it;
2269 BOOST_FOREACH(CTxDestination address, grouping)
2270 if ((it = setmap.find(address)) != setmap.end())
2271 hits.insert((*it).second);
2273 // merge all hit groups into a new single group and delete old groups
2274 set<CTxDestination>* merged = new set<CTxDestination>(grouping);
2275 BOOST_FOREACH(set<CTxDestination>* hit, hits)
2277 merged->insert(hit->begin(), hit->end());
2278 uniqueGroupings.erase(hit);
2281 uniqueGroupings.insert(merged);
2284 BOOST_FOREACH(CTxDestination element, *merged)
2285 setmap[element] = merged;
2288 set< set<CTxDestination> > ret;
2289 BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings)
2291 ret.insert(*uniqueGrouping);
2292 delete uniqueGrouping;
2298 // ppcoin: check 'spent' consistency between wallet and txindex
2299 // ppcoin: fix wallet spent state according to txindex
2300 void CWallet::FixSpentCoins(int& nMismatchFound, int64& nBalanceInQuestion, bool fCheckOnly)
2303 nBalanceInQuestion = 0;
2306 vector<CWalletTx*> vCoins;
2307 vCoins.reserve(mapWallet.size());
2308 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2309 vCoins.push_back(&(*it).second);
2312 BOOST_FOREACH(CWalletTx* pcoin, vCoins)
2314 // Find the corresponding transaction index
2316 if (!txdb.ReadTxIndex(pcoin->GetHash(), txindex))
2318 for (unsigned int n=0; n < pcoin->vout.size(); n++)
2320 if (IsMine(pcoin->vout[n]) && pcoin->IsSpent(n) && (txindex.vSpent.size() <= n || txindex.vSpent[n].IsNull()))
2322 printf("FixSpentCoins found lost coin %sppc %s[%d], %s\n",
2323 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2325 nBalanceInQuestion += pcoin->vout[n].nValue;
2328 pcoin->MarkUnspent(n);
2329 pcoin->WriteToDisk();
2332 else if (IsMine(pcoin->vout[n]) && !pcoin->IsSpent(n) && (txindex.vSpent.size() > n && !txindex.vSpent[n].IsNull()))
2334 printf("FixSpentCoins found spent coin %sppc %s[%d], %s\n",
2335 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2337 nBalanceInQuestion += pcoin->vout[n].nValue;
2340 pcoin->MarkSpent(n);
2341 pcoin->WriteToDisk();
2348 // ppcoin: disable transaction (only for coinstake)
2349 void CWallet::DisableTransaction(const CTransaction &tx)
2351 if (!tx.IsCoinStake() || !IsFromMe(tx))
2352 return; // only disconnecting coinstake requires marking input unspent
2355 BOOST_FOREACH(const CTxIn& txin, tx.vin)
2357 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
2358 if (mi != mapWallet.end())
2360 CWalletTx& prev = (*mi).second;
2361 if (txin.prevout.n < prev.vout.size() && IsMine(prev.vout[txin.prevout.n]))
2363 prev.MarkUnspent(txin.prevout.n);
2370 CPubKey CReserveKey::GetReservedKey()
2375 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
2377 vchPubKey = keypool.vchPubKey;
2380 printf("CReserveKey::GetReservedKey(): Warning: Using default key instead of a new key, top up your keypool!");
2381 vchPubKey = pwallet->vchDefaultKey;
2384 assert(vchPubKey.IsValid());
2388 void CReserveKey::KeepKey()
2391 pwallet->KeepKey(nIndex);
2393 vchPubKey = CPubKey();
2396 void CReserveKey::ReturnKey()
2399 pwallet->ReturnKey(nIndex);
2401 vchPubKey = CPubKey();
2404 void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
2408 CWalletDB walletdb(strWalletFile);
2410 LOCK2(cs_main, cs_wallet);
2411 BOOST_FOREACH(const int64& id, setKeyPool)
2414 if (!walletdb.ReadPool(id, keypool))
2415 throw runtime_error("GetAllReserveKeyHashes() : read failed");
2416 assert(keypool.vchPubKey.IsValid());
2417 CKeyID keyID = keypool.vchPubKey.GetID();
2418 if (!HaveKey(keyID))
2419 throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
2420 setAddress.insert(keyID);
2424 void CWallet::UpdatedTransaction(const uint256 &hashTx)
2428 // Only notify UI if this transaction is in this wallet
2429 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
2430 if (mi != mapWallet.end())
2431 NotifyTransactionChanged(this, hashTx, CT_UPDATED);
2435 void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64> &mapKeyBirth) const {
2436 mapKeyBirth.clear();
2438 // get birth times for keys with metadata
2439 for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++)
2440 if (it->second.nCreateTime)
2441 mapKeyBirth[it->first] = it->second.nCreateTime;
2443 // map in which we'll infer heights of other keys
2444 CBlockIndex *pindexMax = FindBlockByHeight(std::max(0, nBestHeight - 144)); // the tip can be reorganised; use a 144-block safety margin
2445 std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
2446 std::set<CKeyID> setKeys;
2448 BOOST_FOREACH(const CKeyID &keyid, setKeys) {
2449 if (mapKeyBirth.count(keyid) == 0)
2450 mapKeyFirstBlock[keyid] = pindexMax;
2454 // if there are no such keys, we're done
2455 if (mapKeyFirstBlock.empty())
2458 // find first block that affects those keys, if there are any left
2459 std::vector<CKeyID> vAffected;
2460 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
2461 // iterate over all wallet transactions...
2462 const CWalletTx &wtx = (*it).second;
2463 std::map<uint256, CBlockIndex*>::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
2464 if (blit != mapBlockIndex.end() && blit->second->IsInMainChain()) {
2465 // ... which are already in a block
2466 int nHeight = blit->second->nHeight;
2467 BOOST_FOREACH(const CTxOut &txout, wtx.vout) {
2468 // iterate over all their outputs
2469 ::ExtractAffectedKeys(*this, txout.scriptPubKey, vAffected);
2470 BOOST_FOREACH(const CKeyID &keyid, vAffected) {
2471 // ... and all their affected keys
2472 std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
2473 if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
2474 rit->second = blit->second;
2481 // Extract block timestamps for those keys
2482 for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
2483 mapKeyBirth[it->first] = it->second->nTime - 7200; // block times can be 2h off