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.
9 #include "ui_interface.h"
14 extern int nStakeMaxAge;
17 //////////////////////////////////////////////////////////////////////////////
22 struct CompareValueOnly
24 bool operator()(const pair<int64, pair<const CWalletTx*, unsigned int> >& t1,
25 const pair<int64, pair<const CWalletTx*, unsigned int> >& t2) const
27 return t1.first < t2.first;
31 CPubKey CWallet::GenerateNewKey()
33 bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
37 key.MakeNewKey(fCompressed);
39 // Compressed public keys were introduced in version 0.6.0
41 SetMinVersion(FEATURE_COMPRPUBKEY);
44 throw std::runtime_error("CWallet::GenerateNewKey() : AddKey failed");
45 return key.GetPubKey();
48 bool CWallet::AddKey(const CKey& key)
50 if (!CCryptoKeyStore::AddKey(key))
55 return CWalletDB(strWalletFile).WriteKey(key.GetPubKey(), key.GetPrivKey());
59 bool CWallet::AddCryptedKey(const CPubKey &vchPubKey, const vector<unsigned char> &vchCryptedSecret)
61 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
67 if (pwalletdbEncryption)
68 return pwalletdbEncryption->WriteCryptedKey(vchPubKey, vchCryptedSecret);
70 return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret);
75 bool CWallet::AddCScript(const CScript& redeemScript)
77 if (!CCryptoKeyStore::AddCScript(redeemScript))
81 return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript);
84 // ppcoin: optional setting to unlock wallet for block minting only;
85 // serves to disable the trivial sendmoney when OS account compromised
86 bool fWalletUnlockMintOnly = false;
88 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
94 CKeyingMaterial vMasterKey;
98 BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
100 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
102 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
104 if (CCryptoKeyStore::Unlock(vMasterKey))
111 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
113 bool fWasLocked = IsLocked();
120 CKeyingMaterial vMasterKey;
121 BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
123 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
125 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
127 if (CCryptoKeyStore::Unlock(vMasterKey))
129 int64 nStartTime = GetTimeMillis();
130 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
131 pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
133 nStartTime = GetTimeMillis();
134 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
135 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
137 if (pMasterKey.second.nDeriveIterations < 25000)
138 pMasterKey.second.nDeriveIterations = 25000;
140 printf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
142 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
144 if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
146 CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
157 void CWallet::SetBestChain(const CBlockLocator& loc)
159 CWalletDB walletdb(strWalletFile);
160 walletdb.WriteBestBlock(loc);
163 // This class implements an addrIncoming entry that causes pre-0.4
164 // clients to crash on startup if reading a private-key-encrypted wallet.
165 class CCorruptAddress
170 if (nType & SER_DISK)
175 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
177 if (nWalletVersion >= nVersion)
180 // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
181 if (fExplicit && nVersion > nWalletMaxVersion)
182 nVersion = FEATURE_LATEST;
184 nWalletVersion = nVersion;
186 if (nVersion > nWalletMaxVersion)
187 nWalletMaxVersion = nVersion;
191 CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile);
192 if (nWalletVersion >= 40000)
194 // Versions prior to 0.4.0 did not support the "minversion" record.
195 // Use a CCorruptAddress to make them crash instead.
196 CCorruptAddress corruptAddress;
197 pwalletdb->WriteSetting("addrIncoming", corruptAddress);
199 if (nWalletVersion > 40000)
200 pwalletdb->WriteMinVersion(nWalletVersion);
208 bool CWallet::SetMaxVersion(int nVersion)
210 // cannot downgrade below current version
211 if (nWalletVersion > nVersion)
214 nWalletMaxVersion = nVersion;
219 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
224 CKeyingMaterial vMasterKey;
225 RandAddSeedPerfmon();
227 vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
228 RAND_bytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
230 CMasterKey kMasterKey;
232 RandAddSeedPerfmon();
233 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
234 RAND_bytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
237 int64 nStartTime = GetTimeMillis();
238 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
239 kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
241 nStartTime = GetTimeMillis();
242 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
243 kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
245 if (kMasterKey.nDeriveIterations < 25000)
246 kMasterKey.nDeriveIterations = 25000;
248 printf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
250 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
252 if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
257 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
260 pwalletdbEncryption = new CWalletDB(strWalletFile);
261 if (!pwalletdbEncryption->TxnBegin())
263 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
266 if (!EncryptKeys(vMasterKey))
269 pwalletdbEncryption->TxnAbort();
270 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.
273 // Encryption was introduced in version 0.4.0
274 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
278 if (!pwalletdbEncryption->TxnCommit())
279 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.
281 delete pwalletdbEncryption;
282 pwalletdbEncryption = NULL;
286 Unlock(strWalletPassphrase);
290 // Need to completely rewrite the wallet file; if we don't, bdb might keep
291 // bits of the unencrypted private key in slack space in the database file.
292 CDB::Rewrite(strWalletFile);
295 NotifyStatusChanged(this);
300 int64 CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
302 int64 nRet = nOrderPosNext++;
304 pwalletdb->WriteOrderPosNext(nOrderPosNext);
306 CWalletDB(strWalletFile).WriteOrderPosNext(nOrderPosNext);
311 CWallet::TxItems CWallet::OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount)
313 CWalletDB walletdb(strWalletFile);
315 // First: get all CWalletTx and CAccountingEntry into a sorted-by-order multimap.
318 // Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry
319 // would make this much faster for applications that do this a lot.
320 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
322 CWalletTx* wtx = &((*it).second);
323 txOrdered.insert(make_pair(wtx->nOrderPos, TxPair(wtx, (CAccountingEntry*)0)));
326 walletdb.ListAccountCreditDebit(strAccount, acentries);
327 BOOST_FOREACH(CAccountingEntry& entry, acentries)
329 txOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
335 void CWallet::WalletUpdateSpent(const CTransaction &tx)
337 // Anytime a signature is successfully verified, it's proof the outpoint is spent.
338 // Update the wallet spent flag if it doesn't know due to wallet.dat being
339 // restored from backup or the user making copies of wallet.dat.
342 BOOST_FOREACH(const CTxIn& txin, tx.vin)
344 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
345 if (mi != mapWallet.end())
347 CWalletTx& wtx = (*mi).second;
348 if (txin.prevout.n >= wtx.vout.size())
349 printf("WalletUpdateSpent: bad wtx %s\n", wtx.GetHash().ToString().c_str());
350 else if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n]))
352 printf("WalletUpdateSpent found spent coin %snvc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
353 wtx.MarkSpent(txin.prevout.n);
355 NotifyTransactionChanged(this, txin.prevout.hash, CT_UPDATED);
362 void CWallet::MarkDirty()
366 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
367 item.second.MarkDirty();
371 bool CWallet::AddToWallet(const CWalletTx& wtxIn)
373 uint256 hash = wtxIn.GetHash();
376 // Inserts only if not already there, returns tx inserted or tx found
377 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
378 CWalletTx& wtx = (*ret.first).second;
379 wtx.BindWallet(this);
380 bool fInsertedNew = ret.second;
383 wtx.nTimeReceived = GetAdjustedTime();
384 wtx.nOrderPos = IncOrderPosNext();
386 wtx.nTimeSmart = wtx.nTimeReceived;
387 if (wtxIn.hashBlock != 0)
389 if (mapBlockIndex.count(wtxIn.hashBlock))
391 unsigned int latestNow = wtx.nTimeReceived;
392 unsigned int latestEntry = 0;
394 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
395 int64 latestTolerated = latestNow + 300;
396 std::list<CAccountingEntry> acentries;
397 TxItems txOrdered = OrderedTxItems(acentries);
398 for (TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
400 CWalletTx *const pwtx = (*it).second.first;
403 CAccountingEntry *const pacentry = (*it).second.second;
407 nSmartTime = pwtx->nTimeSmart;
409 nSmartTime = pwtx->nTimeReceived;
412 nSmartTime = pacentry->nTime;
413 if (nSmartTime <= latestTolerated)
415 latestEntry = nSmartTime;
416 if (nSmartTime > latestNow)
417 latestNow = nSmartTime;
423 unsigned int& blocktime = mapBlockIndex[wtxIn.hashBlock]->nTime;
424 wtx.nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
427 printf("AddToWallet() : found %s in block %s not in index\n",
428 wtxIn.GetHash().ToString().substr(0,10).c_str(),
429 wtxIn.hashBlock.ToString().c_str());
433 bool fUpdated = false;
437 if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
439 wtx.hashBlock = wtxIn.hashBlock;
442 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
444 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
445 wtx.nIndex = wtxIn.nIndex;
448 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
450 wtx.fFromMe = wtxIn.fFromMe;
453 fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);
457 printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
460 if (fInsertedNew || fUpdated)
461 if (!wtx.WriteToDisk())
464 // If default receiving address gets used, replace it with a new one
465 CScript scriptDefaultKey;
466 scriptDefaultKey.SetDestination(vchDefaultKey.GetID());
467 BOOST_FOREACH(const CTxOut& txout, wtx.vout)
469 if (txout.scriptPubKey == scriptDefaultKey)
471 CPubKey newDefaultKey;
472 if (GetKeyFromPool(newDefaultKey, false))
474 SetDefaultKey(newDefaultKey);
475 SetAddressBookName(vchDefaultKey.GetID(), "");
480 // since AddToWallet is called directly for self-originating transactions, check for consumption of own coins
481 WalletUpdateSpent(wtx);
483 // Notify UI of new or updated transaction
484 NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
489 // Add a transaction to the wallet, or update it.
490 // pblock is optional, but should be provided if the transaction is known to be in a block.
491 // If fUpdate is true, existing transactions will be updated.
492 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fFindBlock)
494 uint256 hash = tx.GetHash();
497 bool fExisted = mapWallet.count(hash);
498 if (fExisted && !fUpdate) return false;
499 if (fExisted || IsMine(tx) || IsFromMe(tx))
501 CWalletTx wtx(this,tx);
502 // Get merkle branch if transaction was found in a block
504 wtx.SetMerkleBranch(pblock);
505 return AddToWallet(wtx);
508 WalletUpdateSpent(tx);
513 bool CWallet::EraseFromWallet(uint256 hash)
519 if (mapWallet.erase(hash))
520 CWalletDB(strWalletFile).EraseTx(hash);
526 bool CWallet::IsMine(const CTxIn &txin) const
530 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
531 if (mi != mapWallet.end())
533 const CWalletTx& prev = (*mi).second;
534 if (txin.prevout.n < prev.vout.size())
535 if (IsMine(prev.vout[txin.prevout.n]))
542 int64 CWallet::GetDebit(const CTxIn &txin) const
546 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
547 if (mi != mapWallet.end())
549 const CWalletTx& prev = (*mi).second;
550 if (txin.prevout.n < prev.vout.size())
551 if (IsMine(prev.vout[txin.prevout.n]))
552 return prev.vout[txin.prevout.n].nValue;
558 bool CWallet::IsChange(const CTxOut& txout) const
560 CTxDestination address;
562 // TODO: fix handling of 'change' outputs. The assumption is that any
563 // payment to a TX_PUBKEYHASH that is mine but isn't in the address book
564 // is change. That assumption is likely to break when we implement multisignature
565 // wallets that return change back into a multi-signature-protected address;
566 // a better way of identifying which outputs are 'the send' and which are
567 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
568 // which output, if any, was change).
569 if (ExtractDestination(txout.scriptPubKey, address) && ::IsMine(*this, address))
572 if (!mapAddressBook.count(address))
578 int64 CWalletTx::GetTxTime() const
580 int64 n = nTimeSmart;
581 return n ? n : nTimeReceived;
584 int CWalletTx::GetRequestCount() const
586 // Returns -1 if it wasn't being tracked
589 LOCK(pwallet->cs_wallet);
590 if (IsCoinBase() || IsCoinStake())
595 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
596 if (mi != pwallet->mapRequestCount.end())
597 nRequests = (*mi).second;
602 // Did anyone request this transaction?
603 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
604 if (mi != pwallet->mapRequestCount.end())
606 nRequests = (*mi).second;
608 // How about the block it's in?
609 if (nRequests == 0 && hashBlock != 0)
611 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
612 if (mi != pwallet->mapRequestCount.end())
613 nRequests = (*mi).second;
615 nRequests = 1; // If it's in someone else's block it must have got out
623 void CWalletTx::GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, list<pair<CTxDestination, int64> >& listReceived,
624 list<pair<CTxDestination, int64> >& listSent, int64& nFee, string& strSentAccount) const
626 nGeneratedImmature = nGeneratedMature = nFee = 0;
627 listReceived.clear();
629 strSentAccount = strFromAccount;
631 if (IsCoinBase() || IsCoinStake())
633 if (GetBlocksToMaturity() > 0)
634 nGeneratedImmature = pwallet->GetCredit(*this);
636 nGeneratedMature = GetCredit();
641 int64 nDebit = GetDebit();
642 if (nDebit > 0) // debit>0 means we signed/sent this transaction
644 int64 nValueOut = GetValueOut();
645 nFee = nDebit - nValueOut;
649 BOOST_FOREACH(const CTxOut& txout, vout)
651 CTxDestination address;
652 vector<unsigned char> vchPubKey;
653 if (!ExtractDestination(txout.scriptPubKey, address))
655 printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
656 this->GetHash().ToString().c_str());
659 // Don't report 'change' txouts
660 if (nDebit > 0 && pwallet->IsChange(txout))
664 listSent.push_back(make_pair(address, txout.nValue));
666 if (pwallet->IsMine(txout))
667 listReceived.push_back(make_pair(address, txout.nValue));
672 void CWalletTx::GetAccountAmounts(const string& strAccount, int64& nGenerated, int64& nReceived,
673 int64& nSent, int64& nFee) const
675 nReceived = nSent = nFee = 0;
677 int64 allGeneratedImmature, allGeneratedMature, allFee;
678 string strSentAccount;
679 list<pair<CTxDestination, int64> > listReceived;
680 list<pair<CTxDestination, int64> > listSent;
681 GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount);
683 if (strAccount == "")
684 nGenerated = allGeneratedMature;
685 if (strAccount == strSentAccount)
687 BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& s, listSent)
692 LOCK(pwallet->cs_wallet);
693 BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listReceived)
695 if (pwallet->mapAddressBook.count(r.first))
697 map<CTxDestination, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);
698 if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)
699 nReceived += r.second;
701 else if (strAccount.empty())
703 nReceived += r.second;
709 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
713 const int COPY_DEPTH = 3;
714 if (SetMerkleBranch() < COPY_DEPTH)
716 vector<uint256> vWorkQueue;
717 BOOST_FOREACH(const CTxIn& txin, vin)
718 vWorkQueue.push_back(txin.prevout.hash);
720 // This critsect is OK because txdb is already open
722 LOCK(pwallet->cs_wallet);
723 map<uint256, const CMerkleTx*> mapWalletPrev;
724 set<uint256> setAlreadyDone;
725 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
727 uint256 hash = vWorkQueue[i];
728 if (setAlreadyDone.count(hash))
730 setAlreadyDone.insert(hash);
733 map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
734 if (mi != pwallet->mapWallet.end())
737 BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev)
738 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
740 else if (mapWalletPrev.count(hash))
742 tx = *mapWalletPrev[hash];
744 else if (!fClient && txdb.ReadDiskTx(hash, tx))
750 printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
754 int nDepth = tx.SetMerkleBranch();
755 vtxPrev.push_back(tx);
757 if (nDepth < COPY_DEPTH)
759 BOOST_FOREACH(const CTxIn& txin, tx.vin)
760 vWorkQueue.push_back(txin.prevout.hash);
766 reverse(vtxPrev.begin(), vtxPrev.end());
769 bool CWalletTx::WriteToDisk()
771 return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
774 // Scan the block chain (starting in pindexStart) for transactions
775 // from or to us. If fUpdate is true, found transactions that already
776 // exist in the wallet will be updated.
777 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
781 CBlockIndex* pindex = pindexStart;
787 block.ReadFromDisk(pindex, true);
788 BOOST_FOREACH(CTransaction& tx, block.vtx)
790 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
793 pindex = pindex->pnext;
799 int CWallet::ScanForWalletTransaction(const uint256& hashTx)
802 tx.ReadFromDisk(COutPoint(hashTx, 0));
803 if (AddToWalletIfInvolvingMe(tx, NULL, true, true))
808 void CWallet::ReacceptWalletTransactions()
816 vector<CDiskTxPos> vMissingTx;
817 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
819 CWalletTx& wtx = item.second;
820 if ((wtx.IsCoinBase() && wtx.IsSpent(0)) || (wtx.IsCoinStake() && wtx.IsSpent(1)))
824 bool fUpdated = false;
825 if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
827 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
828 if (txindex.vSpent.size() != wtx.vout.size())
830 printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %"PRIszu" != wtx.vout.size() %"PRIszu"\n", txindex.vSpent.size(), wtx.vout.size());
833 for (unsigned int i = 0; i < txindex.vSpent.size(); i++)
837 if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i]))
841 vMissingTx.push_back(txindex.vSpent[i]);
846 printf("ReacceptWalletTransactions found spent coin %snvc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
853 // Re-accept any txes of ours that aren't already in a block
854 if (!(wtx.IsCoinBase() || wtx.IsCoinStake()))
855 wtx.AcceptWalletTransaction(txdb, false);
858 if (!vMissingTx.empty())
860 // TODO: optimize this to scan just part of the block chain?
861 if (ScanForWalletTransactions(pindexGenesisBlock))
862 fRepeat = true; // Found missing transactions: re-do re-accept.
867 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
869 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
871 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
873 uint256 hash = tx.GetHash();
874 if (!txdb.ContainsTx(hash))
875 RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx);
878 if (!(IsCoinBase() || IsCoinStake()))
880 uint256 hash = GetHash();
881 if (!txdb.ContainsTx(hash))
883 printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
884 RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this);
889 void CWalletTx::RelayWalletTransaction()
892 RelayWalletTransaction(txdb);
895 void CWallet::ResendWalletTransactions()
897 // Do this infrequently and randomly to avoid giving away
898 // that these are our transactions.
899 static int64 nNextTime;
900 if (GetTime() < nNextTime)
902 bool fFirst = (nNextTime == 0);
903 nNextTime = GetTime() + GetRand(30 * 60);
907 // Only do it if there's been a new block since last time
908 static int64 nLastTime;
909 if (nTimeBestReceived < nLastTime)
911 nLastTime = GetTime();
913 // Rebroadcast any of our txes that aren't in a block yet
914 printf("ResendWalletTransactions()\n");
918 // Sort them in chronological order
919 multimap<unsigned int, CWalletTx*> mapSorted;
920 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
922 CWalletTx& wtx = item.second;
923 // Don't rebroadcast until it's had plenty of time that
924 // it should have gotten in already by now.
925 if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
926 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
928 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
930 CWalletTx& wtx = *item.second;
931 if (wtx.CheckTransaction())
932 wtx.RelayWalletTransaction(txdb);
934 printf("ResendWalletTransactions() : CheckTransaction failed for transaction %s\n", wtx.GetHash().ToString().c_str());
944 //////////////////////////////////////////////////////////////////////////////
950 int64 CWallet::GetBalance() const
955 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
957 const CWalletTx* pcoin = &(*it).second;
958 if (pcoin->IsFinal() && pcoin->IsConfirmed())
959 nTotal += pcoin->GetAvailableCredit();
966 int64 CWallet::GetUnconfirmedBalance() const
971 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
973 const CWalletTx* pcoin = &(*it).second;
974 if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
975 nTotal += pcoin->GetAvailableCredit();
981 int64 CWallet::GetImmatureBalance() const
986 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
988 const CWalletTx& pcoin = (*it).second;
989 if (pcoin.IsCoinBase() && pcoin.GetBlocksToMaturity() > 0 && pcoin.IsInMainChain())
990 nTotal += GetCredit(pcoin);
996 // populate vCoins with vector of spendable COutputs
997 void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed) const
1003 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1005 const CWalletTx* pcoin = &(*it).second;
1007 if (!pcoin->IsFinal())
1010 if (fOnlyConfirmed && !pcoin->IsConfirmed())
1013 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
1016 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
1017 if (!(pcoin->IsSpent(i)) && IsMine(pcoin->vout[i]) && pcoin->vout[i].nValue > 0)
1018 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain()));
1023 static void ApproximateBestSubset(vector<pair<int64, pair<const CWalletTx*,unsigned int> > >vValue, int64 nTotalLower, int64 nTargetValue,
1024 vector<char>& vfBest, int64& nBest, int iterations = 1000)
1026 vector<char> vfIncluded;
1028 vfBest.assign(vValue.size(), true);
1029 nBest = nTotalLower;
1031 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
1033 vfIncluded.assign(vValue.size(), false);
1035 bool fReachedTarget = false;
1036 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
1038 for (unsigned int i = 0; i < vValue.size(); i++)
1040 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
1042 nTotal += vValue[i].first;
1043 vfIncluded[i] = true;
1044 if (nTotal >= nTargetValue)
1046 fReachedTarget = true;
1050 vfBest = vfIncluded;
1052 nTotal -= vValue[i].first;
1053 vfIncluded[i] = false;
1061 // ppcoin: total coins staked (non-spendable until maturity)
1062 int64 CWallet::GetStake() const
1066 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1068 const CWalletTx* pcoin = &(*it).second;
1069 if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1070 nTotal += CWallet::GetCredit(*pcoin);
1075 int64 CWallet::GetNewMint() const
1079 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1081 const CWalletTx* pcoin = &(*it).second;
1082 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1083 nTotal += CWallet::GetCredit(*pcoin);
1088 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
1090 setCoinsRet.clear();
1093 // List of values less than target
1094 pair<int64, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
1095 coinLowestLarger.first = std::numeric_limits<int64>::max();
1096 coinLowestLarger.second.first = NULL;
1097 vector<pair<int64, pair<const CWalletTx*,unsigned int> > > vValue;
1098 int64 nTotalLower = 0;
1100 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
1102 BOOST_FOREACH(COutput output, vCoins)
1104 const CWalletTx *pcoin = output.tx;
1106 if (output.nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs))
1111 if (pcoin->nTime > nSpendTime)
1112 continue; // ppcoin: timestamp must not exceed spend time
1114 int64 n = pcoin->vout[i].nValue;
1116 pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1118 if (n == nTargetValue)
1120 setCoinsRet.insert(coin.second);
1121 nValueRet += coin.first;
1124 else if (n < nTargetValue + CENT)
1126 vValue.push_back(coin);
1129 else if (n < coinLowestLarger.first)
1131 coinLowestLarger = coin;
1135 if (nTotalLower == nTargetValue)
1137 for (unsigned int i = 0; i < vValue.size(); ++i)
1139 setCoinsRet.insert(vValue[i].second);
1140 nValueRet += vValue[i].first;
1145 if (nTotalLower < nTargetValue)
1147 if (coinLowestLarger.second.first == NULL)
1149 setCoinsRet.insert(coinLowestLarger.second);
1150 nValueRet += coinLowestLarger.first;
1154 // Solve subset sum by stochastic approximation
1155 sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
1156 vector<char> vfBest;
1159 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);
1160 if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT)
1161 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000);
1163 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
1164 // or the next bigger coin is closer), return the bigger coin
1165 if (coinLowestLarger.second.first &&
1166 ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest))
1168 setCoinsRet.insert(coinLowestLarger.second);
1169 nValueRet += coinLowestLarger.first;
1172 for (unsigned int i = 0; i < vValue.size(); i++)
1175 setCoinsRet.insert(vValue[i].second);
1176 nValueRet += vValue[i].first;
1179 if (fDebug && GetBoolArg("-printpriority"))
1182 printf("SelectCoins() best subset: ");
1183 for (unsigned int i = 0; i < vValue.size(); i++)
1185 printf("%s ", FormatMoney(vValue[i].first).c_str());
1186 printf("total %s\n", FormatMoney(nBest).c_str());
1193 bool CWallet::SelectCoins(int64 nTargetValue, unsigned int nSpendTime, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
1195 vector<COutput> vCoins;
1196 AvailableCoins(vCoins);
1198 return (SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 6, vCoins, setCoinsRet, nValueRet) ||
1199 SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 1, vCoins, setCoinsRet, nValueRet) ||
1200 SelectCoinsMinConf(nTargetValue, nSpendTime, 0, 1, vCoins, setCoinsRet, nValueRet));
1206 bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
1209 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1215 if (vecSend.empty() || nValue < 0)
1218 wtxNew.BindWallet(this);
1221 LOCK2(cs_main, cs_wallet);
1222 // txdb must be opened before the mapWallet lock
1225 nFeeRet = nTransactionFee;
1229 wtxNew.vout.clear();
1230 wtxNew.fFromMe = true;
1232 int64 nTotalValue = nValue + nFeeRet;
1233 double dPriority = 0;
1234 // vouts to the payees
1235 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1236 wtxNew.vout.push_back(CTxOut(s.second, s.first));
1238 // Choose coins to use
1239 set<pair<const CWalletTx*,unsigned int> > setCoins;
1241 if (!SelectCoins(nTotalValue, wtxNew.nTime, setCoins, nValueIn))
1243 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1245 int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
1246 dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
1249 int64 nChange = nValueIn - nValue - nFeeRet;
1250 // if sub-cent change is required, the fee must be raised to at least MIN_TX_FEE
1251 // or until nChange becomes zero
1252 // NOTE: this depends on the exact behaviour of GetMinFee
1253 if (nFeeRet < MIN_TX_FEE && nChange > 0 && nChange < CENT)
1255 int64 nMoveToFee = min(nChange, MIN_TX_FEE - nFeeRet);
1256 nChange -= nMoveToFee;
1257 nFeeRet += nMoveToFee;
1260 // ppcoin: sub-cent change is moved to fee
1261 if (nChange > 0 && nChange < MIN_TXOUT_AMOUNT)
1269 // Note: We use a new key here to keep it from being obvious which side is the change.
1270 // The drawback is that by not reusing a previous key, the change may be lost if a
1271 // backup is restored, if the backup doesn't have the new private key for the change.
1272 // If we reused the old key, it would be possible to add code to look for and
1273 // rediscover unknown transactions that were written with keys of ours to recover
1274 // post-backup change.
1276 // Reserve a new key pair from key pool
1277 CPubKey vchPubKey = reservekey.GetReservedKey();
1278 // assert(mapKeys.count(vchPubKey));
1280 // Fill a vout to ourself
1281 // TODO: pass in scriptChange instead of reservekey so
1282 // change transaction isn't always pay-to-bitcoin-address
1283 CScript scriptChange;
1284 scriptChange.SetDestination(vchPubKey.GetID());
1286 // Insert change txn at random position:
1287 vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
1288 wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
1291 reservekey.ReturnKey();
1294 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1295 wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
1299 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1300 if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
1304 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
1305 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1307 dPriority /= nBytes;
1309 // Check that enough fee is included
1310 int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
1311 int64 nMinFee = wtxNew.GetMinFee(1, false, GMF_SEND);
1313 if (nFeeRet < max(nPayFee, nMinFee))
1315 nFeeRet = max(nPayFee, nMinFee);
1319 // Fill vtxPrev by copying from previous transactions vtxPrev
1320 wtxNew.AddSupportingTransactions(txdb);
1321 wtxNew.fTimeReceivedIsTxTime = true;
1330 bool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
1332 vector< pair<CScript, int64> > vecSend;
1333 vecSend.push_back(make_pair(scriptPubKey, nValue));
1334 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet);
1337 // ppcoin: create coin stake transaction
1338 bool CWallet::CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int64 nSearchInterval, CTransaction& txNew)
1340 // The following split & combine thresholds are important to security
1341 // Should not be adjusted if you don't understand the consequences
1342 static unsigned int nStakeSplitAge = (60 * 60 * 24 * 90);
1343 int64 nCombineThreshold = GetProofOfWorkReward(GetLastBlockIndex(pindexBest, false)->nBits) / 3;
1345 CBigNum bnTargetPerCoinDay;
1346 bnTargetPerCoinDay.SetCompact(nBits);
1348 LOCK2(cs_main, cs_wallet);
1351 // Mark coin stake transaction
1352 CScript scriptEmpty;
1353 scriptEmpty.clear();
1354 txNew.vout.push_back(CTxOut(0, scriptEmpty));
1355 // Choose coins to use
1356 int64 nBalance = GetBalance();
1357 int64 nReserveBalance = 0;
1358 if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
1359 return error("CreateCoinStake : invalid reserve balance amount");
1360 if (nBalance <= nReserveBalance)
1362 set<pair<const CWalletTx*,unsigned int> > setCoins;
1363 vector<const CWalletTx*> vwtxPrev;
1365 if (!SelectCoins(nBalance - nReserveBalance, txNew.nTime, setCoins, nValueIn))
1367 if (setCoins.empty())
1370 CScript scriptPubKeyKernel;
1371 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1375 if (!txdb.ReadTxIndex(pcoin.first->GetHash(), txindex))
1378 // Read block header
1380 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
1382 static int nMaxStakeSearchInterval = 60;
1383 if (block.GetBlockTime() + nStakeMinAge > txNew.nTime - nMaxStakeSearchInterval)
1384 continue; // only count coins meeting min age requirement
1386 bool fKernelFound = false;
1387 for (unsigned int n=0; n<min(nSearchInterval,(int64)nMaxStakeSearchInterval) && !fKernelFound && !fShutdown; n++)
1389 // Search backward in time from the given txNew timestamp
1390 // Search nSearchInterval seconds back up to nMaxStakeSearchInterval
1391 uint256 hashProofOfStake = 0;
1392 COutPoint prevoutStake = COutPoint(pcoin.first->GetHash(), pcoin.second);
1393 if (CheckStakeKernelHash(nBits, block, txindex.pos.nTxPos - txindex.pos.nBlockPos, *pcoin.first, prevoutStake, txNew.nTime - n, hashProofOfStake))
1396 if (fDebug && GetBoolArg("-printcoinstake"))
1397 printf("CreateCoinStake : kernel found\n");
1398 vector<valtype> vSolutions;
1399 txnouttype whichType;
1400 CScript scriptPubKeyOut;
1401 scriptPubKeyKernel = pcoin.first->vout[pcoin.second].scriptPubKey;
1402 if (!Solver(scriptPubKeyKernel, whichType, vSolutions))
1404 if (fDebug && GetBoolArg("-printcoinstake"))
1405 printf("CreateCoinStake : failed to parse kernel\n");
1408 if (fDebug && GetBoolArg("-printcoinstake"))
1409 printf("CreateCoinStake : parsed kernel type=%d\n", whichType);
1410 if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH)
1412 if (fDebug && GetBoolArg("-printcoinstake"))
1413 printf("CreateCoinStake : no support for kernel type=%d\n", whichType);
1414 break; // only support pay to public key and pay to address
1416 if (whichType == TX_PUBKEYHASH) // pay to address type
1418 // convert to pay to public key type
1420 if (!keystore.GetKey(uint160(vSolutions[0]), key))
1422 if (fDebug && GetBoolArg("-printcoinstake"))
1423 printf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1424 break; // unable to find corresponding public key
1426 scriptPubKeyOut << key.GetPubKey() << OP_CHECKSIG;
1429 scriptPubKeyOut = scriptPubKeyKernel;
1432 txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1433 nCredit += pcoin.first->vout[pcoin.second].nValue;
1434 vwtxPrev.push_back(pcoin.first);
1435 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
1436 if (block.GetBlockTime() + nStakeSplitAge > txNew.nTime)
1437 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut)); //split stake
1438 if (fDebug && GetBoolArg("-printcoinstake"))
1439 printf("CreateCoinStake : added kernel type=%d\n", whichType);
1440 fKernelFound = true;
1444 if (fKernelFound || fShutdown)
1445 break; // if kernel is found stop searching
1447 if (nCredit == 0 || nCredit > nBalance - nReserveBalance)
1449 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1451 // Attempt to add more inputs
1452 // Only add coins of the same key/address as kernel
1453 if (txNew.vout.size() == 2 && ((pcoin.first->vout[pcoin.second].scriptPubKey == scriptPubKeyKernel || pcoin.first->vout[pcoin.second].scriptPubKey == txNew.vout[1].scriptPubKey))
1454 && pcoin.first->GetHash() != txNew.vin[0].prevout.hash)
1456 // Stop adding more inputs if already too many inputs
1457 if (txNew.vin.size() >= 100)
1459 // Stop adding more inputs if value is already pretty significant
1460 if (nCredit > nCombineThreshold)
1462 // Stop adding inputs if reached reserve limit
1463 if (nCredit + pcoin.first->vout[pcoin.second].nValue > nBalance - nReserveBalance)
1465 // Do not add additional significant input
1466 if (pcoin.first->vout[pcoin.second].nValue > nCombineThreshold)
1468 // Do not add input that is still too young
1469 if (pcoin.first->nTime + nStakeMaxAge > txNew.nTime)
1471 txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1472 nCredit += pcoin.first->vout[pcoin.second].nValue;
1473 vwtxPrev.push_back(pcoin.first);
1476 // Calculate coin age reward
1480 if (!txNew.GetCoinAge(txdb, nCoinAge))
1481 return error("CreateCoinStake : failed to calculate coin age");
1482 nCredit += GetProofOfStakeReward(nCoinAge, nBits, txNew.nTime);
1488 // Set output amount
1489 if (txNew.vout.size() == 3)
1491 txNew.vout[1].nValue = ((nCredit - nMinFee) / 2 / CENT) * CENT;
1492 txNew.vout[2].nValue = nCredit - nMinFee - txNew.vout[1].nValue;
1495 txNew.vout[1].nValue = nCredit - nMinFee;
1499 BOOST_FOREACH(const CWalletTx* pcoin, vwtxPrev)
1501 if (!SignSignature(*this, *pcoin, txNew, nIn++))
1502 return error("CreateCoinStake : failed to sign coinstake");
1506 unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION);
1507 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1508 return error("CreateCoinStake : exceeded coinstake size limit");
1510 // Check enough fee is paid
1511 if (nMinFee < txNew.GetMinFee() - MIN_TX_FEE)
1513 nMinFee = txNew.GetMinFee() - MIN_TX_FEE;
1514 continue; // try signing again
1518 if (fDebug && GetBoolArg("-printfee"))
1519 printf("CreateCoinStake : fee for coinstake %s\n", FormatMoney(nMinFee).c_str());
1524 // Successfully generated coinstake
1529 // Call after CreateTransaction unless you want to abort
1530 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
1533 LOCK2(cs_main, cs_wallet);
1534 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
1536 // This is only to keep the database open to defeat the auto-flush for the
1537 // duration of this scope. This is the only place where this optimization
1538 // maybe makes sense; please don't do it anywhere else.
1539 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
1541 // Take key pair from key pool so it won't be used again
1542 reservekey.KeepKey();
1544 // Add tx to wallet, because if it has change it's also ours,
1545 // otherwise just for transaction history.
1546 AddToWallet(wtxNew);
1548 // Mark old coins as spent
1549 set<CWalletTx*> setCoins;
1550 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
1552 CWalletTx &coin = mapWallet[txin.prevout.hash];
1553 coin.BindWallet(this);
1554 coin.MarkSpent(txin.prevout.n);
1556 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
1563 // Track how many getdata requests our transaction gets
1564 mapRequestCount[wtxNew.GetHash()] = 0;
1567 if (!wtxNew.AcceptToMemoryPool())
1569 // This must not fail. The transaction has already been signed and recorded.
1570 printf("CommitTransaction() : Error: Transaction not valid");
1573 wtxNew.RelayWalletTransaction();
1581 string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1583 CReserveKey reservekey(this);
1588 string strError = _("Error: Wallet locked, unable to create transaction ");
1589 printf("SendMoney() : %s", strError.c_str());
1592 if (fWalletUnlockMintOnly)
1594 string strError = _("Error: Wallet unlocked for block minting only, unable to create transaction.");
1595 printf("SendMoney() : %s", strError.c_str());
1598 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
1601 if (nValue + nFeeRequired > GetBalance())
1602 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());
1604 strError = _("Error: Transaction creation failed ");
1605 printf("SendMoney() : %s", strError.c_str());
1609 if (fAskFee && !uiInterface.ThreadSafeAskFee(nFeeRequired, _("Sending...")))
1612 if (!CommitTransaction(wtxNew, reservekey))
1613 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.");
1620 string CWallet::SendMoneyToDestination(const CTxDestination& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1624 return _("Invalid amount");
1625 if (nValue + nTransactionFee > GetBalance())
1626 return _("Insufficient funds");
1628 // Parse Bitcoin address
1629 CScript scriptPubKey;
1630 scriptPubKey.SetDestination(address);
1632 return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
1638 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
1642 fFirstRunRet = false;
1643 DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
1644 if (nLoadWalletRet == DB_NEED_REWRITE)
1646 if (CDB::Rewrite(strWalletFile, "\x04pool"))
1649 // Note: can't top-up keypool here, because wallet is locked.
1650 // User will be prompted to unlock wallet the next operation
1651 // the requires a new key.
1655 if (nLoadWalletRet != DB_LOAD_OK)
1656 return nLoadWalletRet;
1657 fFirstRunRet = !vchDefaultKey.IsValid();
1659 NewThread(ThreadFlushWalletDB, &strWalletFile);
1664 bool CWallet::SetAddressBookName(const CTxDestination& address, const string& strName)
1666 std::map<CTxDestination, std::string>::iterator mi = mapAddressBook.find(address);
1667 mapAddressBook[address] = strName;
1668 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address), (mi == mapAddressBook.end()) ? CT_NEW : CT_UPDATED);
1671 return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName);
1674 bool CWallet::DelAddressBookName(const CTxDestination& address)
1676 mapAddressBook.erase(address);
1677 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address), CT_DELETED);
1680 return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString());
1684 void CWallet::PrintWallet(const CBlock& block)
1688 if (block.IsProofOfWork() && mapWallet.count(block.vtx[0].GetHash()))
1690 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
1691 printf(" mine: %d %d %"PRI64d"", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
1693 if (block.IsProofOfStake() && mapWallet.count(block.vtx[1].GetHash()))
1695 CWalletTx& wtx = mapWallet[block.vtx[1].GetHash()];
1696 printf(" stake: %d %d %"PRI64d"", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
1703 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
1707 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
1708 if (mi != mapWallet.end())
1717 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
1721 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
1724 vchDefaultKey = vchPubKey;
1728 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
1730 if (!pwallet->fFileBacked)
1732 strWalletFileOut = pwallet->strWalletFile;
1737 // Mark old keypool keys as used,
1738 // and generate all new keys
1740 bool CWallet::NewKeyPool()
1744 CWalletDB walletdb(strWalletFile);
1745 BOOST_FOREACH(int64 nIndex, setKeyPool)
1746 walletdb.ErasePool(nIndex);
1752 int64 nKeys = max(GetArg("-keypool", 100), (int64)0);
1753 for (int i = 0; i < nKeys; i++)
1756 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
1757 setKeyPool.insert(nIndex);
1759 printf("CWallet::NewKeyPool wrote %"PRI64d" new keys\n", nKeys);
1764 bool CWallet::TopUpKeyPool()
1772 CWalletDB walletdb(strWalletFile);
1775 unsigned int nTargetSize = max(GetArg("-keypool", 100), 0LL);
1776 while (setKeyPool.size() < (nTargetSize + 1))
1779 if (!setKeyPool.empty())
1780 nEnd = *(--setKeyPool.end()) + 1;
1781 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
1782 throw runtime_error("TopUpKeyPool() : writing generated key failed");
1783 setKeyPool.insert(nEnd);
1784 printf("keypool added key %"PRI64d", size=%"PRIszu"\n", nEnd, setKeyPool.size());
1790 void CWallet::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool)
1793 keypool.vchPubKey = CPubKey();
1800 // Get the oldest key
1801 if(setKeyPool.empty())
1804 CWalletDB walletdb(strWalletFile);
1806 nIndex = *(setKeyPool.begin());
1807 setKeyPool.erase(setKeyPool.begin());
1808 if (!walletdb.ReadPool(nIndex, keypool))
1809 throw runtime_error("ReserveKeyFromKeyPool() : read failed");
1810 if (!HaveKey(keypool.vchPubKey.GetID()))
1811 throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
1812 assert(keypool.vchPubKey.IsValid());
1813 if (fDebug && GetBoolArg("-printkeypool"))
1814 printf("keypool reserve %"PRI64d"\n", nIndex);
1818 int64 CWallet::AddReserveKey(const CKeyPool& keypool)
1821 LOCK2(cs_main, cs_wallet);
1822 CWalletDB walletdb(strWalletFile);
1824 int64 nIndex = 1 + *(--setKeyPool.end());
1825 if (!walletdb.WritePool(nIndex, keypool))
1826 throw runtime_error("AddReserveKey() : writing added key failed");
1827 setKeyPool.insert(nIndex);
1833 void CWallet::KeepKey(int64 nIndex)
1835 // Remove from key pool
1838 CWalletDB walletdb(strWalletFile);
1839 walletdb.ErasePool(nIndex);
1842 printf("keypool keep %"PRI64d"\n", nIndex);
1845 void CWallet::ReturnKey(int64 nIndex)
1847 // Return to key pool
1850 setKeyPool.insert(nIndex);
1853 printf("keypool return %"PRI64d"\n", nIndex);
1856 bool CWallet::GetKeyFromPool(CPubKey& result, bool fAllowReuse)
1862 ReserveKeyFromKeyPool(nIndex, keypool);
1865 if (fAllowReuse && vchDefaultKey.IsValid())
1867 result = vchDefaultKey;
1870 if (IsLocked()) return false;
1871 result = GenerateNewKey();
1875 result = keypool.vchPubKey;
1880 int64 CWallet::GetOldestKeyPoolTime()
1884 ReserveKeyFromKeyPool(nIndex, keypool);
1888 return keypool.nTime;
1891 std::map<CTxDestination, int64> CWallet::GetAddressBalances()
1893 map<CTxDestination, int64> balances;
1897 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
1899 CWalletTx *pcoin = &walletEntry.second;
1901 if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
1904 if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0)
1907 int nDepth = pcoin->GetDepthInMainChain();
1908 if (nDepth < (pcoin->IsFromMe() ? 0 : 1))
1911 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
1913 CTxDestination addr;
1914 if (!IsMine(pcoin->vout[i]))
1916 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr))
1919 int64 n = pcoin->IsSpent(i) ? 0 : pcoin->vout[i].nValue;
1921 if (!balances.count(addr))
1923 balances[addr] += n;
1931 set< set<CTxDestination> > CWallet::GetAddressGroupings()
1933 set< set<CTxDestination> > groupings;
1934 set<CTxDestination> grouping;
1936 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
1938 CWalletTx *pcoin = &walletEntry.second;
1940 if (pcoin->vin.size() > 0 && IsMine(pcoin->vin[0]))
1942 // group all input addresses with each other
1943 BOOST_FOREACH(CTxIn txin, pcoin->vin)
1945 CTxDestination address;
1946 if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
1948 grouping.insert(address);
1951 // group change with input addresses
1952 BOOST_FOREACH(CTxOut txout, pcoin->vout)
1953 if (IsChange(txout))
1955 CWalletTx tx = mapWallet[pcoin->vin[0].prevout.hash];
1956 CTxDestination txoutAddr;
1957 if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
1959 grouping.insert(txoutAddr);
1961 groupings.insert(grouping);
1965 // group lone addrs by themselves
1966 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
1967 if (IsMine(pcoin->vout[i]))
1969 CTxDestination address;
1970 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address))
1972 grouping.insert(address);
1973 groupings.insert(grouping);
1978 set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
1979 map< CTxDestination, set<CTxDestination>* > setmap; // map addresses to the unique group containing it
1980 BOOST_FOREACH(set<CTxDestination> grouping, groupings)
1982 // make a set of all the groups hit by this new group
1983 set< set<CTxDestination>* > hits;
1984 map< CTxDestination, set<CTxDestination>* >::iterator it;
1985 BOOST_FOREACH(CTxDestination address, grouping)
1986 if ((it = setmap.find(address)) != setmap.end())
1987 hits.insert((*it).second);
1989 // merge all hit groups into a new single group and delete old groups
1990 set<CTxDestination>* merged = new set<CTxDestination>(grouping);
1991 BOOST_FOREACH(set<CTxDestination>* hit, hits)
1993 merged->insert(hit->begin(), hit->end());
1994 uniqueGroupings.erase(hit);
1997 uniqueGroupings.insert(merged);
2000 BOOST_FOREACH(CTxDestination element, *merged)
2001 setmap[element] = merged;
2004 set< set<CTxDestination> > ret;
2005 BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings)
2007 ret.insert(*uniqueGrouping);
2008 delete uniqueGrouping;
2014 // ppcoin: check 'spent' consistency between wallet and txindex
2015 // ppcoin: fix wallet spent state according to txindex
2016 void CWallet::FixSpentCoins(int& nMismatchFound, int64& nBalanceInQuestion, bool fCheckOnly)
2019 nBalanceInQuestion = 0;
2022 vector<CWalletTx*> vCoins;
2023 vCoins.reserve(mapWallet.size());
2024 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2025 vCoins.push_back(&(*it).second);
2028 BOOST_FOREACH(CWalletTx* pcoin, vCoins)
2030 // Find the corresponding transaction index
2032 if (!txdb.ReadTxIndex(pcoin->GetHash(), txindex))
2034 for (unsigned int n=0; n < pcoin->vout.size(); n++)
2036 if (IsMine(pcoin->vout[n]) && pcoin->IsSpent(n) && (txindex.vSpent.size() <= n || txindex.vSpent[n].IsNull()))
2038 printf("FixSpentCoins found lost coin %sppc %s[%d], %s\n",
2039 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2041 nBalanceInQuestion += pcoin->vout[n].nValue;
2044 pcoin->MarkUnspent(n);
2045 pcoin->WriteToDisk();
2048 else if (IsMine(pcoin->vout[n]) && !pcoin->IsSpent(n) && (txindex.vSpent.size() > n && !txindex.vSpent[n].IsNull()))
2050 printf("FixSpentCoins found spent coin %sppc %s[%d], %s\n",
2051 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2053 nBalanceInQuestion += pcoin->vout[n].nValue;
2056 pcoin->MarkSpent(n);
2057 pcoin->WriteToDisk();
2064 // ppcoin: disable transaction (only for coinstake)
2065 void CWallet::DisableTransaction(const CTransaction &tx)
2067 if (!tx.IsCoinStake() || !IsFromMe(tx))
2068 return; // only disconnecting coinstake requires marking input unspent
2071 BOOST_FOREACH(const CTxIn& txin, tx.vin)
2073 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
2074 if (mi != mapWallet.end())
2076 CWalletTx& prev = (*mi).second;
2077 if (txin.prevout.n < prev.vout.size() && IsMine(prev.vout[txin.prevout.n]))
2079 prev.MarkUnspent(txin.prevout.n);
2086 CPubKey CReserveKey::GetReservedKey()
2091 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
2093 vchPubKey = keypool.vchPubKey;
2096 printf("CReserveKey::GetReservedKey(): Warning: Using default key instead of a new key, top up your keypool!");
2097 vchPubKey = pwallet->vchDefaultKey;
2100 assert(vchPubKey.IsValid());
2104 void CReserveKey::KeepKey()
2107 pwallet->KeepKey(nIndex);
2109 vchPubKey = CPubKey();
2112 void CReserveKey::ReturnKey()
2115 pwallet->ReturnKey(nIndex);
2117 vchPubKey = CPubKey();
2120 void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress)
2124 CWalletDB walletdb(strWalletFile);
2126 LOCK2(cs_main, cs_wallet);
2127 BOOST_FOREACH(const int64& id, setKeyPool)
2130 if (!walletdb.ReadPool(id, keypool))
2131 throw runtime_error("GetAllReserveKeyHashes() : read failed");
2132 assert(keypool.vchPubKey.IsValid());
2133 CKeyID keyID = keypool.vchPubKey.GetID();
2134 if (!HaveKey(keyID))
2135 throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
2136 setAddress.insert(keyID);
2140 void CWallet::UpdatedTransaction(const uint256 &hashTx)
2144 // Only notify UI if this transaction is in this wallet
2145 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
2146 if (mi != mapWallet.end())
2147 NotifyTransactionChanged(this, hashTx, CT_UPDATED);