1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Copyright (c) 2011-2013 The PPCoin developers
4 // Copyright (c) 2013 NovaCoin Developers
5 // Distributed under the MIT/X11 software license, see the accompanying
6 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
11 #include "ui_interface.h"
17 //////////////////////////////////////////////////////////////////////////////
22 std::vector<unsigned char> CWallet::GenerateNewKey(bool bCompressed = true)
24 bool fCompressed = bCompressed ? CanSupportFeature(FEATURE_COMPRPUBKEY) : false; // default to compressed public keys if we want 0.6.0 wallets
28 key.MakeNewKey(fCompressed);
30 // Compressed public keys were introduced in version 0.6.0
32 SetMinVersion(FEATURE_COMPRPUBKEY);
35 throw std::runtime_error("CWallet::GenerateNewKey() : AddKey failed");
36 return key.GetPubKey();
39 bool CWallet::AddKey(const CKey& key)
41 if (!CCryptoKeyStore::AddKey(key))
46 return CWalletDB(strWalletFile).WriteKey(key.GetPubKey(), key.GetPrivKey());
50 bool CWallet::AddCryptedKey(const vector<unsigned char> &vchPubKey, const vector<unsigned char> &vchCryptedSecret)
52 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
58 if (pwalletdbEncryption)
59 return pwalletdbEncryption->WriteCryptedKey(vchPubKey, vchCryptedSecret);
61 return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret);
66 bool CWallet::AddCScript(const CScript& redeemScript)
68 if (!CCryptoKeyStore::AddCScript(redeemScript))
72 return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript);
75 // ppcoin: optional setting to unlock wallet for block minting only;
76 // serves to disable the trivial sendmoney when OS account compromised
77 bool fWalletUnlockMintOnly = false;
79 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
85 CKeyingMaterial vMasterKey;
89 BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
91 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
93 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
95 if (CCryptoKeyStore::Unlock(vMasterKey))
102 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
104 bool fWasLocked = IsLocked();
111 CKeyingMaterial vMasterKey;
112 BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
114 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
116 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
118 if (CCryptoKeyStore::Unlock(vMasterKey))
120 int64 nStartTime = GetTimeMillis();
121 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
122 pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
124 nStartTime = GetTimeMillis();
125 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
126 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
128 if (pMasterKey.second.nDeriveIterations < 25000)
129 pMasterKey.second.nDeriveIterations = 25000;
131 printf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
133 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
135 if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
137 CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
148 void CWallet::SetBestChain(const CBlockLocator& loc)
150 CWalletDB walletdb(strWalletFile);
151 walletdb.WriteBestBlock(loc);
154 // This class implements an addrIncoming entry that causes pre-0.4
155 // clients to crash on startup if reading a private-key-encrypted wallet.
156 class CCorruptAddress
161 if (nType & SER_DISK)
166 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
168 if (nWalletVersion >= nVersion)
171 // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
172 if (fExplicit && nVersion > nWalletMaxVersion)
173 nVersion = FEATURE_LATEST;
175 nWalletVersion = nVersion;
177 if (nVersion > nWalletMaxVersion)
178 nWalletMaxVersion = nVersion;
182 CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile);
183 if (nWalletVersion >= 40000)
185 // Versions prior to 0.4.0 did not support the "minversion" record.
186 // Use a CCorruptAddress to make them crash instead.
187 CCorruptAddress corruptAddress;
188 pwalletdb->WriteSetting("addrIncoming", corruptAddress);
190 if (nWalletVersion > 40000)
191 pwalletdb->WriteMinVersion(nWalletVersion);
199 bool CWallet::SetMaxVersion(int nVersion)
201 // cannot downgrade below current version
202 if (nWalletVersion > nVersion)
205 nWalletMaxVersion = nVersion;
210 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
215 CKeyingMaterial vMasterKey;
216 RandAddSeedPerfmon();
218 vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
219 RAND_bytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
221 CMasterKey kMasterKey;
223 RandAddSeedPerfmon();
224 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
225 RAND_bytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
228 int64 nStartTime = GetTimeMillis();
229 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
230 kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
232 nStartTime = GetTimeMillis();
233 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
234 kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
236 if (kMasterKey.nDeriveIterations < 25000)
237 kMasterKey.nDeriveIterations = 25000;
239 printf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
241 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
243 if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
248 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
251 pwalletdbEncryption = new CWalletDB(strWalletFile);
252 if (!pwalletdbEncryption->TxnBegin())
254 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
257 if (!EncryptKeys(vMasterKey))
260 pwalletdbEncryption->TxnAbort();
261 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.
264 // Encryption was introduced in version 0.4.0
265 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
269 if (!pwalletdbEncryption->TxnCommit())
270 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.
272 delete pwalletdbEncryption;
273 pwalletdbEncryption = NULL;
277 Unlock(strWalletPassphrase);
281 // Need to completely rewrite the wallet file; if we don't, bdb might keep
282 // bits of the unencrypted private key in slack space in the database file.
283 CDB::Rewrite(strWalletFile);
289 void CWallet::WalletUpdateSpent(const CTransaction &tx)
291 // Anytime a signature is successfully verified, it's proof the outpoint is spent.
292 // Update the wallet spent flag if it doesn't know due to wallet.dat being
293 // restored from backup or the user making copies of wallet.dat.
296 BOOST_FOREACH(const CTxIn& txin, tx.vin)
298 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
299 if (mi != mapWallet.end())
301 CWalletTx& wtx = (*mi).second;
302 if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n]))
304 printf("WalletUpdateSpent found spent coin %sppc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
305 wtx.MarkSpent(txin.prevout.n);
307 vWalletUpdated.push_back(txin.prevout.hash);
314 void CWallet::MarkDirty()
318 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
319 item.second.MarkDirty();
323 bool CWallet::AddToWallet(const CWalletTx& wtxIn)
325 uint256 hash = wtxIn.GetHash();
328 // Inserts only if not already there, returns tx inserted or tx found
329 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
330 CWalletTx& wtx = (*ret.first).second;
331 wtx.BindWallet(this);
332 bool fInsertedNew = ret.second;
334 wtx.nTimeReceived = GetAdjustedTime();
336 bool fUpdated = false;
340 if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
342 wtx.hashBlock = wtxIn.hashBlock;
345 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
347 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
348 wtx.nIndex = wtxIn.nIndex;
351 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
353 wtx.fFromMe = wtxIn.fFromMe;
356 fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);
360 printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
363 if (fInsertedNew || fUpdated)
364 if (!wtx.WriteToDisk())
367 // If default receiving address gets used, replace it with a new one
368 CScript scriptDefaultKey;
369 scriptDefaultKey.SetBitcoinAddress(vchDefaultKey);
370 BOOST_FOREACH(const CTxOut& txout, wtx.vout)
372 if (txout.scriptPubKey == scriptDefaultKey)
374 std::vector<unsigned char> newDefaultKey;
375 if (GetKeyFromPool(newDefaultKey, false))
377 SetDefaultKey(newDefaultKey);
378 SetAddressBookName(CBitcoinAddress(vchDefaultKey), "");
384 vWalletUpdated.push_back(hash);
386 // since AddToWallet is called directly for self-originating transactions, check for consumption of own coins
387 WalletUpdateSpent(wtx);
395 // Add a transaction to the wallet, or update it.
396 // pblock is optional, but should be provided if the transaction is known to be in a block.
397 // If fUpdate is true, existing transactions will be updated.
398 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fFindBlock)
400 uint256 hash = tx.GetHash();
403 bool fExisted = mapWallet.count(hash);
404 if (fExisted && !fUpdate) return false;
405 if (fExisted || IsMine(tx) || IsFromMe(tx))
407 CWalletTx wtx(this,tx);
408 // Get merkle branch if transaction was found in a block
410 wtx.SetMerkleBranch(pblock);
411 return AddToWallet(wtx);
414 WalletUpdateSpent(tx);
419 bool CWallet::EraseFromWallet(uint256 hash)
425 if (mapWallet.erase(hash))
426 CWalletDB(strWalletFile).EraseTx(hash);
432 bool CWallet::IsMine(const CTxIn &txin) const
436 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
437 if (mi != mapWallet.end())
439 const CWalletTx& prev = (*mi).second;
440 if (txin.prevout.n < prev.vout.size())
441 if (IsMine(prev.vout[txin.prevout.n]))
448 int64 CWallet::GetDebit(const CTxIn &txin) const
452 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
453 if (mi != mapWallet.end())
455 const CWalletTx& prev = (*mi).second;
456 if (txin.prevout.n < prev.vout.size())
457 if (IsMine(prev.vout[txin.prevout.n]))
458 return prev.vout[txin.prevout.n].nValue;
464 bool CWallet::IsChange(const CTxOut& txout) const
466 CBitcoinAddress address;
468 // TODO: fix handling of 'change' outputs. The assumption is that any
469 // payment to a TX_PUBKEYHASH that is mine but isn't in the address book
470 // is change. That assumption is likely to break when we implement multisignature
471 // wallets that return change back into a multi-signature-protected address;
472 // a better way of identifying which outputs are 'the send' and which are
473 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
474 // which output, if any, was change).
475 if (ExtractAddress(txout.scriptPubKey, address) && HaveKey(address))
478 if (!mapAddressBook.count(address))
484 int64 CWalletTx::GetTxTime() const
486 return nTimeReceived;
489 int CWalletTx::GetRequestCount() const
491 // Returns -1 if it wasn't being tracked
494 LOCK(pwallet->cs_wallet);
495 if (IsCoinBase() || IsCoinStake())
500 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
501 if (mi != pwallet->mapRequestCount.end())
502 nRequests = (*mi).second;
507 // Did anyone request this transaction?
508 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
509 if (mi != pwallet->mapRequestCount.end())
511 nRequests = (*mi).second;
513 // How about the block it's in?
514 if (nRequests == 0 && hashBlock != 0)
516 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
517 if (mi != pwallet->mapRequestCount.end())
518 nRequests = (*mi).second;
520 nRequests = 1; // If it's in someone else's block it must have got out
528 void CWalletTx::GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, list<pair<CBitcoinAddress, int64> >& listReceived,
529 list<pair<CBitcoinAddress, int64> >& listSent, int64& nFee, string& strSentAccount) const
531 nGeneratedImmature = nGeneratedMature = nFee = 0;
532 listReceived.clear();
534 strSentAccount = strFromAccount;
536 if (IsCoinBase() || IsCoinStake())
538 if (GetBlocksToMaturity() > 0)
539 nGeneratedImmature = pwallet->GetCredit(*this);
541 nGeneratedMature = GetCredit();
546 int64 nDebit = GetDebit();
547 if (nDebit > 0) // debit>0 means we signed/sent this transaction
549 int64 nValueOut = GetValueOut();
550 nFee = nDebit - nValueOut;
554 BOOST_FOREACH(const CTxOut& txout, vout)
556 CBitcoinAddress address;
557 vector<unsigned char> vchPubKey;
558 if (!ExtractAddress(txout.scriptPubKey, address))
560 printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
561 this->GetHash().ToString().c_str());
562 address = " unknown ";
565 // Don't report 'change' txouts
566 if (nDebit > 0 && pwallet->IsChange(txout))
570 listSent.push_back(make_pair(address, txout.nValue));
572 if (pwallet->IsMine(txout))
573 listReceived.push_back(make_pair(address, txout.nValue));
578 void CWalletTx::GetAccountAmounts(const string& strAccount, int64& nGenerated, int64& nReceived,
579 int64& nSent, int64& nFee) const
581 nGenerated = nReceived = nSent = nFee = 0;
583 int64 allGeneratedImmature, allGeneratedMature, allFee;
584 allGeneratedImmature = allGeneratedMature = allFee = 0;
585 string strSentAccount;
586 list<pair<CBitcoinAddress, int64> > listReceived;
587 list<pair<CBitcoinAddress, int64> > listSent;
588 GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount);
590 if (strAccount == "")
591 nGenerated = allGeneratedMature;
592 if (strAccount == strSentAccount)
594 BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress,int64)& s, listSent)
599 LOCK(pwallet->cs_wallet);
600 BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress,int64)& r, listReceived)
602 if (pwallet->mapAddressBook.count(r.first))
604 map<CBitcoinAddress, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);
605 if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)
606 nReceived += r.second;
608 else if (strAccount.empty())
610 nReceived += r.second;
616 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
620 const int COPY_DEPTH = 3;
621 if (SetMerkleBranch() < COPY_DEPTH)
623 vector<uint256> vWorkQueue;
624 BOOST_FOREACH(const CTxIn& txin, vin)
625 vWorkQueue.push_back(txin.prevout.hash);
627 // This critsect is OK because txdb is already open
629 LOCK(pwallet->cs_wallet);
630 map<uint256, const CMerkleTx*> mapWalletPrev;
631 set<uint256> setAlreadyDone;
632 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
634 uint256 hash = vWorkQueue[i];
635 if (setAlreadyDone.count(hash))
637 setAlreadyDone.insert(hash);
640 map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
641 if (mi != pwallet->mapWallet.end())
644 BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev)
645 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
647 else if (mapWalletPrev.count(hash))
649 tx = *mapWalletPrev[hash];
651 else if (!fClient && txdb.ReadDiskTx(hash, tx))
657 printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
661 int nDepth = tx.SetMerkleBranch();
662 vtxPrev.push_back(tx);
664 if (nDepth < COPY_DEPTH)
666 BOOST_FOREACH(const CTxIn& txin, tx.vin)
667 vWorkQueue.push_back(txin.prevout.hash);
673 reverse(vtxPrev.begin(), vtxPrev.end());
676 bool CWalletTx::WriteToDisk()
678 return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
681 // Scan the block chain (starting in pindexStart) for transactions
682 // from or to us. If fUpdate is true, found transactions that already
683 // exist in the wallet will be updated.
684 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
688 CBlockIndex* pindex = pindexStart;
694 block.ReadFromDisk(pindex, true);
695 BOOST_FOREACH(CTransaction& tx, block.vtx)
697 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
700 pindex = pindex->pnext;
706 int CWallet::ScanForWalletTransaction(const uint256& hashTx)
709 tx.ReadFromDisk(COutPoint(hashTx, 0));
710 if (AddToWalletIfInvolvingMe(tx, NULL, true, true))
715 void CWallet::ReacceptWalletTransactions()
723 vector<CDiskTxPos> vMissingTx;
724 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
726 CWalletTx& wtx = item.second;
727 if ((wtx.IsCoinBase() && wtx.IsSpent(0)) || (wtx.IsCoinStake() && wtx.IsSpent(1)))
731 bool fUpdated = false;
732 if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
734 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
735 if (txindex.vSpent.size() != wtx.vout.size())
737 printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %d != wtx.vout.size() %d\n", txindex.vSpent.size(), wtx.vout.size());
740 for (unsigned int i = 0; i < txindex.vSpent.size(); i++)
744 if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i]))
748 vMissingTx.push_back(txindex.vSpent[i]);
753 printf("ReacceptWalletTransactions found spent coin %sppc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
760 // Reaccept any txes of ours that aren't already in a block
761 if (!(wtx.IsCoinBase() || wtx.IsCoinStake()))
762 wtx.AcceptWalletTransaction(txdb, false);
765 if (!vMissingTx.empty())
767 // TODO: optimize this to scan just part of the block chain?
768 if (ScanForWalletTransactions(pindexGenesisBlock))
769 fRepeat = true; // Found missing transactions: re-do Reaccept.
774 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
776 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
778 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
780 uint256 hash = tx.GetHash();
781 if (!txdb.ContainsTx(hash))
782 RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx);
785 if (!(IsCoinBase() || IsCoinStake()))
787 uint256 hash = GetHash();
788 if (!txdb.ContainsTx(hash))
790 printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
791 RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this);
796 void CWalletTx::RelayWalletTransaction()
799 RelayWalletTransaction(txdb);
802 void CWallet::ResendWalletTransactions()
804 // Do this infrequently and randomly to avoid giving away
805 // that these are our transactions.
806 static int64 nNextTime;
807 if (GetTime() < nNextTime)
809 bool fFirst = (nNextTime == 0);
810 nNextTime = GetTime() + GetRand(30 * 60);
814 // Only do it if there's been a new block since last time
815 static int64 nLastTime;
816 if (nTimeBestReceived < nLastTime)
818 nLastTime = GetTime();
820 // Rebroadcast any of our txes that aren't in a block yet
821 printf("ResendWalletTransactions()\n");
825 // Sort them in chronological order
826 multimap<unsigned int, CWalletTx*> mapSorted;
827 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
829 CWalletTx& wtx = item.second;
830 // Don't rebroadcast until it's had plenty of time that
831 // it should have gotten in already by now.
832 if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
833 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
835 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
837 CWalletTx& wtx = *item.second;
838 if (wtx.CheckTransaction())
839 wtx.RelayWalletTransaction(txdb);
841 printf("ResendWalletTransactions() : CheckTransaction failed for transaction %s\n", wtx.GetHash().ToString().c_str());
851 //////////////////////////////////////////////////////////////////////////////
857 int64 CWallet::GetBalance() const
862 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
864 const CWalletTx* pcoin = &(*it).second;
865 if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
867 nTotal += pcoin->GetAvailableCredit();
874 int64 CWallet::GetUnconfirmedBalance() const
879 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
881 const CWalletTx* pcoin = &(*it).second;
882 if (pcoin->IsFinal() && pcoin->IsConfirmed())
884 nTotal += pcoin->GetAvailableCredit();
890 // ppcoin: total coins staked (non-spendable until maturity)
891 int64 CWallet::GetStake() const
895 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
897 const CWalletTx* pcoin = &(*it).second;
898 if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
899 nTotal += CWallet::GetCredit(*pcoin);
904 int64 CWallet::GetNewMint() const
908 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
910 const CWalletTx* pcoin = &(*it).second;
911 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
912 nTotal += CWallet::GetCredit(*pcoin);
918 bool CWallet::SelectCoinsMinConf(int64 nTargetValue, unsigned int nSpendTime, int nConfMine, int nConfTheirs, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
923 // List of values less than target
924 pair<int64, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
925 coinLowestLarger.first = std::numeric_limits<int64>::max();
926 coinLowestLarger.second.first = NULL;
927 vector<pair<int64, pair<const CWalletTx*,unsigned int> > > vValue;
928 int64 nTotalLower = 0;
932 vector<const CWalletTx*> vCoins;
933 vCoins.reserve(mapWallet.size());
934 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
935 vCoins.push_back(&(*it).second);
936 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
938 BOOST_FOREACH(const CWalletTx* pcoin, vCoins)
940 if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
943 if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0)
946 int nDepth = pcoin->GetDepthInMainChain();
947 if (nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs))
950 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
952 if (pcoin->IsSpent(i) || !IsMine(pcoin->vout[i]))
955 if (pcoin->nTime > nSpendTime)
956 continue; // ppcoin: timestamp must not exceed spend time
958 int64 n = pcoin->vout[i].nValue;
963 pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin,i));
965 if (n == nTargetValue)
967 setCoinsRet.insert(coin.second);
968 nValueRet += coin.first;
971 else if (n < nTargetValue + CENT)
973 vValue.push_back(coin);
976 else if (n < coinLowestLarger.first)
978 coinLowestLarger = coin;
984 if (nTotalLower == nTargetValue || nTotalLower == nTargetValue + CENT)
986 for (unsigned int i = 0; i < vValue.size(); ++i)
988 setCoinsRet.insert(vValue[i].second);
989 nValueRet += vValue[i].first;
994 if (nTotalLower < nTargetValue + (coinLowestLarger.second.first ? CENT : 0))
996 if (coinLowestLarger.second.first == NULL)
998 setCoinsRet.insert(coinLowestLarger.second);
999 nValueRet += coinLowestLarger.first;
1003 if (nTotalLower >= nTargetValue + CENT)
1004 nTargetValue += CENT;
1006 // Solve subset sum by stochastic approximation
1007 sort(vValue.rbegin(), vValue.rend());
1008 vector<char> vfIncluded;
1009 vector<char> vfBest(vValue.size(), true);
1010 int64 nBest = nTotalLower;
1012 for (int nRep = 0; nRep < 1000 && nBest != nTargetValue; nRep++)
1014 vfIncluded.assign(vValue.size(), false);
1016 bool fReachedTarget = false;
1017 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
1019 for (unsigned int i = 0; i < vValue.size(); i++)
1021 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
1023 nTotal += vValue[i].first;
1024 vfIncluded[i] = true;
1025 if (nTotal >= nTargetValue)
1027 fReachedTarget = true;
1031 vfBest = vfIncluded;
1033 nTotal -= vValue[i].first;
1034 vfIncluded[i] = false;
1041 // If the next larger is still closer, return it
1042 if (coinLowestLarger.second.first && coinLowestLarger.first - nTargetValue <= nBest - nTargetValue)
1044 setCoinsRet.insert(coinLowestLarger.second);
1045 nValueRet += coinLowestLarger.first;
1048 for (unsigned int i = 0; i < vValue.size(); i++)
1051 setCoinsRet.insert(vValue[i].second);
1052 nValueRet += vValue[i].first;
1056 if (fDebug && GetBoolArg("-printselectcoin"))
1058 printf("SelectCoins() best subset: ");
1059 for (unsigned int i = 0; i < vValue.size(); i++)
1061 printf("%s ", FormatMoney(vValue[i].first).c_str());
1062 printf("total %s\n", FormatMoney(nBest).c_str());
1069 bool CWallet::SelectCoins(int64 nTargetValue, unsigned int nSpendTime, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
1071 return (SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 6, setCoinsRet, nValueRet) ||
1072 SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 1, setCoinsRet, nValueRet) ||
1073 SelectCoinsMinConf(nTargetValue, nSpendTime, 0, 1, setCoinsRet, nValueRet));
1079 bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
1082 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1088 if (vecSend.empty() || nValue < 0)
1091 wtxNew.BindWallet(this);
1094 LOCK2(cs_main, cs_wallet);
1095 // txdb must be opened before the mapWallet lock
1098 nFeeRet = nTransactionFee;
1102 wtxNew.vout.clear();
1103 wtxNew.fFromMe = true;
1105 int64 nTotalValue = nValue + nFeeRet;
1106 double dPriority = 0;
1107 // vouts to the payees
1108 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1109 wtxNew.vout.push_back(CTxOut(s.second, s.first));
1111 // Choose coins to use
1112 set<pair<const CWalletTx*,unsigned int> > setCoins;
1114 if (!SelectCoins(nTotalValue, wtxNew.nTime, setCoins, nValueIn))
1116 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1118 int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
1119 dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
1122 int64 nChange = nValueIn - nValue - nFeeRet;
1123 // if sub-cent change is required, the fee must be raised to at least MIN_TX_FEE
1124 // or until nChange becomes zero
1125 // NOTE: this depends on the exact behaviour of GetMinFee
1126 if (nFeeRet < MIN_TX_FEE && nChange > 0 && nChange < CENT)
1128 int64 nMoveToFee = min(nChange, MIN_TX_FEE - nFeeRet);
1129 nChange -= nMoveToFee;
1130 nFeeRet += nMoveToFee;
1133 // ppcoin: sub-cent change is moved to fee
1134 if (nChange > 0 && nChange < MIN_TXOUT_AMOUNT)
1142 // Note: We use a new key here to keep it from being obvious which side is the change.
1143 // The drawback is that by not reusing a previous key, the change may be lost if a
1144 // backup is restored, if the backup doesn't have the new private key for the change.
1145 // If we reused the old key, it would be possible to add code to look for and
1146 // rediscover unknown transactions that were written with keys of ours to recover
1147 // post-backup change.
1149 // Reserve a new key pair from key pool
1150 vector<unsigned char> vchPubKey = reservekey.GetReservedKey();
1151 // assert(mapKeys.count(vchPubKey));
1153 // Fill a vout to ourself
1154 // TODO: pass in scriptChange instead of reservekey so
1155 // change transaction isn't always pay-to-bitcoin-address
1156 CScript scriptChange;
1157 scriptChange.SetBitcoinAddress(vchPubKey);
1159 // Insert change txn at random position:
1160 vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
1161 wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
1164 reservekey.ReturnKey();
1167 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1168 wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
1172 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1173 if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
1177 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
1178 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1180 dPriority /= nBytes;
1182 // Check that enough fee is included
1183 int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
1184 int64 nMinFee = wtxNew.GetMinFee(1, false, GMF_SEND);
1185 if (nFeeRet < max(nPayFee, nMinFee))
1187 nFeeRet = max(nPayFee, nMinFee);
1191 // Fill vtxPrev by copying from previous transactions vtxPrev
1192 wtxNew.AddSupportingTransactions(txdb);
1193 wtxNew.fTimeReceivedIsTxTime = true;
1202 bool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
1204 vector< pair<CScript, int64> > vecSend;
1205 vecSend.push_back(make_pair(scriptPubKey, nValue));
1206 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet);
1209 // ppcoin: create coin stake transaction
1210 bool CWallet::CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int64 nSearchInterval, CTransaction& txNew)
1212 // The following split & combine thresholds are important to security
1213 // Should not be adjusted if you don't understand the consequences
1214 static unsigned int nStakeSplitAge = (60 * 60 * 24 * 90);
1215 int64 nCombineThreshold = GetProofOfWorkReward(GetLastBlockIndex(pindexBest, false)->nBits) / 3;
1217 CBigNum bnTargetPerCoinDay;
1218 bnTargetPerCoinDay.SetCompact(nBits);
1220 LOCK2(cs_main, cs_wallet);
1223 // Mark coin stake transaction
1224 CScript scriptEmpty;
1225 scriptEmpty.clear();
1226 txNew.vout.push_back(CTxOut(0, scriptEmpty));
1227 // Choose coins to use
1228 int64 nBalance = GetBalance();
1229 int64 nReserveBalance = 0;
1230 if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
1231 return error("CreateCoinStake : invalid reserve balance amount");
1232 if (nBalance <= nReserveBalance)
1234 set<pair<const CWalletTx*,unsigned int> > setCoins;
1235 vector<const CWalletTx*> vwtxPrev;
1237 if (!SelectCoins(nBalance - nReserveBalance, txNew.nTime, setCoins, nValueIn))
1239 if (setCoins.empty())
1242 CScript scriptPubKeyKernel;
1243 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1247 if (!txdb.ReadTxIndex(pcoin.first->GetHash(), txindex))
1250 // Read block header
1252 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
1254 static int nMaxStakeSearchInterval = 60;
1255 if (block.GetBlockTime() + nStakeMinAge > txNew.nTime - nMaxStakeSearchInterval)
1256 continue; // only count coins meeting min age requirement
1258 bool fKernelFound = false;
1259 for (unsigned int n=0; n<min(nSearchInterval,(int64)nMaxStakeSearchInterval) && !fKernelFound && !fShutdown; n++)
1261 // Search backward in time from the given txNew timestamp
1262 // Search nSearchInterval seconds back up to nMaxStakeSearchInterval
1263 uint256 hashProofOfStake = 0;
1264 COutPoint prevoutStake = COutPoint(pcoin.first->GetHash(), pcoin.second);
1265 if (CheckStakeKernelHash(nBits, block, txindex.pos.nTxPos - txindex.pos.nBlockPos, *pcoin.first, prevoutStake, txNew.nTime - n, hashProofOfStake))
1268 if (fDebug && GetBoolArg("-printcoinstake"))
1269 printf("CreateCoinStake : kernel found\n");
1270 vector<valtype> vSolutions;
1271 txnouttype whichType;
1272 CScript scriptPubKeyOut;
1273 scriptPubKeyKernel = pcoin.first->vout[pcoin.second].scriptPubKey;
1274 if (!Solver(scriptPubKeyKernel, whichType, vSolutions))
1276 if (fDebug && GetBoolArg("-printcoinstake"))
1277 printf("CreateCoinStake : failed to parse kernel\n", whichType);
1280 if (fDebug && GetBoolArg("-printcoinstake"))
1281 printf("CreateCoinStake : parsed kernel type=%d\n", whichType);
1282 if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH)
1284 if (fDebug && GetBoolArg("-printcoinstake"))
1285 printf("CreateCoinStake : no support for kernel type=%d\n", whichType);
1286 break; // only support pay to public key and pay to address
1288 if (whichType == TX_PUBKEYHASH) // pay to address type
1290 // convert to pay to public key type
1292 if (!keystore.GetKey(uint160(vSolutions[0]), key))
1294 if (fDebug && GetBoolArg("-printcoinstake"))
1295 printf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1296 break; // unable to find corresponding public key
1298 scriptPubKeyOut << key.GetPubKey() << OP_CHECKSIG;
1301 scriptPubKeyOut = scriptPubKeyKernel;
1304 txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1305 nCredit += pcoin.first->vout[pcoin.second].nValue;
1306 vwtxPrev.push_back(pcoin.first);
1307 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
1308 if (block.GetBlockTime() + nStakeSplitAge > txNew.nTime)
1309 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut)); //split stake
1310 if (fDebug && GetBoolArg("-printcoinstake"))
1311 printf("CreateCoinStake : added kernel type=%d\n", whichType);
1312 fKernelFound = true;
1316 if (fKernelFound || fShutdown)
1317 break; // if kernel is found stop searching
1319 if (nCredit == 0 || nCredit > nBalance - nReserveBalance)
1321 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1323 // Attempt to add more inputs
1324 // Only add coins of the same key/address as kernel
1325 if (txNew.vout.size() == 2 && ((pcoin.first->vout[pcoin.second].scriptPubKey == scriptPubKeyKernel || pcoin.first->vout[pcoin.second].scriptPubKey == txNew.vout[1].scriptPubKey))
1326 && pcoin.first->GetHash() != txNew.vin[0].prevout.hash)
1328 // Stop adding more inputs if already too many inputs
1329 if (txNew.vin.size() >= 100)
1331 // Stop adding more inputs if value is already pretty significant
1332 if (nCredit > nCombineThreshold)
1334 // Stop adding inputs if reached reserve limit
1335 if (nCredit + pcoin.first->vout[pcoin.second].nValue > nBalance - nReserveBalance)
1337 // Do not add additional significant input
1338 if (pcoin.first->vout[pcoin.second].nValue > nCombineThreshold)
1340 // Do not add input that is still too young
1341 if (pcoin.first->nTime + STAKE_MAX_AGE > txNew.nTime)
1343 txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1344 nCredit += pcoin.first->vout[pcoin.second].nValue;
1345 vwtxPrev.push_back(pcoin.first);
1348 // Calculate coin age reward
1352 if (!txNew.GetCoinAge(txdb, nCoinAge))
1353 return error("CreateCoinStake : failed to calculate coin age");
1354 nCredit += GetProofOfStakeReward(nCoinAge);
1360 // Set output amount
1361 if (txNew.vout.size() == 3)
1363 txNew.vout[1].nValue = ((nCredit - nMinFee) / 2 / CENT) * CENT;
1364 txNew.vout[2].nValue = nCredit - nMinFee - txNew.vout[1].nValue;
1367 txNew.vout[1].nValue = nCredit - nMinFee;
1371 BOOST_FOREACH(const CWalletTx* pcoin, vwtxPrev)
1373 if (!SignSignature(*this, *pcoin, txNew, nIn++))
1374 return error("CreateCoinStake : failed to sign coinstake");
1378 unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION);
1379 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1380 return error("CreateCoinStake : exceeded coinstake size limit");
1382 // Check enough fee is paid
1383 if (nMinFee < txNew.GetMinFee() - MIN_TX_FEE)
1385 nMinFee = txNew.GetMinFee() - MIN_TX_FEE;
1386 continue; // try signing again
1390 if (fDebug && GetBoolArg("-printfee"))
1391 printf("CreateCoinStake : fee for coinstake %s\n", FormatMoney(nMinFee).c_str());
1396 // Successfully generated coinstake
1400 // Call after CreateTransaction unless you want to abort
1401 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
1404 LOCK2(cs_main, cs_wallet);
1405 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
1407 // This is only to keep the database open to defeat the auto-flush for the
1408 // duration of this scope. This is the only place where this optimization
1409 // maybe makes sense; please don't do it anywhere else.
1410 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
1412 // Take key pair from key pool so it won't be used again
1413 reservekey.KeepKey();
1415 // Add tx to wallet, because if it has change it's also ours,
1416 // otherwise just for transaction history.
1417 AddToWallet(wtxNew);
1419 // Mark old coins as spent
1420 set<CWalletTx*> setCoins;
1421 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
1423 CWalletTx &coin = mapWallet[txin.prevout.hash];
1424 coin.BindWallet(this);
1425 coin.MarkSpent(txin.prevout.n);
1427 vWalletUpdated.push_back(coin.GetHash());
1434 // Track how many getdata requests our transaction gets
1435 mapRequestCount[wtxNew.GetHash()] = 0;
1438 if (!wtxNew.AcceptToMemoryPool())
1440 // This must not fail. The transaction has already been signed and recorded.
1441 printf("CommitTransaction() : Error: Transaction not valid");
1444 wtxNew.RelayWalletTransaction();
1453 string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1455 CReserveKey reservekey(this);
1460 string strError = _("Error: Wallet locked, unable to create transaction ");
1461 printf("SendMoney() : %s", strError.c_str());
1464 if (fWalletUnlockMintOnly)
1466 string strError = _("Error: Wallet unlocked for block minting only, unable to create transaction.");
1467 printf("SendMoney() : %s", strError.c_str());
1470 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
1473 if (nValue + nFeeRequired > GetBalance())
1474 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());
1476 strError = _("Error: Transaction creation failed ");
1477 printf("SendMoney() : %s", strError.c_str());
1481 if (fAskFee && !ThreadSafeAskFee(nFeeRequired, _("Sending...")))
1484 if (!CommitTransaction(wtxNew, reservekey))
1485 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.");
1493 string CWallet::SendMoneyToBitcoinAddress(const CBitcoinAddress& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1497 return _("Invalid amount");
1498 if (nValue + nTransactionFee > GetBalance())
1499 return _("Insufficient funds");
1501 // Parse bitcoin address
1502 CScript scriptPubKey;
1503 scriptPubKey.SetBitcoinAddress(address);
1505 return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
1511 int CWallet::LoadWallet(bool& fFirstRunRet)
1515 fFirstRunRet = false;
1516 int nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
1517 if (nLoadWalletRet == DB_NEED_REWRITE)
1519 if (CDB::Rewrite(strWalletFile, "\x04pool"))
1522 // Note: can't top-up keypool here, because wallet is locked.
1523 // User will be prompted to unlock wallet the next operation
1524 // the requires a new key.
1526 nLoadWalletRet = DB_NEED_REWRITE;
1529 if (nLoadWalletRet != DB_LOAD_OK)
1530 return nLoadWalletRet;
1531 fFirstRunRet = vchDefaultKey.empty();
1533 CreateThread(ThreadFlushWalletDB, &strWalletFile);
1538 bool CWallet::SetAddressBookName(const CBitcoinAddress& address, const string& strName)
1540 mapAddressBook[address] = strName;
1541 AddressBookRepaint();
1544 return CWalletDB(strWalletFile).WriteName(address.ToString(), strName);
1547 bool CWallet::DelAddressBookName(const CBitcoinAddress& address)
1549 mapAddressBook.erase(address);
1550 AddressBookRepaint();
1553 return CWalletDB(strWalletFile).EraseName(address.ToString());
1557 void CWallet::PrintWallet(const CBlock& block)
1561 if (block.IsProofOfWork() && mapWallet.count(block.vtx[0].GetHash()))
1563 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
1564 printf(" mine: %d %d %s", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), FormatMoney(wtx.GetCredit()).c_str());
1566 if (block.IsProofOfStake() && mapWallet.count(block.vtx[1].GetHash()))
1568 CWalletTx& wtx = mapWallet[block.vtx[1].GetHash()];
1569 printf(" stake: %d %d %s", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), FormatMoney(wtx.GetCredit()).c_str());
1575 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
1579 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
1580 if (mi != mapWallet.end())
1589 bool CWallet::SetDefaultKey(const std::vector<unsigned char> &vchPubKey)
1593 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
1596 vchDefaultKey = vchPubKey;
1600 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
1602 if (!pwallet->fFileBacked)
1604 strWalletFileOut = pwallet->strWalletFile;
1609 // Mark old keypool keys as used,
1610 // and generate all new keys
1612 bool CWallet::NewKeyPool()
1616 CWalletDB walletdb(strWalletFile);
1617 BOOST_FOREACH(int64 nIndex, setKeyPool)
1618 walletdb.ErasePool(nIndex);
1624 int64 nKeys = max(GetArg("-keypool", 100), (int64)0);
1625 for (int i = 0; i < nKeys; i++)
1628 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
1629 setKeyPool.insert(nIndex);
1631 printf("CWallet::NewKeyPool wrote %"PRI64d" new keys\n", nKeys);
1636 bool CWallet::TopUpKeyPool()
1644 CWalletDB walletdb(strWalletFile);
1647 unsigned int nTargetSize = max(GetArg("-keypool", 100), 0LL);
1648 while (setKeyPool.size() < (nTargetSize + 1))
1651 if (!setKeyPool.empty())
1652 nEnd = *(--setKeyPool.end()) + 1;
1653 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
1654 throw runtime_error("TopUpKeyPool() : writing generated key failed");
1655 setKeyPool.insert(nEnd);
1656 printf("keypool added key %"PRI64d", size=%d\n", nEnd, setKeyPool.size());
1662 void CWallet::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool)
1665 keypool.vchPubKey.clear();
1672 // Get the oldest key
1673 if(setKeyPool.empty())
1676 CWalletDB walletdb(strWalletFile);
1678 nIndex = *(setKeyPool.begin());
1679 setKeyPool.erase(setKeyPool.begin());
1680 if (!walletdb.ReadPool(nIndex, keypool))
1681 throw runtime_error("ReserveKeyFromKeyPool() : read failed");
1682 if (!HaveKey(Hash160(keypool.vchPubKey)))
1683 throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
1684 assert(!keypool.vchPubKey.empty());
1685 if (fDebug && GetBoolArg("-printkeypool"))
1686 printf("keypool reserve %"PRI64d"\n", nIndex);
1690 int64 CWallet::AddReserveKey(const CKeyPool& keypool)
1693 LOCK2(cs_main, cs_wallet);
1694 CWalletDB walletdb(strWalletFile);
1696 int64 nIndex = 1 + *(--setKeyPool.end());
1697 if (!walletdb.WritePool(nIndex, keypool))
1698 throw runtime_error("AddReserveKey() : writing added key failed");
1699 setKeyPool.insert(nIndex);
1705 void CWallet::KeepKey(int64 nIndex)
1707 // Remove from key pool
1710 CWalletDB walletdb(strWalletFile);
1711 walletdb.ErasePool(nIndex);
1713 printf("keypool keep %"PRI64d"\n", nIndex);
1716 void CWallet::ReturnKey(int64 nIndex)
1718 // Return to key pool
1721 setKeyPool.insert(nIndex);
1723 if (fDebug && GetBoolArg("-printkeypool"))
1724 printf("keypool return %"PRI64d"\n", nIndex);
1727 bool CWallet::GetKeyFromPool(vector<unsigned char>& result, bool fAllowReuse)
1733 ReserveKeyFromKeyPool(nIndex, keypool);
1736 if (fAllowReuse && !vchDefaultKey.empty())
1738 result = vchDefaultKey;
1741 if (IsLocked()) return false;
1742 result = GenerateNewKey();
1746 result = keypool.vchPubKey;
1751 int64 CWallet::GetOldestKeyPoolTime()
1755 ReserveKeyFromKeyPool(nIndex, keypool);
1759 return keypool.nTime;
1762 // ppcoin: check 'spent' consistency between wallet and txindex
1763 // ppcoin: fix wallet spent state according to txindex
1764 void CWallet::FixSpentCoins(int& nMismatchFound, int64& nBalanceInQuestion, bool fCheckOnly)
1767 nBalanceInQuestion = 0;
1770 vector<CWalletTx*> vCoins;
1771 vCoins.reserve(mapWallet.size());
1772 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1773 vCoins.push_back(&(*it).second);
1776 BOOST_FOREACH(CWalletTx* pcoin, vCoins)
1778 // Find the corresponding transaction index
1780 if (!txdb.ReadTxIndex(pcoin->GetHash(), txindex))
1782 for (int n=0; n < pcoin->vout.size(); n++)
1784 if (IsMine(pcoin->vout[n]) && pcoin->IsSpent(n) && (txindex.vSpent.size() <= n || txindex.vSpent[n].IsNull()))
1786 printf("FixSpentCoins found lost coin %sppc %s[%d], %s\n",
1787 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
1789 nBalanceInQuestion += pcoin->vout[n].nValue;
1792 pcoin->MarkUnspent(n);
1793 pcoin->WriteToDisk();
1796 else if (IsMine(pcoin->vout[n]) && !pcoin->IsSpent(n) && (txindex.vSpent.size() > n && !txindex.vSpent[n].IsNull()))
1798 printf("FixSpentCoins found spent coin %sppc %s[%d], %s\n",
1799 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
1801 nBalanceInQuestion += pcoin->vout[n].nValue;
1804 pcoin->MarkSpent(n);
1805 pcoin->WriteToDisk();
1812 // ppcoin: disable transaction (only for coinstake)
1813 void CWallet::DisableTransaction(const CTransaction &tx)
1815 if (!tx.IsCoinStake() || !IsFromMe(tx))
1816 return; // only disconnecting coinstake requires marking input unspent
1819 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1821 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
1822 if (mi != mapWallet.end())
1824 CWalletTx& prev = (*mi).second;
1825 if (txin.prevout.n < prev.vout.size() && IsMine(prev.vout[txin.prevout.n]))
1827 prev.MarkUnspent(txin.prevout.n);
1834 vector<unsigned char> CReserveKey::GetReservedKey()
1839 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
1841 vchPubKey = keypool.vchPubKey;
1844 printf("CReserveKey::GetReservedKey(): Warning: using default key instead of a new key, top up your keypool.");
1845 vchPubKey = pwallet->vchDefaultKey;
1848 assert(!vchPubKey.empty());
1852 void CReserveKey::KeepKey()
1855 pwallet->KeepKey(nIndex);
1860 void CReserveKey::ReturnKey()
1863 pwallet->ReturnKey(nIndex);
1868 void CWallet::GetAllReserveAddresses(set<CBitcoinAddress>& setAddress)
1872 CWalletDB walletdb(strWalletFile);
1874 LOCK2(cs_main, cs_wallet);
1875 BOOST_FOREACH(const int64& id, setKeyPool)
1878 if (!walletdb.ReadPool(id, keypool))
1879 throw runtime_error("GetAllReserveKeyHashes() : read failed");
1880 CBitcoinAddress address(keypool.vchPubKey);
1881 assert(!keypool.vchPubKey.empty());
1882 if (!HaveKey(address))
1883 throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
1884 setAddress.insert(address);