1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Copyright (c) 2011-2012 The PPCoin developers
4 // Distributed under the MIT/X11 software license, see the accompanying
5 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
10 #include "checkpoints.h"
11 #include "ui_interface.h"
16 //////////////////////////////////////////////////////////////////////////////
21 std::vector<unsigned char> CWallet::GenerateNewKey()
23 bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
27 key.MakeNewKey(fCompressed);
29 // Compressed public keys were introduced in version 0.6.0
31 SetMinVersion(FEATURE_COMPRPUBKEY);
34 throw std::runtime_error("CWallet::GenerateNewKey() : AddKey failed");
35 return key.GetPubKey();
38 bool CWallet::AddKey(const CKey& key)
40 if (!CCryptoKeyStore::AddKey(key))
45 return CWalletDB(strWalletFile).WriteKey(key.GetPubKey(), key.GetPrivKey());
49 bool CWallet::AddCryptedKey(const vector<unsigned char> &vchPubKey, const vector<unsigned char> &vchCryptedSecret)
51 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
57 if (pwalletdbEncryption)
58 return pwalletdbEncryption->WriteCryptedKey(vchPubKey, vchCryptedSecret);
60 return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret);
65 bool CWallet::AddCScript(const CScript& redeemScript)
67 if (!CCryptoKeyStore::AddCScript(redeemScript))
71 return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript);
74 // ppcoin: optional setting to create coinstake only when unlocked;
75 // serves to disable the trivial sendmoney when OS account compromised
76 bool fWalletUnlockMintOnly = false;
78 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
84 CKeyingMaterial vMasterKey;
88 BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
90 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
92 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
94 if (CCryptoKeyStore::Unlock(vMasterKey))
101 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
103 bool fWasLocked = IsLocked();
110 CKeyingMaterial vMasterKey;
111 BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
113 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
115 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
117 if (CCryptoKeyStore::Unlock(vMasterKey))
119 int64 nStartTime = GetTimeMillis();
120 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
121 pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
123 nStartTime = GetTimeMillis();
124 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
125 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
127 if (pMasterKey.second.nDeriveIterations < 25000)
128 pMasterKey.second.nDeriveIterations = 25000;
130 printf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
132 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
134 if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
136 CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
147 void CWallet::SetBestChain(const CBlockLocator& loc)
149 CWalletDB walletdb(strWalletFile);
150 walletdb.WriteBestBlock(loc);
153 // This class implements an addrIncoming entry that causes pre-0.4
154 // clients to crash on startup if reading a private-key-encrypted wallet.
155 class CCorruptAddress
160 if (nType & SER_DISK)
165 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
167 if (nWalletVersion >= nVersion)
170 // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
171 if (fExplicit && nVersion > nWalletMaxVersion)
172 nVersion = FEATURE_LATEST;
174 nWalletVersion = nVersion;
176 if (nVersion > nWalletMaxVersion)
177 nWalletMaxVersion = nVersion;
181 CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile);
182 if (nWalletVersion >= 40000)
184 // Versions prior to 0.4.0 did not support the "minversion" record.
185 // Use a CCorruptAddress to make them crash instead.
186 CCorruptAddress corruptAddress;
187 pwalletdb->WriteSetting("addrIncoming", corruptAddress);
189 if (nWalletVersion > 40000)
190 pwalletdb->WriteMinVersion(nWalletVersion);
198 bool CWallet::SetMaxVersion(int nVersion)
200 // cannot downgrade below current version
201 if (nWalletVersion > nVersion)
204 nWalletMaxVersion = nVersion;
209 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
214 CKeyingMaterial vMasterKey;
215 RandAddSeedPerfmon();
217 vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
218 RAND_bytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
220 CMasterKey kMasterKey;
222 RandAddSeedPerfmon();
223 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
224 RAND_bytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
227 int64 nStartTime = GetTimeMillis();
228 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
229 kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
231 nStartTime = GetTimeMillis();
232 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
233 kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
235 if (kMasterKey.nDeriveIterations < 25000)
236 kMasterKey.nDeriveIterations = 25000;
238 printf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
240 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
242 if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
247 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
250 pwalletdbEncryption = new CWalletDB(strWalletFile);
251 if (!pwalletdbEncryption->TxnBegin())
253 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
256 if (!EncryptKeys(vMasterKey))
259 pwalletdbEncryption->TxnAbort();
260 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.
263 // Encryption was introduced in version 0.4.0
264 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
268 if (!pwalletdbEncryption->TxnCommit())
269 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.
271 delete pwalletdbEncryption;
272 pwalletdbEncryption = NULL;
276 Unlock(strWalletPassphrase);
280 // Need to completely rewrite the wallet file; if we don't, bdb might keep
281 // bits of the unencrypted private key in slack space in the database file.
282 CDB::Rewrite(strWalletFile);
288 void CWallet::WalletUpdateSpent(const CTransaction &tx)
290 // Anytime a signature is successfully verified, it's proof the outpoint is spent.
291 // Update the wallet spent flag if it doesn't know due to wallet.dat being
292 // restored from backup or the user making copies of wallet.dat.
295 BOOST_FOREACH(const CTxIn& txin, tx.vin)
297 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
298 if (mi != mapWallet.end())
300 CWalletTx& wtx = (*mi).second;
301 if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n]))
303 printf("WalletUpdateSpent found spent coin %sppc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
304 wtx.MarkSpent(txin.prevout.n);
306 vWalletUpdated.push_back(txin.prevout.hash);
313 void CWallet::MarkDirty()
317 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
318 item.second.MarkDirty();
322 bool CWallet::AddToWallet(const CWalletTx& wtxIn)
324 uint256 hash = wtxIn.GetHash();
327 // Inserts only if not already there, returns tx inserted or tx found
328 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
329 CWalletTx& wtx = (*ret.first).second;
330 wtx.BindWallet(this);
331 bool fInsertedNew = ret.second;
333 wtx.nTimeReceived = GetAdjustedTime();
335 bool fUpdated = false;
339 if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
341 wtx.hashBlock = wtxIn.hashBlock;
344 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
346 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
347 wtx.nIndex = wtxIn.nIndex;
350 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
352 wtx.fFromMe = wtxIn.fFromMe;
355 fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);
359 printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
362 if (fInsertedNew || fUpdated)
363 if (!wtx.WriteToDisk())
366 // If default receiving address gets used, replace it with a new one
367 CScript scriptDefaultKey;
368 scriptDefaultKey.SetBitcoinAddress(vchDefaultKey);
369 BOOST_FOREACH(const CTxOut& txout, wtx.vout)
371 if (txout.scriptPubKey == scriptDefaultKey)
373 std::vector<unsigned char> newDefaultKey;
374 if (GetKeyFromPool(newDefaultKey, false))
376 SetDefaultKey(newDefaultKey);
377 SetAddressBookName(CBitcoinAddress(vchDefaultKey), "");
383 vWalletUpdated.push_back(hash);
385 // since AddToWallet is called directly for self-originating transactions, check for consumption of own coins
386 WalletUpdateSpent(wtx);
394 // Add a transaction to the wallet, or update it.
395 // pblock is optional, but should be provided if the transaction is known to be in a block.
396 // If fUpdate is true, existing transactions will be updated.
397 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fFindBlock)
399 uint256 hash = tx.GetHash();
402 bool fExisted = mapWallet.count(hash);
403 if (fExisted && !fUpdate) return false;
404 if (fExisted || IsMine(tx) || IsFromMe(tx))
406 CWalletTx wtx(this,tx);
407 // Get merkle branch if transaction was found in a block
409 wtx.SetMerkleBranch(pblock);
410 return AddToWallet(wtx);
413 WalletUpdateSpent(tx);
418 bool CWallet::EraseFromWallet(uint256 hash)
424 if (mapWallet.erase(hash))
425 CWalletDB(strWalletFile).EraseTx(hash);
431 bool CWallet::IsMine(const CTxIn &txin) const
435 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
436 if (mi != mapWallet.end())
438 const CWalletTx& prev = (*mi).second;
439 if (txin.prevout.n < prev.vout.size())
440 if (IsMine(prev.vout[txin.prevout.n]))
447 int64 CWallet::GetDebit(const CTxIn &txin) const
451 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
452 if (mi != mapWallet.end())
454 const CWalletTx& prev = (*mi).second;
455 if (txin.prevout.n < prev.vout.size())
456 if (IsMine(prev.vout[txin.prevout.n]))
457 return prev.vout[txin.prevout.n].nValue;
463 bool CWallet::IsChange(const CTxOut& txout) const
465 CBitcoinAddress address;
467 // TODO: fix handling of 'change' outputs. The assumption is that any
468 // payment to a TX_PUBKEYHASH that is mine but isn't in the address book
469 // is change. That assumption is likely to break when we implement multisignature
470 // wallets that return change back into a multi-signature-protected address;
471 // a better way of identifying which outputs are 'the send' and which are
472 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
473 // which output, if any, was change).
474 if (ExtractAddress(txout.scriptPubKey, address) && HaveKey(address))
477 if (!mapAddressBook.count(address))
483 int64 CWalletTx::GetTxTime() const
485 return nTimeReceived;
488 int CWalletTx::GetRequestCount() const
490 // Returns -1 if it wasn't being tracked
493 LOCK(pwallet->cs_wallet);
494 if (IsCoinBase() || IsCoinStake())
499 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
500 if (mi != pwallet->mapRequestCount.end())
501 nRequests = (*mi).second;
506 // Did anyone request this transaction?
507 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
508 if (mi != pwallet->mapRequestCount.end())
510 nRequests = (*mi).second;
512 // How about the block it's in?
513 if (nRequests == 0 && hashBlock != 0)
515 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
516 if (mi != pwallet->mapRequestCount.end())
517 nRequests = (*mi).second;
519 nRequests = 1; // If it's in someone else's block it must have got out
527 void CWalletTx::GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, list<pair<CBitcoinAddress, int64> >& listReceived,
528 list<pair<CBitcoinAddress, int64> >& listSent, int64& nFee, string& strSentAccount) const
530 nGeneratedImmature = nGeneratedMature = nFee = 0;
531 listReceived.clear();
533 strSentAccount = strFromAccount;
535 if (IsCoinBase() || IsCoinStake())
537 if (GetBlocksToMaturity() > 0)
538 nGeneratedImmature = pwallet->GetCredit(*this);
540 nGeneratedMature = GetCredit();
545 int64 nDebit = GetDebit();
546 if (nDebit > 0) // debit>0 means we signed/sent this transaction
548 int64 nValueOut = GetValueOut();
549 nFee = nDebit - nValueOut;
553 BOOST_FOREACH(const CTxOut& txout, vout)
555 CBitcoinAddress address;
556 vector<unsigned char> vchPubKey;
557 if (!ExtractAddress(txout.scriptPubKey, address))
559 printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
560 this->GetHash().ToString().c_str());
561 address = " unknown ";
564 // Don't report 'change' txouts
565 if (nDebit > 0 && pwallet->IsChange(txout))
569 listSent.push_back(make_pair(address, txout.nValue));
571 if (pwallet->IsMine(txout))
572 listReceived.push_back(make_pair(address, txout.nValue));
577 void CWalletTx::GetAccountAmounts(const string& strAccount, int64& nGenerated, int64& nReceived,
578 int64& nSent, int64& nFee) const
580 nGenerated = nReceived = nSent = nFee = 0;
582 int64 allGeneratedImmature, allGeneratedMature, allFee;
583 allGeneratedImmature = allGeneratedMature = allFee = 0;
584 string strSentAccount;
585 list<pair<CBitcoinAddress, int64> > listReceived;
586 list<pair<CBitcoinAddress, int64> > listSent;
587 GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount);
589 if (strAccount == "")
590 nGenerated = allGeneratedMature;
591 if (strAccount == strSentAccount)
593 BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress,int64)& s, listSent)
598 LOCK(pwallet->cs_wallet);
599 BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress,int64)& r, listReceived)
601 if (pwallet->mapAddressBook.count(r.first))
603 map<CBitcoinAddress, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);
604 if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)
605 nReceived += r.second;
607 else if (strAccount.empty())
609 nReceived += r.second;
615 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
619 const int COPY_DEPTH = 3;
620 if (SetMerkleBranch() < COPY_DEPTH)
622 vector<uint256> vWorkQueue;
623 BOOST_FOREACH(const CTxIn& txin, vin)
624 vWorkQueue.push_back(txin.prevout.hash);
626 // This critsect is OK because txdb is already open
628 LOCK(pwallet->cs_wallet);
629 map<uint256, const CMerkleTx*> mapWalletPrev;
630 set<uint256> setAlreadyDone;
631 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
633 uint256 hash = vWorkQueue[i];
634 if (setAlreadyDone.count(hash))
636 setAlreadyDone.insert(hash);
639 map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
640 if (mi != pwallet->mapWallet.end())
643 BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev)
644 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
646 else if (mapWalletPrev.count(hash))
648 tx = *mapWalletPrev[hash];
650 else if (!fClient && txdb.ReadDiskTx(hash, tx))
656 printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
660 int nDepth = tx.SetMerkleBranch();
661 vtxPrev.push_back(tx);
663 if (nDepth < COPY_DEPTH)
665 BOOST_FOREACH(const CTxIn& txin, tx.vin)
666 vWorkQueue.push_back(txin.prevout.hash);
672 reverse(vtxPrev.begin(), vtxPrev.end());
675 bool CWalletTx::WriteToDisk()
677 return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
680 // Scan the block chain (starting in pindexStart) for transactions
681 // from or to us. If fUpdate is true, found transactions that already
682 // exist in the wallet will be updated.
683 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
687 CBlockIndex* pindex = pindexStart;
693 block.ReadFromDisk(pindex, true);
694 BOOST_FOREACH(CTransaction& tx, block.vtx)
696 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
699 pindex = pindex->pnext;
705 int CWallet::ScanForWalletTransaction(const uint256& hashTx)
708 tx.ReadFromDisk(COutPoint(hashTx, 0));
709 if (AddToWalletIfInvolvingMe(tx, NULL, true, true))
714 void CWallet::ReacceptWalletTransactions()
722 vector<CDiskTxPos> vMissingTx;
723 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
725 CWalletTx& wtx = item.second;
726 if ((wtx.IsCoinBase() && wtx.IsSpent(0)) || (wtx.IsCoinStake() && wtx.IsSpent(1)))
730 bool fUpdated = false;
731 if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
733 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
734 if (txindex.vSpent.size() != wtx.vout.size())
736 printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %d != wtx.vout.size() %d\n", txindex.vSpent.size(), wtx.vout.size());
739 for (unsigned int i = 0; i < txindex.vSpent.size(); i++)
743 if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i]))
747 vMissingTx.push_back(txindex.vSpent[i]);
752 printf("ReacceptWalletTransactions found spent coin %sppc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
759 // Reaccept any txes of ours that aren't already in a block
760 if (!(wtx.IsCoinBase() || wtx.IsCoinStake()))
761 wtx.AcceptWalletTransaction(txdb, false);
764 if (!vMissingTx.empty())
766 // TODO: optimize this to scan just part of the block chain?
767 if (ScanForWalletTransactions(pindexGenesisBlock))
768 fRepeat = true; // Found missing transactions: re-do Reaccept.
773 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
775 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
777 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
779 uint256 hash = tx.GetHash();
780 if (!txdb.ContainsTx(hash))
781 RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx);
784 if (!(IsCoinBase() || IsCoinStake()))
786 uint256 hash = GetHash();
787 if (!txdb.ContainsTx(hash))
789 printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
790 RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this);
795 void CWalletTx::RelayWalletTransaction()
798 RelayWalletTransaction(txdb);
801 void CWallet::ResendWalletTransactions()
803 // Do this infrequently and randomly to avoid giving away
804 // that these are our transactions.
805 static int64 nNextTime;
806 if (GetTime() < nNextTime)
808 bool fFirst = (nNextTime == 0);
809 nNextTime = GetTime() + GetRand(30 * 60);
813 // Only do it if there's been a new block since last time
814 static int64 nLastTime;
815 if (nTimeBestReceived < nLastTime)
817 nLastTime = GetTime();
819 // Rebroadcast any of our txes that aren't in a block yet
820 printf("ResendWalletTransactions()\n");
824 // Sort them in chronological order
825 multimap<unsigned int, CWalletTx*> mapSorted;
826 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
828 CWalletTx& wtx = item.second;
829 // Don't rebroadcast until it's had plenty of time that
830 // it should have gotten in already by now.
831 if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
832 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
834 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
836 CWalletTx& wtx = *item.second;
837 wtx.RelayWalletTransaction(txdb);
847 //////////////////////////////////////////////////////////////////////////////
853 int64 CWallet::GetBalance() const
858 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
860 const CWalletTx* pcoin = &(*it).second;
861 if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
863 nTotal += pcoin->GetAvailableCredit();
870 int64 CWallet::GetUnconfirmedBalance() const
875 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
877 const CWalletTx* pcoin = &(*it).second;
878 if (pcoin->IsFinal() && pcoin->IsConfirmed())
880 nTotal += pcoin->GetAvailableCredit();
886 // ppcoin: total coins staked (non-spendable until maturity)
887 int64 CWallet::GetStake() const
891 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
893 const CWalletTx* pcoin = &(*it).second;
894 if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
895 nTotal += CWallet::GetCredit(*pcoin);
900 int64 CWallet::GetNewMint() const
904 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
906 const CWalletTx* pcoin = &(*it).second;
907 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
908 nTotal += CWallet::GetCredit(*pcoin);
914 bool CWallet::SelectCoinsMinConf(int64 nTargetValue, unsigned int nSpendTime, int nConfMine, int nConfTheirs, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
919 // List of values less than target
920 pair<int64, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
921 coinLowestLarger.first = std::numeric_limits<int64>::max();
922 coinLowestLarger.second.first = NULL;
923 vector<pair<int64, pair<const CWalletTx*,unsigned int> > > vValue;
924 int64 nTotalLower = 0;
928 vector<const CWalletTx*> vCoins;
929 vCoins.reserve(mapWallet.size());
930 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
931 vCoins.push_back(&(*it).second);
932 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
934 BOOST_FOREACH(const CWalletTx* pcoin, vCoins)
936 if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
939 if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0)
942 int nDepth = pcoin->GetDepthInMainChain();
943 if (nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs))
946 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
948 if (pcoin->IsSpent(i) || !IsMine(pcoin->vout[i]))
951 if (pcoin->nTime > nSpendTime)
952 continue; // ppcoin: timestamp must not exceed spend time
954 int64 n = pcoin->vout[i].nValue;
959 pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin,i));
961 if (n == nTargetValue)
963 setCoinsRet.insert(coin.second);
964 nValueRet += coin.first;
967 else if (n < nTargetValue + CENT)
969 vValue.push_back(coin);
972 else if (n < coinLowestLarger.first)
974 coinLowestLarger = coin;
980 if (nTotalLower == nTargetValue || nTotalLower == nTargetValue + CENT)
982 for (unsigned int i = 0; i < vValue.size(); ++i)
984 setCoinsRet.insert(vValue[i].second);
985 nValueRet += vValue[i].first;
990 if (nTotalLower < nTargetValue + (coinLowestLarger.second.first ? CENT : 0))
992 if (coinLowestLarger.second.first == NULL)
994 setCoinsRet.insert(coinLowestLarger.second);
995 nValueRet += coinLowestLarger.first;
999 if (nTotalLower >= nTargetValue + CENT)
1000 nTargetValue += CENT;
1002 // Solve subset sum by stochastic approximation
1003 sort(vValue.rbegin(), vValue.rend());
1004 vector<char> vfIncluded;
1005 vector<char> vfBest(vValue.size(), true);
1006 int64 nBest = nTotalLower;
1008 for (int nRep = 0; nRep < 1000 && nBest != nTargetValue; nRep++)
1010 vfIncluded.assign(vValue.size(), false);
1012 bool fReachedTarget = false;
1013 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
1015 for (unsigned int i = 0; i < vValue.size(); i++)
1017 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
1019 nTotal += vValue[i].first;
1020 vfIncluded[i] = true;
1021 if (nTotal >= nTargetValue)
1023 fReachedTarget = true;
1027 vfBest = vfIncluded;
1029 nTotal -= vValue[i].first;
1030 vfIncluded[i] = false;
1037 // If the next larger is still closer, return it
1038 if (coinLowestLarger.second.first && coinLowestLarger.first - nTargetValue <= nBest - nTargetValue)
1040 setCoinsRet.insert(coinLowestLarger.second);
1041 nValueRet += coinLowestLarger.first;
1044 for (unsigned int i = 0; i < vValue.size(); i++)
1047 setCoinsRet.insert(vValue[i].second);
1048 nValueRet += vValue[i].first;
1052 if (fDebug && GetBoolArg("-printselectcoin"))
1054 printf("SelectCoins() best subset: ");
1055 for (unsigned int i = 0; i < vValue.size(); i++)
1057 printf("%s ", FormatMoney(vValue[i].first).c_str());
1058 printf("total %s\n", FormatMoney(nBest).c_str());
1065 bool CWallet::SelectCoins(int64 nTargetValue, unsigned int nSpendTime, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
1067 return (SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 6, setCoinsRet, nValueRet) ||
1068 SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 1, setCoinsRet, nValueRet) ||
1069 SelectCoinsMinConf(nTargetValue, nSpendTime, 0, 1, setCoinsRet, nValueRet));
1075 bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
1078 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1084 if (vecSend.empty() || nValue < 0)
1087 wtxNew.BindWallet(this);
1090 LOCK2(cs_main, cs_wallet);
1091 // txdb must be opened before the mapWallet lock
1094 nFeeRet = nTransactionFee;
1098 wtxNew.vout.clear();
1099 wtxNew.fFromMe = true;
1101 int64 nTotalValue = nValue + nFeeRet;
1102 double dPriority = 0;
1103 // vouts to the payees
1104 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1105 wtxNew.vout.push_back(CTxOut(s.second, s.first));
1107 // Choose coins to use
1108 set<pair<const CWalletTx*,unsigned int> > setCoins;
1110 if (!SelectCoins(nTotalValue, wtxNew.nTime, setCoins, nValueIn))
1112 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1114 int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
1115 dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
1118 int64 nChange = nValueIn - nValue - nFeeRet;
1119 // if sub-cent change is required, the fee must be raised to at least MIN_TX_FEE
1120 // or until nChange becomes zero
1121 // NOTE: this depends on the exact behaviour of GetMinFee
1122 if (nFeeRet < MIN_TX_FEE && nChange > 0 && nChange < CENT)
1124 int64 nMoveToFee = min(nChange, MIN_TX_FEE - nFeeRet);
1125 nChange -= nMoveToFee;
1126 nFeeRet += nMoveToFee;
1129 // ppcoin: sub-cent change is moved to fee
1130 if (nChange > 0 && nChange < MIN_TXOUT_AMOUNT)
1138 // Note: We use a new key here to keep it from being obvious which side is the change.
1139 // The drawback is that by not reusing a previous key, the change may be lost if a
1140 // backup is restored, if the backup doesn't have the new private key for the change.
1141 // If we reused the old key, it would be possible to add code to look for and
1142 // rediscover unknown transactions that were written with keys of ours to recover
1143 // post-backup change.
1145 // Reserve a new key pair from key pool
1146 vector<unsigned char> vchPubKey = reservekey.GetReservedKey();
1147 // assert(mapKeys.count(vchPubKey));
1149 // Fill a vout to ourself
1150 // TODO: pass in scriptChange instead of reservekey so
1151 // change transaction isn't always pay-to-bitcoin-address
1152 CScript scriptChange;
1153 scriptChange.SetBitcoinAddress(vchPubKey);
1155 // Insert change txn at random position:
1156 vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
1157 wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
1160 reservekey.ReturnKey();
1163 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1164 wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
1168 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1169 if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
1173 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
1174 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1176 dPriority /= nBytes;
1178 // Check that enough fee is included
1179 int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
1180 int64 nMinFee = wtxNew.GetMinFee(1, false, GMF_SEND);
1181 if (nFeeRet < max(nPayFee, nMinFee))
1183 nFeeRet = max(nPayFee, nMinFee);
1187 // Fill vtxPrev by copying from previous transactions vtxPrev
1188 wtxNew.AddSupportingTransactions(txdb);
1189 wtxNew.fTimeReceivedIsTxTime = true;
1198 bool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
1200 vector< pair<CScript, int64> > vecSend;
1201 vecSend.push_back(make_pair(scriptPubKey, nValue));
1202 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet);
1205 // ppcoin: create coin stake transaction
1206 bool CWallet::CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, CTransaction& txNew)
1208 // The following split & combine thresholds are important to security
1209 // Should not be adjusted if you don't understand the consequences
1210 static unsigned int nStakeSplitAge = (60 * 60 * 24 * 90);
1211 int64 nCombineThreshold = GetProofOfWorkReward(GetLastBlockIndex(pindexBest, false)->nBits) / 3;
1213 CBigNum bnTargetPerCoinDay;
1214 bnTargetPerCoinDay.SetCompact(nBits);
1216 LOCK2(cs_main, cs_wallet);
1219 // Mark coin stake transaction
1220 CScript scriptEmpty;
1221 scriptEmpty.clear();
1222 txNew.vout.push_back(CTxOut(0, scriptEmpty));
1223 // Choose coins to use
1224 int64 nBalance = GetBalance();
1225 int64 nReserveBalance = 0;
1226 if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
1227 return error("CreateCoinStake : invalid reserve balance amount");
1228 if (nBalance <= nReserveBalance)
1230 set<pair<const CWalletTx*,unsigned int> > setCoins;
1231 vector<const CWalletTx*> vwtxPrev;
1233 if (!SelectCoins(nBalance - nReserveBalance, txNew.nTime, setCoins, nValueIn))
1235 if (setCoins.empty())
1238 CScript scriptPubKeyKernel;
1239 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1243 if (!txdb.ReadTxIndex(pcoin.first->GetHash(), txindex))
1246 // Read block header
1248 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
1250 if (block.GetBlockTime() + nStakeMinAge > txNew.nTime)
1251 continue; // only count coins meeting min age requirement
1253 int64 nValueIn = pcoin.first->vout[pcoin.second].nValue;
1254 CBigNum bnCoinDay = CBigNum(nValueIn) * min(txNew.nTime-pcoin.first->nTime, (unsigned int)STAKE_MAX_AGE) / COIN / (24 * 60 * 60);
1256 CDataStream ss(SER_GETHASH, 0);
1257 ss << nBits << block.nTime << (txindex.pos.nTxPos - txindex.pos.nBlockPos) << pcoin.first->nTime << pcoin.second << txNew.nTime;
1258 if (CBigNum(Hash(ss.begin(), ss.end())) <= bnCoinDay * bnTargetPerCoinDay)
1261 if (fDebug && GetBoolArg("-printcoinstake"))
1262 printf("CreateCoinStake : kernel found\n");
1263 vector<valtype> vSolutions;
1264 txnouttype whichType;
1265 CScript scriptPubKeyOut;
1266 scriptPubKeyKernel = pcoin.first->vout[pcoin.second].scriptPubKey;
1267 if (!Solver(scriptPubKeyKernel, whichType, vSolutions))
1269 if (fDebug && GetBoolArg("-printcoinstake"))
1270 printf("CreateCoinStake : failed to parse kernel\n", whichType);
1273 if (fDebug && GetBoolArg("-printcoinstake"))
1274 printf("CreateCoinStake : parsed kernel type=%d\n", whichType);
1275 if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH)
1277 if (fDebug && GetBoolArg("-printcoinstake"))
1278 printf("CreateCoinStake : no support for kernel type=%d\n", whichType);
1279 continue; // only support pay to public key and pay to address
1281 if (whichType == TX_PUBKEYHASH) // pay to address type
1283 // convert to pay to public key type
1285 if (!keystore.GetKey(uint160(vSolutions[0]), key))
1287 if (fDebug && GetBoolArg("-printcoinstake"))
1288 printf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1289 continue; // unable to find corresponding public key
1291 scriptPubKeyOut << key.GetPubKey() << OP_CHECKSIG;
1294 scriptPubKeyOut = scriptPubKeyKernel;
1296 txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1297 nCredit += pcoin.first->vout[pcoin.second].nValue;
1298 vwtxPrev.push_back(pcoin.first);
1299 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
1300 if (block.GetBlockTime() + nStakeSplitAge > txNew.nTime)
1301 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut)); //split stake
1302 if (fDebug && GetBoolArg("-printcoinstake"))
1303 printf("CreateCoinStake : added kernel type=%d\n", whichType);
1307 if (nCredit == 0 || nCredit > nBalance - nReserveBalance)
1309 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1311 // Attempt to add more inputs
1312 // Only add coins of the same key/address as kernel
1313 if (txNew.vout.size() == 2 && ((pcoin.first->vout[pcoin.second].scriptPubKey == scriptPubKeyKernel || pcoin.first->vout[pcoin.second].scriptPubKey == txNew.vout[1].scriptPubKey))
1314 && pcoin.first->GetHash() != txNew.vin[0].prevout.hash)
1316 // Stop adding more inputs if value is already pretty significant
1317 if (nCredit > nCombineThreshold)
1319 // Stop adding inputs if reached reserve limit
1320 if (nCredit + pcoin.first->vout[pcoin.second].nValue > nBalance - nReserveBalance)
1322 // Do not add additional significant input
1323 if (pcoin.first->vout[pcoin.second].nValue > nCombineThreshold)
1325 txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1326 nCredit += pcoin.first->vout[pcoin.second].nValue;
1327 vwtxPrev.push_back(pcoin.first);
1330 // Calculate coin age reward
1334 if (!txNew.GetCoinAge(txdb, nCoinAge))
1335 return error("CreateCoinStake : failed to calculate coin age");
1336 nCredit += GetProofOfStakeReward(nCoinAge);
1342 // Set output amount
1343 if (txNew.vout.size() == 3)
1345 txNew.vout[1].nValue = ((nCredit - nMinFee) / 2 / CENT) * CENT;
1346 txNew.vout[2].nValue = nCredit - nMinFee - txNew.vout[1].nValue;
1349 txNew.vout[1].nValue = nCredit - nMinFee;
1353 BOOST_FOREACH(const CWalletTx* pcoin, vwtxPrev)
1355 if (!SignSignature(*this, *pcoin, txNew, nIn++))
1356 return error("CreateCoinStake : failed to sign coinstake");
1360 unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION);
1361 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1364 // Check enough fee is paid
1365 if (nMinFee < txNew.GetMinFee() - MIN_TX_FEE)
1367 nMinFee = txNew.GetMinFee() - MIN_TX_FEE;
1368 continue; // try signing again
1372 if (fDebug && GetBoolArg("-printfee"))
1373 printf("CreateCoinStake : fee for coinstake %s\n", FormatMoney(nMinFee).c_str());
1378 // Successfully generated coinstake
1382 // Call after CreateTransaction unless you want to abort
1383 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
1386 LOCK2(cs_main, cs_wallet);
1387 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
1389 // This is only to keep the database open to defeat the auto-flush for the
1390 // duration of this scope. This is the only place where this optimization
1391 // maybe makes sense; please don't do it anywhere else.
1392 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
1394 // Take key pair from key pool so it won't be used again
1395 reservekey.KeepKey();
1397 // Add tx to wallet, because if it has change it's also ours,
1398 // otherwise just for transaction history.
1399 AddToWallet(wtxNew);
1401 // Mark old coins as spent
1402 set<CWalletTx*> setCoins;
1403 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
1405 CWalletTx &coin = mapWallet[txin.prevout.hash];
1406 coin.BindWallet(this);
1407 coin.MarkSpent(txin.prevout.n);
1409 vWalletUpdated.push_back(coin.GetHash());
1416 // Track how many getdata requests our transaction gets
1417 mapRequestCount[wtxNew.GetHash()] = 0;
1420 if (!wtxNew.AcceptToMemoryPool())
1422 // This must not fail. The transaction has already been signed and recorded.
1423 printf("CommitTransaction() : Error: Transaction not valid");
1426 wtxNew.RelayWalletTransaction();
1435 string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1437 CReserveKey reservekey(this);
1442 string strError = _("Error: Wallet locked, unable to create transaction ");
1443 printf("SendMoney() : %s", strError.c_str());
1446 if (fWalletUnlockMintOnly)
1448 string strError = _("Error: Wallet unlocked for block minting only, unable to create transaction.");
1449 printf("SendMoney() : %s", strError.c_str());
1452 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
1455 if (nValue + nFeeRequired > GetBalance())
1456 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());
1458 strError = _("Error: Transaction creation failed ");
1459 printf("SendMoney() : %s", strError.c_str());
1463 if (fAskFee && !ThreadSafeAskFee(nFeeRequired, _("Sending...")))
1466 if (!CommitTransaction(wtxNew, reservekey))
1467 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.");
1475 string CWallet::SendMoneyToBitcoinAddress(const CBitcoinAddress& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1479 return _("Invalid amount");
1480 if (nValue + nTransactionFee > GetBalance())
1481 return _("Insufficient funds");
1483 // Parse bitcoin address
1484 CScript scriptPubKey;
1485 scriptPubKey.SetBitcoinAddress(address);
1487 return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
1493 int CWallet::LoadWallet(bool& fFirstRunRet)
1497 fFirstRunRet = false;
1498 int nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
1499 if (nLoadWalletRet == DB_NEED_REWRITE)
1501 if (CDB::Rewrite(strWalletFile, "\x04pool"))
1504 // Note: can't top-up keypool here, because wallet is locked.
1505 // User will be prompted to unlock wallet the next operation
1506 // the requires a new key.
1508 nLoadWalletRet = DB_NEED_REWRITE;
1511 if (nLoadWalletRet != DB_LOAD_OK)
1512 return nLoadWalletRet;
1513 fFirstRunRet = vchDefaultKey.empty();
1515 CreateThread(ThreadFlushWalletDB, &strWalletFile);
1520 bool CWallet::SetAddressBookName(const CBitcoinAddress& address, const string& strName)
1522 mapAddressBook[address] = strName;
1523 AddressBookRepaint();
1526 return CWalletDB(strWalletFile).WriteName(address.ToString(), strName);
1529 bool CWallet::DelAddressBookName(const CBitcoinAddress& address)
1531 mapAddressBook.erase(address);
1532 AddressBookRepaint();
1535 return CWalletDB(strWalletFile).EraseName(address.ToString());
1539 void CWallet::PrintWallet(const CBlock& block)
1543 if (block.IsProofOfWork() && mapWallet.count(block.vtx[0].GetHash()))
1545 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
1546 printf(" mine: %d %d %s", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), FormatMoney(wtx.GetCredit()).c_str());
1548 if (block.IsProofOfStake() && mapWallet.count(block.vtx[1].GetHash()))
1550 CWalletTx& wtx = mapWallet[block.vtx[1].GetHash()];
1551 printf(" stake: %d %d %s", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), FormatMoney(wtx.GetCredit()).c_str());
1557 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
1561 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
1562 if (mi != mapWallet.end())
1571 bool CWallet::SetDefaultKey(const std::vector<unsigned char> &vchPubKey)
1575 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
1578 vchDefaultKey = vchPubKey;
1582 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
1584 if (!pwallet->fFileBacked)
1586 strWalletFileOut = pwallet->strWalletFile;
1591 // Mark old keypool keys as used,
1592 // and generate all new keys
1594 bool CWallet::NewKeyPool()
1598 CWalletDB walletdb(strWalletFile);
1599 BOOST_FOREACH(int64 nIndex, setKeyPool)
1600 walletdb.ErasePool(nIndex);
1606 int64 nKeys = max(GetArg("-keypool", 100), (int64)0);
1607 for (int i = 0; i < nKeys; i++)
1610 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
1611 setKeyPool.insert(nIndex);
1613 printf("CWallet::NewKeyPool wrote %"PRI64d" new keys\n", nKeys);
1618 bool CWallet::TopUpKeyPool()
1626 CWalletDB walletdb(strWalletFile);
1629 unsigned int nTargetSize = max(GetArg("-keypool", 100), 0LL);
1630 while (setKeyPool.size() < (nTargetSize + 1))
1633 if (!setKeyPool.empty())
1634 nEnd = *(--setKeyPool.end()) + 1;
1635 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
1636 throw runtime_error("TopUpKeyPool() : writing generated key failed");
1637 setKeyPool.insert(nEnd);
1638 printf("keypool added key %"PRI64d", size=%d\n", nEnd, setKeyPool.size());
1644 void CWallet::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool)
1647 keypool.vchPubKey.clear();
1654 // Get the oldest key
1655 if(setKeyPool.empty())
1658 CWalletDB walletdb(strWalletFile);
1660 nIndex = *(setKeyPool.begin());
1661 setKeyPool.erase(setKeyPool.begin());
1662 if (!walletdb.ReadPool(nIndex, keypool))
1663 throw runtime_error("ReserveKeyFromKeyPool() : read failed");
1664 if (!HaveKey(Hash160(keypool.vchPubKey)))
1665 throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
1666 assert(!keypool.vchPubKey.empty());
1667 if (fDebug && GetBoolArg("-printkeypool"))
1668 printf("keypool reserve %"PRI64d"\n", nIndex);
1672 int64 CWallet::AddReserveKey(const CKeyPool& keypool)
1675 LOCK2(cs_main, cs_wallet);
1676 CWalletDB walletdb(strWalletFile);
1678 int64 nIndex = 1 + *(--setKeyPool.end());
1679 if (!walletdb.WritePool(nIndex, keypool))
1680 throw runtime_error("AddReserveKey() : writing added key failed");
1681 setKeyPool.insert(nIndex);
1687 void CWallet::KeepKey(int64 nIndex)
1689 // Remove from key pool
1692 CWalletDB walletdb(strWalletFile);
1693 walletdb.ErasePool(nIndex);
1695 printf("keypool keep %"PRI64d"\n", nIndex);
1698 void CWallet::ReturnKey(int64 nIndex)
1700 // Return to key pool
1703 setKeyPool.insert(nIndex);
1705 if (fDebug && GetBoolArg("-printkeypool"))
1706 printf("keypool return %"PRI64d"\n", nIndex);
1709 bool CWallet::GetKeyFromPool(vector<unsigned char>& result, bool fAllowReuse)
1715 ReserveKeyFromKeyPool(nIndex, keypool);
1718 if (fAllowReuse && !vchDefaultKey.empty())
1720 result = vchDefaultKey;
1723 if (IsLocked()) return false;
1724 result = GenerateNewKey();
1728 result = keypool.vchPubKey;
1733 int64 CWallet::GetOldestKeyPoolTime()
1737 ReserveKeyFromKeyPool(nIndex, keypool);
1741 return keypool.nTime;
1744 // ppcoin: check 'spent' consistency between wallet and txindex
1745 bool CWallet::CheckSpentCoins(int& nMismatchFound, int64& nBalanceInQuestion)
1748 nBalanceInQuestion = 0;
1751 vector<const CWalletTx*> vCoins;
1752 vCoins.reserve(mapWallet.size());
1753 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1754 vCoins.push_back(&(*it).second);
1757 BOOST_FOREACH(const CWalletTx* pcoin, vCoins)
1759 // Find the corresponding transaction index
1761 if (!txdb.ReadTxIndex(pcoin->GetHash(), txindex))
1763 for (int n=0; n < pcoin->vout.size(); n++)
1765 if (pcoin->IsSpent(n) && (txindex.vSpent.size() <= n || txindex.vSpent[n].IsNull()))
1767 printf("CheckSpentCoins found lost coin %sppc %s[%d]\n", FormatMoney(pcoin->GetCredit()).c_str(), pcoin->GetHash().ToString().c_str(), n);
1769 nBalanceInQuestion += pcoin->vout[n].nValue;
1771 else if (!pcoin->IsSpent(n) && (txindex.vSpent.size() > n && !txindex.vSpent[n].IsNull()))
1773 printf("CheckSpentCoins found spent coin %sppc %s[%d]\n", FormatMoney(pcoin->GetCredit()).c_str(), pcoin->GetHash().ToString().c_str(), n);
1775 nBalanceInQuestion += pcoin->vout[n].nValue;
1779 return (nMismatchFound == 0);
1782 // ppcoin: fix wallet spent state according to txindex
1783 void CWallet::FixSpentCoins(int& nMismatchFound, int64& nBalanceInQuestion)
1786 nBalanceInQuestion = 0;
1789 vector<CWalletTx*> vCoins;
1790 vCoins.reserve(mapWallet.size());
1791 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1792 vCoins.push_back(&(*it).second);
1795 BOOST_FOREACH(CWalletTx* pcoin, vCoins)
1797 // Find the corresponding transaction index
1799 if (!txdb.ReadTxIndex(pcoin->GetHash(), txindex))
1801 for (int n=0; n < pcoin->vout.size(); n++)
1803 if (pcoin->IsSpent(n) && (txindex.vSpent.size() <= n || txindex.vSpent[n].IsNull()))
1805 printf("FixSpentCoins found lost coin %sppc %s[%d]\n", FormatMoney(pcoin->GetCredit()).c_str(), pcoin->GetHash().ToString().c_str(), n);
1807 nBalanceInQuestion += pcoin->vout[n].nValue;
1808 pcoin->MarkUnspent(n);
1809 pcoin->WriteToDisk();
1811 else if (!pcoin->IsSpent(n) && (txindex.vSpent.size() > n && !txindex.vSpent[n].IsNull()))
1813 printf("FixSpentCoins found spent coin %sppc %s[%d]\n", FormatMoney(pcoin->GetCredit()).c_str(), pcoin->GetHash().ToString().c_str(), n);
1815 nBalanceInQuestion += pcoin->vout[n].nValue;
1816 pcoin->MarkSpent(n);
1817 pcoin->WriteToDisk();
1823 // ppcoin: disable transaction (only for coinstake)
1824 void CWallet::DisableTransaction(const CTransaction &tx)
1826 if (!tx.IsCoinStake() || !IsFromMe(tx))
1827 return; // only disconnecting coinstake requires marking input unspent
1830 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1832 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
1833 if (mi != mapWallet.end())
1835 CWalletTx& prev = (*mi).second;
1836 if (txin.prevout.n < prev.vout.size() && IsMine(prev.vout[txin.prevout.n]))
1838 prev.MarkUnspent(txin.prevout.n);
1845 vector<unsigned char> CReserveKey::GetReservedKey()
1850 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
1852 vchPubKey = keypool.vchPubKey;
1855 printf("CReserveKey::GetReservedKey(): Warning: using default key instead of a new key, top up your keypool.");
1856 vchPubKey = pwallet->vchDefaultKey;
1859 assert(!vchPubKey.empty());
1863 void CReserveKey::KeepKey()
1866 pwallet->KeepKey(nIndex);
1871 void CReserveKey::ReturnKey()
1874 pwallet->ReturnKey(nIndex);
1879 void CWallet::GetAllReserveAddresses(set<CBitcoinAddress>& setAddress)
1883 CWalletDB walletdb(strWalletFile);
1885 LOCK2(cs_main, cs_wallet);
1886 BOOST_FOREACH(const int64& id, setKeyPool)
1889 if (!walletdb.ReadPool(id, keypool))
1890 throw runtime_error("GetAllReserveKeyHashes() : read failed");
1891 CBitcoinAddress address(keypool.vchPubKey);
1892 assert(!keypool.vchPubKey.empty());
1893 if (!HaveKey(address))
1894 throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
1895 setAddress.insert(address);