1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
9 #include "ui_interface.h"
14 extern int nStakeMaxAge;
17 //////////////////////////////////////////////////////////////////////////////
22 struct CompareValueOnly
24 bool operator()(const pair<int64, pair<const CWalletTx*, unsigned int> >& t1,
25 const pair<int64, pair<const CWalletTx*, unsigned int> >& t2) const
27 return t1.first < t2.first;
31 CPubKey CWallet::GenerateNewKey()
33 bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
37 key.MakeNewKey(fCompressed);
39 // Compressed public keys were introduced in version 0.6.0
41 SetMinVersion(FEATURE_COMPRPUBKEY);
43 CPubKey pubkey = key.GetPubKey();
45 // Create new metadata
46 int64 nCreationTime = GetTime();
47 mapKeyMetadata[pubkey.GetID()] = CKeyMetadata(nCreationTime);
48 if (!nTimeFirstKey || nCreationTime < nTimeFirstKey)
49 nTimeFirstKey = nCreationTime;
52 throw std::runtime_error("CWallet::GenerateNewKey() : AddKey failed");
53 return key.GetPubKey();
56 bool CWallet::AddKey(const CKey& key)
58 CPubKey pubkey = key.GetPubKey();
60 if (!CCryptoKeyStore::AddKey(key))
65 return CWalletDB(strWalletFile).WriteKey(pubkey, key.GetPrivKey(), mapKeyMetadata[pubkey.GetID()]);
69 bool CWallet::AddCryptedKey(const CPubKey &vchPubKey, const vector<unsigned char> &vchCryptedSecret)
71 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
77 if (pwalletdbEncryption)
78 return pwalletdbEncryption->WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]);
80 return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]);
85 bool CWallet::LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &meta)
87 if (meta.nCreateTime && (!nTimeFirstKey || meta.nCreateTime < nTimeFirstKey))
88 nTimeFirstKey = meta.nCreateTime;
90 mapKeyMetadata[pubkey.GetID()] = meta;
94 bool CWallet::AddCScript(const CScript& redeemScript)
96 if (!CCryptoKeyStore::AddCScript(redeemScript))
100 return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript);
103 // ppcoin: optional setting to unlock wallet for block minting only;
104 // serves to disable the trivial sendmoney when OS account compromised
105 bool fWalletUnlockMintOnly = false;
107 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
113 CKeyingMaterial vMasterKey;
117 BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
119 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
121 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
123 if (CCryptoKeyStore::Unlock(vMasterKey))
130 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
132 bool fWasLocked = IsLocked();
139 CKeyingMaterial vMasterKey;
140 BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
142 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
144 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
146 if (CCryptoKeyStore::Unlock(vMasterKey))
148 int64 nStartTime = GetTimeMillis();
149 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
150 pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
152 nStartTime = GetTimeMillis();
153 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
154 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
156 if (pMasterKey.second.nDeriveIterations < 25000)
157 pMasterKey.second.nDeriveIterations = 25000;
159 printf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
161 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
163 if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
165 CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
176 void CWallet::SetBestChain(const CBlockLocator& loc)
178 CWalletDB walletdb(strWalletFile);
179 walletdb.WriteBestBlock(loc);
182 // This class implements an addrIncoming entry that causes pre-0.4
183 // clients to crash on startup if reading a private-key-encrypted wallet.
184 class CCorruptAddress
189 if (nType & SER_DISK)
194 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
196 if (nWalletVersion >= nVersion)
199 // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
200 if (fExplicit && nVersion > nWalletMaxVersion)
201 nVersion = FEATURE_LATEST;
203 nWalletVersion = nVersion;
205 if (nVersion > nWalletMaxVersion)
206 nWalletMaxVersion = nVersion;
210 CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile);
211 if (nWalletVersion >= 40000)
213 // Versions prior to 0.4.0 did not support the "minversion" record.
214 // Use a CCorruptAddress to make them crash instead.
215 CCorruptAddress corruptAddress;
216 pwalletdb->WriteSetting("addrIncoming", corruptAddress);
218 if (nWalletVersion > 40000)
219 pwalletdb->WriteMinVersion(nWalletVersion);
227 bool CWallet::SetMaxVersion(int nVersion)
229 // cannot downgrade below current version
230 if (nWalletVersion > nVersion)
233 nWalletMaxVersion = nVersion;
238 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
243 CKeyingMaterial vMasterKey;
244 RandAddSeedPerfmon();
246 vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
247 RAND_bytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
249 CMasterKey kMasterKey;
251 RandAddSeedPerfmon();
252 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
253 RAND_bytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
256 int64 nStartTime = GetTimeMillis();
257 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
258 kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
260 nStartTime = GetTimeMillis();
261 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
262 kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
264 if (kMasterKey.nDeriveIterations < 25000)
265 kMasterKey.nDeriveIterations = 25000;
267 printf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
269 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
271 if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
276 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
279 pwalletdbEncryption = new CWalletDB(strWalletFile);
280 if (!pwalletdbEncryption->TxnBegin())
282 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
285 if (!EncryptKeys(vMasterKey))
288 pwalletdbEncryption->TxnAbort();
289 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.
292 // Encryption was introduced in version 0.4.0
293 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
297 if (!pwalletdbEncryption->TxnCommit())
298 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.
300 delete pwalletdbEncryption;
301 pwalletdbEncryption = NULL;
305 Unlock(strWalletPassphrase);
309 // Need to completely rewrite the wallet file; if we don't, bdb might keep
310 // bits of the unencrypted private key in slack space in the database file.
311 CDB::Rewrite(strWalletFile);
314 NotifyStatusChanged(this);
319 int64 CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
321 int64 nRet = nOrderPosNext++;
323 pwalletdb->WriteOrderPosNext(nOrderPosNext);
325 CWalletDB(strWalletFile).WriteOrderPosNext(nOrderPosNext);
330 CWallet::TxItems CWallet::OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount)
332 CWalletDB walletdb(strWalletFile);
334 // First: get all CWalletTx and CAccountingEntry into a sorted-by-order multimap.
337 // Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry
338 // would make this much faster for applications that do this a lot.
339 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
341 CWalletTx* wtx = &((*it).second);
342 txOrdered.insert(make_pair(wtx->nOrderPos, TxPair(wtx, (CAccountingEntry*)0)));
345 walletdb.ListAccountCreditDebit(strAccount, acentries);
346 BOOST_FOREACH(CAccountingEntry& entry, acentries)
348 txOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
354 void CWallet::WalletUpdateSpent(const CTransaction &tx)
356 // Anytime a signature is successfully verified, it's proof the outpoint is spent.
357 // Update the wallet spent flag if it doesn't know due to wallet.dat being
358 // restored from backup or the user making copies of wallet.dat.
361 BOOST_FOREACH(const CTxIn& txin, tx.vin)
363 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
364 if (mi != mapWallet.end())
366 CWalletTx& wtx = (*mi).second;
367 if (txin.prevout.n >= wtx.vout.size())
368 printf("WalletUpdateSpent: bad wtx %s\n", wtx.GetHash().ToString().c_str());
369 else if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n]))
371 printf("WalletUpdateSpent found spent coin %snvc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
372 wtx.MarkSpent(txin.prevout.n);
374 NotifyTransactionChanged(this, txin.prevout.hash, CT_UPDATED);
381 void CWallet::MarkDirty()
385 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
386 item.second.MarkDirty();
390 bool CWallet::AddToWallet(const CWalletTx& wtxIn)
392 uint256 hash = wtxIn.GetHash();
395 // Inserts only if not already there, returns tx inserted or tx found
396 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
397 CWalletTx& wtx = (*ret.first).second;
398 wtx.BindWallet(this);
399 bool fInsertedNew = ret.second;
402 wtx.nTimeReceived = GetAdjustedTime();
403 wtx.nOrderPos = IncOrderPosNext();
405 wtx.nTimeSmart = wtx.nTimeReceived;
406 if (wtxIn.hashBlock != 0)
408 if (mapBlockIndex.count(wtxIn.hashBlock))
410 unsigned int latestNow = wtx.nTimeReceived;
411 unsigned int latestEntry = 0;
413 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
414 int64 latestTolerated = latestNow + 300;
415 std::list<CAccountingEntry> acentries;
416 TxItems txOrdered = OrderedTxItems(acentries);
417 for (TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
419 CWalletTx *const pwtx = (*it).second.first;
422 CAccountingEntry *const pacentry = (*it).second.second;
426 nSmartTime = pwtx->nTimeSmart;
428 nSmartTime = pwtx->nTimeReceived;
431 nSmartTime = pacentry->nTime;
432 if (nSmartTime <= latestTolerated)
434 latestEntry = nSmartTime;
435 if (nSmartTime > latestNow)
436 latestNow = nSmartTime;
442 unsigned int& blocktime = mapBlockIndex[wtxIn.hashBlock]->nTime;
443 wtx.nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
446 printf("AddToWallet() : found %s in block %s not in index\n",
447 wtxIn.GetHash().ToString().substr(0,10).c_str(),
448 wtxIn.hashBlock.ToString().c_str());
452 bool fUpdated = false;
456 if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
458 wtx.hashBlock = wtxIn.hashBlock;
461 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
463 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
464 wtx.nIndex = wtxIn.nIndex;
467 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
469 wtx.fFromMe = wtxIn.fFromMe;
472 fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);
476 printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
479 if (fInsertedNew || fUpdated)
480 if (!wtx.WriteToDisk())
483 // If default receiving address gets used, replace it with a new one
484 CScript scriptDefaultKey;
485 scriptDefaultKey.SetDestination(vchDefaultKey.GetID());
486 BOOST_FOREACH(const CTxOut& txout, wtx.vout)
488 if (txout.scriptPubKey == scriptDefaultKey)
490 CPubKey newDefaultKey;
491 if (GetKeyFromPool(newDefaultKey, false))
493 SetDefaultKey(newDefaultKey);
494 SetAddressBookName(vchDefaultKey.GetID(), "");
499 // since AddToWallet is called directly for self-originating transactions, check for consumption of own coins
500 WalletUpdateSpent(wtx);
502 // Notify UI of new or updated transaction
503 NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
508 // Add a transaction to the wallet, or update it.
509 // pblock is optional, but should be provided if the transaction is known to be in a block.
510 // If fUpdate is true, existing transactions will be updated.
511 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fFindBlock)
513 uint256 hash = tx.GetHash();
516 bool fExisted = mapWallet.count(hash);
517 if (fExisted && !fUpdate) return false;
518 if (fExisted || IsMine(tx) || IsFromMe(tx))
520 CWalletTx wtx(this,tx);
521 // Get merkle branch if transaction was found in a block
523 wtx.SetMerkleBranch(pblock);
524 return AddToWallet(wtx);
527 WalletUpdateSpent(tx);
532 bool CWallet::EraseFromWallet(uint256 hash)
538 if (mapWallet.erase(hash))
539 CWalletDB(strWalletFile).EraseTx(hash);
545 bool CWallet::IsMine(const CTxIn &txin) const
549 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
550 if (mi != mapWallet.end())
552 const CWalletTx& prev = (*mi).second;
553 if (txin.prevout.n < prev.vout.size())
554 if (IsMine(prev.vout[txin.prevout.n]))
561 int64 CWallet::GetDebit(const CTxIn &txin) const
565 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
566 if (mi != mapWallet.end())
568 const CWalletTx& prev = (*mi).second;
569 if (txin.prevout.n < prev.vout.size())
570 if (IsMine(prev.vout[txin.prevout.n]))
571 return prev.vout[txin.prevout.n].nValue;
577 bool CWallet::IsChange(const CTxOut& txout) const
579 CTxDestination address;
581 // TODO: fix handling of 'change' outputs. The assumption is that any
582 // payment to a TX_PUBKEYHASH that is mine but isn't in the address book
583 // is change. That assumption is likely to break when we implement multisignature
584 // wallets that return change back into a multi-signature-protected address;
585 // a better way of identifying which outputs are 'the send' and which are
586 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
587 // which output, if any, was change).
588 if (ExtractDestination(txout.scriptPubKey, address) && ::IsMine(*this, address))
591 if (!mapAddressBook.count(address))
597 int64 CWalletTx::GetTxTime() const
599 int64 n = nTimeSmart;
600 return n ? n : nTimeReceived;
603 int CWalletTx::GetRequestCount() const
605 // Returns -1 if it wasn't being tracked
608 LOCK(pwallet->cs_wallet);
609 if (IsCoinBase() || IsCoinStake())
614 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
615 if (mi != pwallet->mapRequestCount.end())
616 nRequests = (*mi).second;
621 // Did anyone request this transaction?
622 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
623 if (mi != pwallet->mapRequestCount.end())
625 nRequests = (*mi).second;
627 // How about the block it's in?
628 if (nRequests == 0 && hashBlock != 0)
630 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
631 if (mi != pwallet->mapRequestCount.end())
632 nRequests = (*mi).second;
634 nRequests = 1; // If it's in someone else's block it must have got out
642 void CWalletTx::GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, list<pair<CTxDestination, int64> >& listReceived,
643 list<pair<CTxDestination, int64> >& listSent, int64& nFee, string& strSentAccount) const
645 nGeneratedImmature = nGeneratedMature = nFee = 0;
646 listReceived.clear();
648 strSentAccount = strFromAccount;
650 if (IsCoinBase() || IsCoinStake())
652 if (GetBlocksToMaturity() > 0)
653 nGeneratedImmature = pwallet->GetCredit(*this);
655 nGeneratedMature = GetCredit();
660 int64 nDebit = GetDebit();
661 if (nDebit > 0) // debit>0 means we signed/sent this transaction
663 int64 nValueOut = GetValueOut();
664 nFee = nDebit - nValueOut;
668 BOOST_FOREACH(const CTxOut& txout, vout)
670 CTxDestination address;
671 vector<unsigned char> vchPubKey;
672 if (!ExtractDestination(txout.scriptPubKey, address))
674 printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
675 this->GetHash().ToString().c_str());
678 // Don't report 'change' txouts
679 if (nDebit > 0 && pwallet->IsChange(txout))
683 listSent.push_back(make_pair(address, txout.nValue));
685 if (pwallet->IsMine(txout))
686 listReceived.push_back(make_pair(address, txout.nValue));
691 void CWalletTx::GetAccountAmounts(const string& strAccount, int64& nGenerated, int64& nReceived,
692 int64& nSent, int64& nFee) const
694 nGenerated = nReceived = nSent = nFee = 0;
696 int64 allGeneratedImmature, allGeneratedMature, allFee;
697 allGeneratedImmature = allGeneratedMature = allFee = 0;
698 string strSentAccount;
699 list<pair<CTxDestination, int64> > listReceived;
700 list<pair<CTxDestination, int64> > listSent;
701 GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount);
703 if (strAccount == "")
704 nGenerated = allGeneratedMature;
705 if (strAccount == strSentAccount)
707 BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& s, listSent)
712 LOCK(pwallet->cs_wallet);
713 BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listReceived)
715 if (pwallet->mapAddressBook.count(r.first))
717 map<CTxDestination, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);
718 if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)
719 nReceived += r.second;
721 else if (strAccount.empty())
723 nReceived += r.second;
729 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
733 const int COPY_DEPTH = 3;
734 if (SetMerkleBranch() < COPY_DEPTH)
736 vector<uint256> vWorkQueue;
737 BOOST_FOREACH(const CTxIn& txin, vin)
738 vWorkQueue.push_back(txin.prevout.hash);
740 // This critsect is OK because txdb is already open
742 LOCK(pwallet->cs_wallet);
743 map<uint256, const CMerkleTx*> mapWalletPrev;
744 set<uint256> setAlreadyDone;
745 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
747 uint256 hash = vWorkQueue[i];
748 if (setAlreadyDone.count(hash))
750 setAlreadyDone.insert(hash);
753 map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
754 if (mi != pwallet->mapWallet.end())
757 BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev)
758 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
760 else if (mapWalletPrev.count(hash))
762 tx = *mapWalletPrev[hash];
764 else if (!fClient && txdb.ReadDiskTx(hash, tx))
770 printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
774 int nDepth = tx.SetMerkleBranch();
775 vtxPrev.push_back(tx);
777 if (nDepth < COPY_DEPTH)
779 BOOST_FOREACH(const CTxIn& txin, tx.vin)
780 vWorkQueue.push_back(txin.prevout.hash);
786 reverse(vtxPrev.begin(), vtxPrev.end());
789 bool CWalletTx::WriteToDisk()
791 return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
794 // Scan the block chain (starting in pindexStart) for transactions
795 // from or to us. If fUpdate is true, found transactions that already
796 // exist in the wallet will be updated.
797 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
801 CBlockIndex* pindex = pindexStart;
807 block.ReadFromDisk(pindex, true);
808 BOOST_FOREACH(CTransaction& tx, block.vtx)
810 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
813 pindex = pindex->pnext;
819 int CWallet::ScanForWalletTransaction(const uint256& hashTx)
822 tx.ReadFromDisk(COutPoint(hashTx, 0));
823 if (AddToWalletIfInvolvingMe(tx, NULL, true, true))
828 void CWallet::ReacceptWalletTransactions()
836 vector<CDiskTxPos> vMissingTx;
837 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
839 CWalletTx& wtx = item.second;
840 if ((wtx.IsCoinBase() && wtx.IsSpent(0)) || (wtx.IsCoinStake() && wtx.IsSpent(1)))
844 bool fUpdated = false;
845 if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
847 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
848 if (txindex.vSpent.size() != wtx.vout.size())
850 printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %"PRIszu" != wtx.vout.size() %"PRIszu"\n", txindex.vSpent.size(), wtx.vout.size());
853 for (unsigned int i = 0; i < txindex.vSpent.size(); i++)
857 if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i]))
861 vMissingTx.push_back(txindex.vSpent[i]);
866 printf("ReacceptWalletTransactions found spent coin %snvc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
873 // Re-accept any txes of ours that aren't already in a block
874 if (!(wtx.IsCoinBase() || wtx.IsCoinStake()))
875 wtx.AcceptWalletTransaction(txdb, false);
878 if (!vMissingTx.empty())
880 // TODO: optimize this to scan just part of the block chain?
881 if (ScanForWalletTransactions(pindexGenesisBlock))
882 fRepeat = true; // Found missing transactions: re-do re-accept.
887 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
889 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
891 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
893 uint256 hash = tx.GetHash();
894 if (!txdb.ContainsTx(hash))
895 RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx);
898 if (!(IsCoinBase() || IsCoinStake()))
900 uint256 hash = GetHash();
901 if (!txdb.ContainsTx(hash))
903 printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
904 RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this);
909 void CWalletTx::RelayWalletTransaction()
912 RelayWalletTransaction(txdb);
915 void CWallet::ResendWalletTransactions()
917 // Do this infrequently and randomly to avoid giving away
918 // that these are our transactions.
919 static int64 nNextTime;
920 if (GetTime() < nNextTime)
922 bool fFirst = (nNextTime == 0);
923 nNextTime = GetTime() + GetRand(30 * 60);
927 // Only do it if there's been a new block since last time
928 static int64 nLastTime;
929 if (nTimeBestReceived < nLastTime)
931 nLastTime = GetTime();
933 // Rebroadcast any of our txes that aren't in a block yet
934 printf("ResendWalletTransactions()\n");
938 // Sort them in chronological order
939 multimap<unsigned int, CWalletTx*> mapSorted;
940 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
942 CWalletTx& wtx = item.second;
943 // Don't rebroadcast until it's had plenty of time that
944 // it should have gotten in already by now.
945 if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
946 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
948 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
950 CWalletTx& wtx = *item.second;
951 if (wtx.CheckTransaction())
952 wtx.RelayWalletTransaction(txdb);
954 printf("ResendWalletTransactions() : CheckTransaction failed for transaction %s\n", wtx.GetHash().ToString().c_str());
964 //////////////////////////////////////////////////////////////////////////////
970 int64 CWallet::GetBalance() const
975 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
977 const CWalletTx* pcoin = &(*it).second;
978 if (pcoin->IsConfirmed())
979 nTotal += pcoin->GetAvailableCredit();
986 int64 CWallet::GetUnconfirmedBalance() const
991 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
993 const CWalletTx* pcoin = &(*it).second;
994 if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
995 nTotal += pcoin->GetAvailableCredit();
1001 int64 CWallet::GetImmatureBalance() const
1006 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1008 const CWalletTx& pcoin = (*it).second;
1009 if (pcoin.IsCoinBase() && pcoin.GetBlocksToMaturity() > 0 && pcoin.IsInMainChain())
1010 nTotal += GetCredit(pcoin);
1016 // populate vCoins with vector of spendable COutputs
1017 void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed) const
1023 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1025 const CWalletTx* pcoin = &(*it).second;
1027 if (!pcoin->IsFinal())
1030 if (fOnlyConfirmed && !pcoin->IsConfirmed())
1033 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
1036 if(pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0)
1039 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
1040 if (!(pcoin->IsSpent(i)) && IsMine(pcoin->vout[i]) && pcoin->vout[i].nValue > 0)
1041 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain()));
1046 static void ApproximateBestSubset(vector<pair<int64, pair<const CWalletTx*,unsigned int> > >vValue, int64 nTotalLower, int64 nTargetValue,
1047 vector<char>& vfBest, int64& nBest, int iterations = 1000)
1049 vector<char> vfIncluded;
1051 vfBest.assign(vValue.size(), true);
1052 nBest = nTotalLower;
1054 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
1056 vfIncluded.assign(vValue.size(), false);
1058 bool fReachedTarget = false;
1059 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
1061 for (unsigned int i = 0; i < vValue.size(); i++)
1063 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
1065 nTotal += vValue[i].first;
1066 vfIncluded[i] = true;
1067 if (nTotal >= nTargetValue)
1069 fReachedTarget = true;
1073 vfBest = vfIncluded;
1075 nTotal -= vValue[i].first;
1076 vfIncluded[i] = false;
1084 // ppcoin: total coins staked (non-spendable until maturity)
1085 int64 CWallet::GetStake() const
1089 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1091 const CWalletTx* pcoin = &(*it).second;
1092 if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1093 nTotal += CWallet::GetCredit(*pcoin);
1098 int64 CWallet::GetNewMint() const
1102 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1104 const CWalletTx* pcoin = &(*it).second;
1105 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1106 nTotal += CWallet::GetCredit(*pcoin);
1111 bool CWallet::SelectCoinsMinConf(int64 nTargetValue, unsigned int nSpendTime, int nConfMine, int nConfTheirs, vector<COutput> vCoins, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
1113 setCoinsRet.clear();
1116 // List of values less than target
1117 pair<int64, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
1118 coinLowestLarger.first = std::numeric_limits<int64>::max();
1119 coinLowestLarger.second.first = NULL;
1120 vector<pair<int64, pair<const CWalletTx*,unsigned int> > > vValue;
1121 int64 nTotalLower = 0;
1123 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
1125 BOOST_FOREACH(COutput output, vCoins)
1127 const CWalletTx *pcoin = output.tx;
1129 if (output.nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs))
1134 if (pcoin->nTime > nSpendTime)
1135 continue; // ppcoin: timestamp must not exceed spend time
1137 int64 n = pcoin->vout[i].nValue;
1139 pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1141 if (n == nTargetValue)
1143 setCoinsRet.insert(coin.second);
1144 nValueRet += coin.first;
1147 else if (n < nTargetValue + CENT)
1149 vValue.push_back(coin);
1152 else if (n < coinLowestLarger.first)
1154 coinLowestLarger = coin;
1158 if (nTotalLower == nTargetValue)
1160 for (unsigned int i = 0; i < vValue.size(); ++i)
1162 setCoinsRet.insert(vValue[i].second);
1163 nValueRet += vValue[i].first;
1168 if (nTotalLower < nTargetValue)
1170 if (coinLowestLarger.second.first == NULL)
1172 setCoinsRet.insert(coinLowestLarger.second);
1173 nValueRet += coinLowestLarger.first;
1177 // Solve subset sum by stochastic approximation
1178 sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
1179 vector<char> vfBest;
1182 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);
1183 if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT)
1184 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000);
1186 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
1187 // or the next bigger coin is closer), return the bigger coin
1188 if (coinLowestLarger.second.first &&
1189 ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest))
1191 setCoinsRet.insert(coinLowestLarger.second);
1192 nValueRet += coinLowestLarger.first;
1195 for (unsigned int i = 0; i < vValue.size(); i++)
1198 setCoinsRet.insert(vValue[i].second);
1199 nValueRet += vValue[i].first;
1202 if (fDebug && GetBoolArg("-printpriority"))
1205 printf("SelectCoins() best subset: ");
1206 for (unsigned int i = 0; i < vValue.size(); i++)
1208 printf("%s ", FormatMoney(vValue[i].first).c_str());
1209 printf("total %s\n", FormatMoney(nBest).c_str());
1216 bool CWallet::SelectCoins(int64 nTargetValue, unsigned int nSpendTime, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
1218 vector<COutput> vCoins;
1219 AvailableCoins(vCoins);
1221 return (SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 6, vCoins, setCoinsRet, nValueRet) ||
1222 SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 1, vCoins, setCoinsRet, nValueRet) ||
1223 SelectCoinsMinConf(nTargetValue, nSpendTime, 0, 1, vCoins, setCoinsRet, nValueRet));
1229 bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
1232 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1238 if (vecSend.empty() || nValue < 0)
1241 wtxNew.BindWallet(this);
1244 LOCK2(cs_main, cs_wallet);
1245 // txdb must be opened before the mapWallet lock
1248 nFeeRet = nTransactionFee;
1252 wtxNew.vout.clear();
1253 wtxNew.fFromMe = true;
1255 int64 nTotalValue = nValue + nFeeRet;
1256 double dPriority = 0;
1257 // vouts to the payees
1258 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1259 wtxNew.vout.push_back(CTxOut(s.second, s.first));
1261 // Choose coins to use
1262 set<pair<const CWalletTx*,unsigned int> > setCoins;
1264 if (!SelectCoins(nTotalValue, wtxNew.nTime, setCoins, nValueIn))
1266 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1268 int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
1269 dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
1272 int64 nChange = nValueIn - nValue - nFeeRet;
1273 // if sub-cent change is required, the fee must be raised to at least MIN_TX_FEE
1274 // or until nChange becomes zero
1275 // NOTE: this depends on the exact behaviour of GetMinFee
1276 if (nFeeRet < MIN_TX_FEE && nChange > 0 && nChange < CENT)
1278 int64 nMoveToFee = min(nChange, MIN_TX_FEE - nFeeRet);
1279 nChange -= nMoveToFee;
1280 nFeeRet += nMoveToFee;
1283 // ppcoin: sub-cent change is moved to fee
1284 if (nChange > 0 && nChange < MIN_TXOUT_AMOUNT)
1292 // Note: We use a new key here to keep it from being obvious which side is the change.
1293 // The drawback is that by not reusing a previous key, the change may be lost if a
1294 // backup is restored, if the backup doesn't have the new private key for the change.
1295 // If we reused the old key, it would be possible to add code to look for and
1296 // rediscover unknown transactions that were written with keys of ours to recover
1297 // post-backup change.
1299 // Reserve a new key pair from key pool
1300 CPubKey vchPubKey = reservekey.GetReservedKey();
1301 // assert(mapKeys.count(vchPubKey));
1303 // Fill a vout to ourself
1304 // TODO: pass in scriptChange instead of reservekey so
1305 // change transaction isn't always pay-to-bitcoin-address
1306 CScript scriptChange;
1307 scriptChange.SetDestination(vchPubKey.GetID());
1309 // Insert change txn at random position:
1310 vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
1311 wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
1314 reservekey.ReturnKey();
1317 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1318 wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
1322 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1323 if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
1327 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
1328 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1330 dPriority /= nBytes;
1332 // Check that enough fee is included
1333 int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
1334 int64 nMinFee = wtxNew.GetMinFee(1, false, GMF_SEND);
1336 if (nFeeRet < max(nPayFee, nMinFee))
1338 nFeeRet = max(nPayFee, nMinFee);
1342 // Fill vtxPrev by copying from previous transactions vtxPrev
1343 wtxNew.AddSupportingTransactions(txdb);
1344 wtxNew.fTimeReceivedIsTxTime = true;
1353 bool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
1355 vector< pair<CScript, int64> > vecSend;
1356 vecSend.push_back(make_pair(scriptPubKey, nValue));
1357 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet);
1360 // NovaCoin: get current stake generation power
1361 uint64 CWallet::GetStakeMintPower(const CKeyStore& keystore, enum StakeWeightMode mode)
1363 LOCK2(cs_main, cs_wallet);
1365 // Choose coins to use
1366 int64 nBalance = GetBalance();
1367 int64 nReserveBalance = 0;
1368 uint64 nCoinAge = 0;
1370 if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
1372 error("CreateCoinStake : invalid reserve balance amount");
1376 if (nBalance <= nReserveBalance)
1379 set<pair<const CWalletTx*,unsigned int> > setCoins;
1380 vector<const CWalletTx*> vwtxPrev;
1382 if (!SelectCoins(nBalance - nReserveBalance, GetTime(), setCoins, nValueIn))
1384 if (setCoins.empty())
1387 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1391 if (!txdb.ReadTxIndex(pcoin.first->GetHash(), txindex))
1397 // Do not count input that is still less than 30 days old
1398 if (pcoin.first->nTime + nStakeMinAge > GetTime())
1401 case STAKE_MAXWEIGHT:
1402 // Do not count input that is still less than 90 days old
1403 if (pcoin.first->nTime + nStakeMaxAge > GetTime())
1406 case STAKE_MINWEIGHT:
1407 // Count only inputs with suitable age (from 30 to 90 days old)
1408 if (pcoin.first->nTime + nStakeMaxAge < GetTime())
1410 if (pcoin.first->nTime + nStakeMinAge > GetTime())
1413 case STAKE_BELOWMIN:
1414 // Count only inputs with suitable age (less than 30 days old)
1415 if (pcoin.first->nTime + nStakeMinAge < GetTime())
1420 CBigNum bnCentSecond = CBigNum(pcoin.first->vout[pcoin.second].nValue) * (GetTime()-pcoin.first->nTime) / CENT;
1421 CBigNum bnCoinDay = bnCentSecond * CENT / COIN / (24 * 60 * 60);
1424 nCoinAge += bnCoinDay.getuint64();
1427 if (fDebug && GetBoolArg("-printcoinage"))
1428 printf("StakePower bnCoinDay=%"PRI64d"\n", nCoinAge);
1433 // ppcoin: create coin stake transaction
1434 bool CWallet::CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int64 nSearchInterval, CTransaction& txNew)
1436 // The following split & combine thresholds are important to security
1437 // Should not be adjusted if you don't understand the consequences
1438 static unsigned int nStakeSplitAge = (60 * 60 * 24 * 90);
1439 int64 nCombineThreshold = GetProofOfWorkReward(GetLastBlockIndex(pindexBest, false)->nBits) / 3;
1441 CBigNum bnTargetPerCoinDay;
1442 bnTargetPerCoinDay.SetCompact(nBits);
1444 LOCK2(cs_main, cs_wallet);
1447 // Mark coin stake transaction
1448 CScript scriptEmpty;
1449 scriptEmpty.clear();
1450 txNew.vout.push_back(CTxOut(0, scriptEmpty));
1451 // Choose coins to use
1452 int64 nBalance = GetBalance();
1453 int64 nReserveBalance = 0;
1454 if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
1455 return error("CreateCoinStake : invalid reserve balance amount");
1456 if (nBalance <= nReserveBalance)
1458 set<pair<const CWalletTx*,unsigned int> > setCoins;
1459 vector<const CWalletTx*> vwtxPrev;
1461 if (!SelectCoins(nBalance - nReserveBalance, txNew.nTime, setCoins, nValueIn))
1463 if (setCoins.empty())
1466 CScript scriptPubKeyKernel;
1467 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1471 if (!txdb.ReadTxIndex(pcoin.first->GetHash(), txindex))
1474 // Read block header
1476 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
1478 static int nMaxStakeSearchInterval = 60;
1479 if (block.GetBlockTime() + nStakeMinAge > txNew.nTime - nMaxStakeSearchInterval)
1480 continue; // only count coins meeting min age requirement
1482 bool fKernelFound = false;
1483 for (unsigned int n=0; n<min(nSearchInterval,(int64)nMaxStakeSearchInterval) && !fKernelFound && !fShutdown; n++)
1485 // Search backward in time from the given txNew timestamp
1486 // Search nSearchInterval seconds back up to nMaxStakeSearchInterval
1487 uint256 hashProofOfStake = 0;
1488 COutPoint prevoutStake = COutPoint(pcoin.first->GetHash(), pcoin.second);
1489 if (CheckStakeKernelHash(nBits, block, txindex.pos.nTxPos - txindex.pos.nBlockPos, *pcoin.first, prevoutStake, txNew.nTime - n, hashProofOfStake))
1492 if (fDebug && GetBoolArg("-printcoinstake"))
1493 printf("CreateCoinStake : kernel found\n");
1494 vector<valtype> vSolutions;
1495 txnouttype whichType;
1496 CScript scriptPubKeyOut;
1497 scriptPubKeyKernel = pcoin.first->vout[pcoin.second].scriptPubKey;
1498 if (!Solver(scriptPubKeyKernel, whichType, vSolutions))
1500 if (fDebug && GetBoolArg("-printcoinstake"))
1501 printf("CreateCoinStake : failed to parse kernel\n");
1504 if (fDebug && GetBoolArg("-printcoinstake"))
1505 printf("CreateCoinStake : parsed kernel type=%d\n", whichType);
1506 if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH)
1508 if (fDebug && GetBoolArg("-printcoinstake"))
1509 printf("CreateCoinStake : no support for kernel type=%d\n", whichType);
1510 break; // only support pay to public key and pay to address
1512 if (whichType == TX_PUBKEYHASH) // pay to address type
1514 // convert to pay to public key type
1516 if (!keystore.GetKey(uint160(vSolutions[0]), key))
1518 if (fDebug && GetBoolArg("-printcoinstake"))
1519 printf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1520 break; // unable to find corresponding public key
1522 scriptPubKeyOut << key.GetPubKey() << OP_CHECKSIG;
1525 scriptPubKeyOut = scriptPubKeyKernel;
1528 txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1529 nCredit += pcoin.first->vout[pcoin.second].nValue;
1530 vwtxPrev.push_back(pcoin.first);
1531 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
1532 if (block.GetBlockTime() + nStakeSplitAge > txNew.nTime)
1533 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut)); //split stake
1534 if (fDebug && GetBoolArg("-printcoinstake"))
1535 printf("CreateCoinStake : added kernel type=%d\n", whichType);
1536 fKernelFound = true;
1540 if (fKernelFound || fShutdown)
1541 break; // if kernel is found stop searching
1543 if (nCredit == 0 || nCredit > nBalance - nReserveBalance)
1545 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1547 // Attempt to add more inputs
1548 // Only add coins of the same key/address as kernel
1549 if (txNew.vout.size() == 2 && ((pcoin.first->vout[pcoin.second].scriptPubKey == scriptPubKeyKernel || pcoin.first->vout[pcoin.second].scriptPubKey == txNew.vout[1].scriptPubKey))
1550 && pcoin.first->GetHash() != txNew.vin[0].prevout.hash)
1552 // Stop adding more inputs if already too many inputs
1553 if (txNew.vin.size() >= 100)
1555 // Stop adding more inputs if value is already pretty significant
1556 if (nCredit > nCombineThreshold)
1558 // Stop adding inputs if reached reserve limit
1559 if (nCredit + pcoin.first->vout[pcoin.second].nValue > nBalance - nReserveBalance)
1561 // Do not add additional significant input
1562 if (pcoin.first->vout[pcoin.second].nValue > nCombineThreshold)
1564 // Do not add input that is still too young
1565 if (pcoin.first->nTime + nStakeMaxAge > txNew.nTime)
1567 txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1568 nCredit += pcoin.first->vout[pcoin.second].nValue;
1569 vwtxPrev.push_back(pcoin.first);
1572 // Calculate coin age reward
1576 if (!txNew.GetCoinAge(txdb, nCoinAge))
1577 return error("CreateCoinStake : failed to calculate coin age");
1578 nCredit += GetProofOfStakeReward(nCoinAge, nBits, txNew.nTime);
1584 // Set output amount
1585 if (txNew.vout.size() == 3)
1587 txNew.vout[1].nValue = ((nCredit - nMinFee) / 2 / CENT) * CENT;
1588 txNew.vout[2].nValue = nCredit - nMinFee - txNew.vout[1].nValue;
1591 txNew.vout[1].nValue = nCredit - nMinFee;
1595 BOOST_FOREACH(const CWalletTx* pcoin, vwtxPrev)
1597 if (!SignSignature(*this, *pcoin, txNew, nIn++))
1598 return error("CreateCoinStake : failed to sign coinstake");
1602 unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION);
1603 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1604 return error("CreateCoinStake : exceeded coinstake size limit");
1606 // Check enough fee is paid
1607 if (nMinFee < txNew.GetMinFee() - MIN_TX_FEE)
1609 nMinFee = txNew.GetMinFee() - MIN_TX_FEE;
1610 continue; // try signing again
1614 if (fDebug && GetBoolArg("-printfee"))
1615 printf("CreateCoinStake : fee for coinstake %s\n", FormatMoney(nMinFee).c_str());
1620 // Successfully generated coinstake
1625 // Call after CreateTransaction unless you want to abort
1626 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
1629 LOCK2(cs_main, cs_wallet);
1630 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
1632 // This is only to keep the database open to defeat the auto-flush for the
1633 // duration of this scope. This is the only place where this optimization
1634 // maybe makes sense; please don't do it anywhere else.
1635 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
1637 // Take key pair from key pool so it won't be used again
1638 reservekey.KeepKey();
1640 // Add tx to wallet, because if it has change it's also ours,
1641 // otherwise just for transaction history.
1642 AddToWallet(wtxNew);
1644 // Mark old coins as spent
1645 set<CWalletTx*> setCoins;
1646 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
1648 CWalletTx &coin = mapWallet[txin.prevout.hash];
1649 coin.BindWallet(this);
1650 coin.MarkSpent(txin.prevout.n);
1652 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
1659 // Track how many getdata requests our transaction gets
1660 mapRequestCount[wtxNew.GetHash()] = 0;
1663 if (!wtxNew.AcceptToMemoryPool())
1665 // This must not fail. The transaction has already been signed and recorded.
1666 printf("CommitTransaction() : Error: Transaction not valid");
1669 wtxNew.RelayWalletTransaction();
1677 string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1679 CReserveKey reservekey(this);
1684 string strError = _("Error: Wallet locked, unable to create transaction ");
1685 printf("SendMoney() : %s", strError.c_str());
1688 if (fWalletUnlockMintOnly)
1690 string strError = _("Error: Wallet unlocked for block minting only, unable to create transaction.");
1691 printf("SendMoney() : %s", strError.c_str());
1694 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
1697 if (nValue + nFeeRequired > GetBalance())
1698 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());
1700 strError = _("Error: Transaction creation failed ");
1701 printf("SendMoney() : %s", strError.c_str());
1705 if (fAskFee && !uiInterface.ThreadSafeAskFee(nFeeRequired, _("Sending...")))
1708 if (!CommitTransaction(wtxNew, reservekey))
1709 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.");
1716 string CWallet::SendMoneyToDestination(const CTxDestination& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1720 return _("Invalid amount");
1721 if (nValue + nTransactionFee > GetBalance())
1722 return _("Insufficient funds");
1724 // Parse Bitcoin address
1725 CScript scriptPubKey;
1726 scriptPubKey.SetDestination(address);
1728 return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
1734 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
1738 fFirstRunRet = false;
1739 DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
1740 if (nLoadWalletRet == DB_NEED_REWRITE)
1742 if (CDB::Rewrite(strWalletFile, "\x04pool"))
1745 // Note: can't top-up keypool here, because wallet is locked.
1746 // User will be prompted to unlock wallet the next operation
1747 // the requires a new key.
1751 if (nLoadWalletRet != DB_LOAD_OK)
1752 return nLoadWalletRet;
1753 fFirstRunRet = !vchDefaultKey.IsValid();
1755 NewThread(ThreadFlushWalletDB, &strWalletFile);
1760 bool CWallet::SetAddressBookName(const CTxDestination& address, const string& strName)
1762 std::map<CTxDestination, std::string>::iterator mi = mapAddressBook.find(address);
1763 mapAddressBook[address] = strName;
1764 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address), (mi == mapAddressBook.end()) ? CT_NEW : CT_UPDATED);
1767 return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName);
1770 bool CWallet::DelAddressBookName(const CTxDestination& address)
1772 mapAddressBook.erase(address);
1773 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address), CT_DELETED);
1776 return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString());
1780 void CWallet::PrintWallet(const CBlock& block)
1784 if (block.IsProofOfWork() && mapWallet.count(block.vtx[0].GetHash()))
1786 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
1787 printf(" mine: %d %d %"PRI64d"", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
1789 if (block.IsProofOfStake() && mapWallet.count(block.vtx[1].GetHash()))
1791 CWalletTx& wtx = mapWallet[block.vtx[1].GetHash()];
1792 printf(" stake: %d %d %"PRI64d"", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
1799 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
1803 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
1804 if (mi != mapWallet.end())
1813 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
1817 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
1820 vchDefaultKey = vchPubKey;
1824 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
1826 if (!pwallet->fFileBacked)
1828 strWalletFileOut = pwallet->strWalletFile;
1833 // Mark old keypool keys as used,
1834 // and generate all new keys
1836 bool CWallet::NewKeyPool()
1840 CWalletDB walletdb(strWalletFile);
1841 BOOST_FOREACH(int64 nIndex, setKeyPool)
1842 walletdb.ErasePool(nIndex);
1848 int64 nKeys = max(GetArg("-keypool", 100), (int64)0);
1849 for (int i = 0; i < nKeys; i++)
1852 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
1853 setKeyPool.insert(nIndex);
1855 printf("CWallet::NewKeyPool wrote %"PRI64d" new keys\n", nKeys);
1860 bool CWallet::TopUpKeyPool()
1868 CWalletDB walletdb(strWalletFile);
1871 unsigned int nTargetSize = max(GetArg("-keypool", 100), 0LL);
1872 while (setKeyPool.size() < (nTargetSize + 1))
1875 if (!setKeyPool.empty())
1876 nEnd = *(--setKeyPool.end()) + 1;
1877 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
1878 throw runtime_error("TopUpKeyPool() : writing generated key failed");
1879 setKeyPool.insert(nEnd);
1880 printf("keypool added key %"PRI64d", size=%"PRIszu"\n", nEnd, setKeyPool.size());
1886 void CWallet::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool)
1889 keypool.vchPubKey = CPubKey();
1896 // Get the oldest key
1897 if(setKeyPool.empty())
1900 CWalletDB walletdb(strWalletFile);
1902 nIndex = *(setKeyPool.begin());
1903 setKeyPool.erase(setKeyPool.begin());
1904 if (!walletdb.ReadPool(nIndex, keypool))
1905 throw runtime_error("ReserveKeyFromKeyPool() : read failed");
1906 if (!HaveKey(keypool.vchPubKey.GetID()))
1907 throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
1908 assert(keypool.vchPubKey.IsValid());
1909 if (fDebug && GetBoolArg("-printkeypool"))
1910 printf("keypool reserve %"PRI64d"\n", nIndex);
1914 int64 CWallet::AddReserveKey(const CKeyPool& keypool)
1917 LOCK2(cs_main, cs_wallet);
1918 CWalletDB walletdb(strWalletFile);
1920 int64 nIndex = 1 + *(--setKeyPool.end());
1921 if (!walletdb.WritePool(nIndex, keypool))
1922 throw runtime_error("AddReserveKey() : writing added key failed");
1923 setKeyPool.insert(nIndex);
1929 void CWallet::KeepKey(int64 nIndex)
1931 // Remove from key pool
1934 CWalletDB walletdb(strWalletFile);
1935 walletdb.ErasePool(nIndex);
1938 printf("keypool keep %"PRI64d"\n", nIndex);
1941 void CWallet::ReturnKey(int64 nIndex)
1943 // Return to key pool
1946 setKeyPool.insert(nIndex);
1949 printf("keypool return %"PRI64d"\n", nIndex);
1952 bool CWallet::GetKeyFromPool(CPubKey& result, bool fAllowReuse)
1958 ReserveKeyFromKeyPool(nIndex, keypool);
1961 if (fAllowReuse && vchDefaultKey.IsValid())
1963 result = vchDefaultKey;
1966 if (IsLocked()) return false;
1967 result = GenerateNewKey();
1971 result = keypool.vchPubKey;
1976 int64 CWallet::GetOldestKeyPoolTime()
1980 ReserveKeyFromKeyPool(nIndex, keypool);
1984 return keypool.nTime;
1987 std::map<CTxDestination, int64> CWallet::GetAddressBalances()
1989 map<CTxDestination, int64> balances;
1993 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
1995 CWalletTx *pcoin = &walletEntry.second;
1997 if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
2000 if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0)
2003 int nDepth = pcoin->GetDepthInMainChain();
2004 if (nDepth < (pcoin->IsFromMe() ? 0 : 1))
2007 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2009 CTxDestination addr;
2010 if (!IsMine(pcoin->vout[i]))
2012 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr))
2015 int64 n = pcoin->IsSpent(i) ? 0 : pcoin->vout[i].nValue;
2017 if (!balances.count(addr))
2019 balances[addr] += n;
2027 set< set<CTxDestination> > CWallet::GetAddressGroupings()
2029 set< set<CTxDestination> > groupings;
2030 set<CTxDestination> grouping;
2032 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2034 CWalletTx *pcoin = &walletEntry.second;
2036 if (pcoin->vin.size() > 0 && IsMine(pcoin->vin[0]))
2038 // group all input addresses with each other
2039 BOOST_FOREACH(CTxIn txin, pcoin->vin)
2041 CTxDestination address;
2042 if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
2044 grouping.insert(address);
2047 // group change with input addresses
2048 BOOST_FOREACH(CTxOut txout, pcoin->vout)
2049 if (IsChange(txout))
2051 CWalletTx tx = mapWallet[pcoin->vin[0].prevout.hash];
2052 CTxDestination txoutAddr;
2053 if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
2055 grouping.insert(txoutAddr);
2057 groupings.insert(grouping);
2061 // group lone addrs by themselves
2062 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2063 if (IsMine(pcoin->vout[i]))
2065 CTxDestination address;
2066 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address))
2068 grouping.insert(address);
2069 groupings.insert(grouping);
2074 set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
2075 map< CTxDestination, set<CTxDestination>* > setmap; // map addresses to the unique group containing it
2076 BOOST_FOREACH(set<CTxDestination> grouping, groupings)
2078 // make a set of all the groups hit by this new group
2079 set< set<CTxDestination>* > hits;
2080 map< CTxDestination, set<CTxDestination>* >::iterator it;
2081 BOOST_FOREACH(CTxDestination address, grouping)
2082 if ((it = setmap.find(address)) != setmap.end())
2083 hits.insert((*it).second);
2085 // merge all hit groups into a new single group and delete old groups
2086 set<CTxDestination>* merged = new set<CTxDestination>(grouping);
2087 BOOST_FOREACH(set<CTxDestination>* hit, hits)
2089 merged->insert(hit->begin(), hit->end());
2090 uniqueGroupings.erase(hit);
2093 uniqueGroupings.insert(merged);
2096 BOOST_FOREACH(CTxDestination element, *merged)
2097 setmap[element] = merged;
2100 set< set<CTxDestination> > ret;
2101 BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings)
2103 ret.insert(*uniqueGrouping);
2104 delete uniqueGrouping;
2110 // ppcoin: check 'spent' consistency between wallet and txindex
2111 // ppcoin: fix wallet spent state according to txindex
2112 void CWallet::FixSpentCoins(int& nMismatchFound, int64& nBalanceInQuestion, bool fCheckOnly)
2115 nBalanceInQuestion = 0;
2118 vector<CWalletTx*> vCoins;
2119 vCoins.reserve(mapWallet.size());
2120 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2121 vCoins.push_back(&(*it).second);
2124 BOOST_FOREACH(CWalletTx* pcoin, vCoins)
2126 // Find the corresponding transaction index
2128 if (!txdb.ReadTxIndex(pcoin->GetHash(), txindex))
2130 for (unsigned int n=0; n < pcoin->vout.size(); n++)
2132 if (IsMine(pcoin->vout[n]) && pcoin->IsSpent(n) && (txindex.vSpent.size() <= n || txindex.vSpent[n].IsNull()))
2134 printf("FixSpentCoins found lost coin %sppc %s[%d], %s\n",
2135 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2137 nBalanceInQuestion += pcoin->vout[n].nValue;
2140 pcoin->MarkUnspent(n);
2141 pcoin->WriteToDisk();
2144 else if (IsMine(pcoin->vout[n]) && !pcoin->IsSpent(n) && (txindex.vSpent.size() > n && !txindex.vSpent[n].IsNull()))
2146 printf("FixSpentCoins found spent coin %sppc %s[%d], %s\n",
2147 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2149 nBalanceInQuestion += pcoin->vout[n].nValue;
2152 pcoin->MarkSpent(n);
2153 pcoin->WriteToDisk();
2160 // ppcoin: disable transaction (only for coinstake)
2161 void CWallet::DisableTransaction(const CTransaction &tx)
2163 if (!tx.IsCoinStake() || !IsFromMe(tx))
2164 return; // only disconnecting coinstake requires marking input unspent
2167 BOOST_FOREACH(const CTxIn& txin, tx.vin)
2169 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
2170 if (mi != mapWallet.end())
2172 CWalletTx& prev = (*mi).second;
2173 if (txin.prevout.n < prev.vout.size() && IsMine(prev.vout[txin.prevout.n]))
2175 prev.MarkUnspent(txin.prevout.n);
2182 CPubKey CReserveKey::GetReservedKey()
2187 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
2189 vchPubKey = keypool.vchPubKey;
2192 printf("CReserveKey::GetReservedKey(): Warning: Using default key instead of a new key, top up your keypool!");
2193 vchPubKey = pwallet->vchDefaultKey;
2196 assert(vchPubKey.IsValid());
2200 void CReserveKey::KeepKey()
2203 pwallet->KeepKey(nIndex);
2205 vchPubKey = CPubKey();
2208 void CReserveKey::ReturnKey()
2211 pwallet->ReturnKey(nIndex);
2213 vchPubKey = CPubKey();
2216 void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
2220 CWalletDB walletdb(strWalletFile);
2222 LOCK2(cs_main, cs_wallet);
2223 BOOST_FOREACH(const int64& id, setKeyPool)
2226 if (!walletdb.ReadPool(id, keypool))
2227 throw runtime_error("GetAllReserveKeyHashes() : read failed");
2228 assert(keypool.vchPubKey.IsValid());
2229 CKeyID keyID = keypool.vchPubKey.GetID();
2230 if (!HaveKey(keyID))
2231 throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
2232 setAddress.insert(keyID);
2236 void CWallet::UpdatedTransaction(const uint256 &hashTx)
2240 // Only notify UI if this transaction is in this wallet
2241 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
2242 if (mi != mapWallet.end())
2243 NotifyTransactionChanged(this, hashTx, CT_UPDATED);
2247 void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64> &mapKeyBirth) const {
2248 mapKeyBirth.clear();
2250 // get birth times for keys with metadata
2251 for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++)
2252 if (it->second.nCreateTime)
2253 mapKeyBirth[it->first] = it->second.nCreateTime;
2255 // map in which we'll infer heights of other keys
2256 CBlockIndex *pindexMax = FindBlockByHeight(std::max(0, nBestHeight - 144)); // the tip can be reorganised; use a 144-block safety margin
2257 std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
2258 std::set<CKeyID> setKeys;
2260 BOOST_FOREACH(const CKeyID &keyid, setKeys) {
2261 if (mapKeyBirth.count(keyid) == 0)
2262 mapKeyFirstBlock[keyid] = pindexMax;
2266 // if there are no such keys, we're done
2267 if (mapKeyFirstBlock.empty())
2270 // find first block that affects those keys, if there are any left
2271 std::vector<CKeyID> vAffected;
2272 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
2273 // iterate over all wallet transactions...
2274 const CWalletTx &wtx = (*it).second;
2275 std::map<uint256, CBlockIndex*>::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
2276 if (blit != mapBlockIndex.end() && blit->second->IsInMainChain()) {
2277 // ... which are already in a block
2278 int nHeight = blit->second->nHeight;
2279 BOOST_FOREACH(const CTxOut &txout, wtx.vout) {
2280 // iterate over all their outputs
2281 ::ExtractAffectedKeys(*this, txout.scriptPubKey, vAffected);
2282 BOOST_FOREACH(const CKeyID &keyid, vAffected) {
2283 // ... and all their affected keys
2284 std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
2285 if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
2286 rit->second = blit->second;
2293 // Extract block timestamps for those keys
2294 for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
2295 mapKeyBirth[it->first] = it->second->nTime - 7200; // block times can be 2h off