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.
7 #include "txdb-leveldb.h"
9 #include "coincontrol.h"
14 #include <openssl/bio.h>
20 extern int64_t nReserveBalance;
22 //////////////////////////////////////////////////////////////////////////////
27 struct CompareValueOnly
29 bool operator()(const pair<int64_t, pair<const CWalletTx*, unsigned int> >& t1,
30 const pair<int64_t, pair<const CWalletTx*, unsigned int> >& t2) const
32 return t1.first < t2.first;
36 const CWalletTx* CWallet::GetWalletTx(const uint256& hash) const
39 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(hash);
40 if (it == mapWallet.end())
45 CPubKey CWallet::GenerateNewKey()
47 bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
51 key.MakeNewKey(fCompressed);
53 // Compressed public keys were introduced in version 0.6.0
55 SetMinVersion(FEATURE_COMPRPUBKEY);
57 CPubKey pubkey = key.GetPubKey();
59 // Create new metadata
60 int64_t nCreationTime = GetTime();
61 mapKeyMetadata[CBitcoinAddress(pubkey.GetID())] = CKeyMetadata(nCreationTime);
62 if (!nTimeFirstKey || nCreationTime < nTimeFirstKey)
63 nTimeFirstKey = nCreationTime;
66 throw std::runtime_error("CWallet::GenerateNewKey() : AddKey failed");
67 return key.GetPubKey();
70 CMalleableKeyView CWallet::GenerateNewMalleableKey()
74 // Compressed public keys were introduced in version 0.6.0
75 SetMinVersion(FEATURE_MALLKEY);
79 const CMalleableKeyView &keyView(mKey);
81 // Create new metadata
82 int64_t nCreationTime = GetTime();
83 mapKeyMetadata[CBitcoinAddress(keyView.GetMalleablePubKey())] = CKeyMetadata(nCreationTime);
84 if (!nTimeFirstKey || nCreationTime < nTimeFirstKey)
85 nTimeFirstKey = nCreationTime;
88 throw std::runtime_error("CWallet::GenerateNewMalleableKey() : AddKey failed");
89 return CMalleableKeyView(mKey);
92 bool CWallet::AddKey(const CKey& key)
94 CPubKey pubkey = key.GetPubKey();
95 if (!CCryptoKeyStore::AddKey(key))
100 return CWalletDB(strWalletFile).WriteKey(pubkey, key.GetPrivKey(), mapKeyMetadata[CBitcoinAddress(pubkey.GetID())]);
104 bool CWallet::AddKey(const CMalleableKey& mKey)
106 CMalleableKeyView keyView = CMalleableKeyView(mKey);
107 CSecret vchSecretH = mKey.GetSecretH();
108 if (!CCryptoKeyStore::AddMalleableKey(keyView, vchSecretH))
113 return CWalletDB(strWalletFile).WriteMalleableKey(keyView, vchSecretH, mapKeyMetadata[CBitcoinAddress(keyView.GetMalleablePubKey())]);
117 bool CWallet::AddCryptedMalleableKey(const CMalleableKeyView& keyView, const std::vector<unsigned char> &vchCryptedSecretH)
119 if (!CCryptoKeyStore::AddCryptedMalleableKey(keyView, vchCryptedSecretH))
127 CBitcoinAddress addr(keyView.GetMalleablePubKey());
128 if (pwalletdbEncryption)
129 return pwalletdbEncryption->WriteCryptedMalleableKey(keyView, vchCryptedSecretH, mapKeyMetadata[addr]);
131 return CWalletDB(strWalletFile).WriteCryptedMalleableKey(keyView, vchCryptedSecretH, mapKeyMetadata[addr]);
137 bool CWallet::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) { SetMinVersion(FEATURE_WALLETCRYPT); return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret); }
139 bool CWallet::AddCryptedKey(const CPubKey &vchPubKey, const vector<unsigned char> &vchCryptedSecret)
141 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
144 // check if we need to remove from watch-only
146 script.SetDestination(vchPubKey.GetID());
147 if (HaveWatchOnly(script))
148 RemoveWatchOnly(script);
154 CBitcoinAddress addr(vchPubKey.GetID());
155 if (pwalletdbEncryption)
156 return pwalletdbEncryption->WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[addr]);
158 return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[addr]);
163 bool CWallet::LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &meta)
165 if (meta.nCreateTime && (!nTimeFirstKey || meta.nCreateTime < nTimeFirstKey))
166 nTimeFirstKey = meta.nCreateTime;
168 mapKeyMetadata[CBitcoinAddress(pubkey.GetID())] = meta;
172 bool CWallet::LoadKeyMetadata(const CMalleableKeyView &keyView, const CKeyMetadata &metadata)
174 if (metadata.nCreateTime && (!nTimeFirstKey || metadata.nCreateTime < nTimeFirstKey))
175 nTimeFirstKey = metadata.nCreateTime;
177 mapKeyMetadata[CBitcoinAddress(keyView.GetMalleablePubKey())] = metadata;
181 bool CWallet::LoadKey(const CMalleableKeyView &keyView, const CSecret &vchSecretH) { return CCryptoKeyStore::AddMalleableKey(keyView, vchSecretH); }
183 bool CWallet::LoadCryptedKey(const CMalleableKeyView &keyView, const std::vector<unsigned char> &vchCryptedSecretH) { return CCryptoKeyStore::AddCryptedMalleableKey(keyView, vchCryptedSecretH); }
185 bool CWallet::LoadMinVersion(int nVersion) { nWalletVersion = nVersion; nWalletMaxVersion = std::max(nWalletMaxVersion, nVersion); return true; }
187 bool CWallet::AddCScript(const CScript& redeemScript)
189 if (!CCryptoKeyStore::AddCScript(redeemScript))
193 return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript);
196 bool CWallet::LoadCScript(const CScript& redeemScript)
198 /* A sanity check was added in commit 5ed0a2b to avoid adding redeemScripts
199 * that never can be redeemed. However, old wallets may still contain
200 * these. Do not add them to the wallet and warn. */
201 if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
203 std::string strAddr = CBitcoinAddress(redeemScript.GetID()).ToString();
204 printf("LoadCScript() : Warning: This wallet contains a redeemScript of size %" PRIszu " which exceeds maximum size %i thus can never be redeemed. Do not use address %s.\n",
205 redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr.c_str());
209 return CCryptoKeyStore::AddCScript(redeemScript);
213 bool CWallet::AddWatchOnly(const CScript &dest)
215 if (!CCryptoKeyStore::AddWatchOnly(dest))
217 nTimeFirstKey = 1; // No birthday information for watch-only keys.
218 NotifyWatchonlyChanged(true);
221 return CWalletDB(strWalletFile).WriteWatchOnly(dest);
224 bool CWallet::RemoveWatchOnly(const CScript &dest)
227 if (!CCryptoKeyStore::RemoveWatchOnly(dest))
229 if (!HaveWatchOnly())
230 NotifyWatchonlyChanged(false);
232 if (!CWalletDB(strWalletFile).EraseWatchOnly(dest))
238 bool CWallet::LoadWatchOnly(const CScript &dest)
240 return CCryptoKeyStore::AddWatchOnly(dest);
243 // ppcoin: optional setting to unlock wallet for block minting only;
244 // serves to disable the trivial sendmoney when OS account compromised
245 bool fWalletUnlockMintOnly = false;
247 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
253 CKeyingMaterial vMasterKey;
257 for (const MasterKeyMap::value_type& pMasterKey : mapMasterKeys)
259 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
261 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
263 if (CCryptoKeyStore::Unlock(vMasterKey))
270 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
272 bool fWasLocked = IsLocked();
279 CKeyingMaterial vMasterKey;
280 for (MasterKeyMap::value_type& pMasterKey : mapMasterKeys)
282 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
284 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
286 if (CCryptoKeyStore::Unlock(vMasterKey))
288 int64_t nStartTime = GetTimeMillis();
289 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
290 double nFirstMultiplier = 1e2 / (GetTimeMillis() - nStartTime);
291 pMasterKey.second.nDeriveIterations = (uint32_t)(pMasterKey.second.nDeriveIterations *nFirstMultiplier);
293 nStartTime = GetTimeMillis();
294 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
295 double nSecondMultiplier = 1e2 / (GetTimeMillis() - nStartTime);
296 pMasterKey.second.nDeriveIterations = (uint32_t)((pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * nSecondMultiplier) / 2);
298 if (pMasterKey.second.nDeriveIterations < 25000)
299 pMasterKey.second.nDeriveIterations = 25000;
301 printf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
303 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
305 if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
307 CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
318 void CWallet::SetBestChain(const CBlockLocator& loc)
320 CWalletDB walletdb(strWalletFile);
321 walletdb.WriteBestBlock(loc);
324 // This class implements an addrIncoming entry that causes pre-0.4
325 // clients to crash on startup if reading a private-key-encrypted wallet.
326 class CCorruptAddress
331 if (nType & SER_DISK)
336 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
338 if (nWalletVersion >= nVersion)
341 // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
342 if (fExplicit && nVersion > nWalletMaxVersion)
343 nVersion = FEATURE_LATEST;
345 nWalletVersion = nVersion;
347 if (nVersion > nWalletMaxVersion)
348 nWalletMaxVersion = nVersion;
352 CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile);
353 if (nWalletVersion > 40000)
354 pwalletdb->WriteMinVersion(nWalletVersion);
362 bool CWallet::SetMaxVersion(int nVersion)
364 // cannot downgrade below current version
365 if (nWalletVersion > nVersion)
368 nWalletMaxVersion = nVersion;
373 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
378 CKeyingMaterial vMasterKey;
379 RandAddSeedPerfmon();
381 vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
382 RAND_bytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
384 CMasterKey kMasterKey;
386 RandAddSeedPerfmon();
387 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
388 RAND_bytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
391 int64_t nStartTime = GetTimeMillis();
392 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
393 int64_t nDivider = GetTimeMillis() - nStartTime;
394 kMasterKey.nDeriveIterations = (uint32_t)(25e5 / (double)(nDivider));
396 nStartTime = GetTimeMillis();
397 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
398 double nMultiplier = 1e2 / (GetTimeMillis() - nStartTime);
399 kMasterKey.nDeriveIterations = (uint32_t)((kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * nMultiplier) / 2);
401 if (kMasterKey.nDeriveIterations < 25000)
402 kMasterKey.nDeriveIterations = 25000;
404 printf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
406 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
408 if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
413 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
416 pwalletdbEncryption = new CWalletDB(strWalletFile);
417 if (!pwalletdbEncryption->TxnBegin())
419 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
422 if (!EncryptKeys(vMasterKey))
425 pwalletdbEncryption->TxnAbort();
426 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.
429 // Encryption was introduced in version 0.4.0
430 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
434 if (!pwalletdbEncryption->TxnCommit())
435 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.
437 delete pwalletdbEncryption;
438 pwalletdbEncryption = NULL;
442 Unlock(strWalletPassphrase);
446 // Need to completely rewrite the wallet file; if we don't, bdb might keep
447 // bits of the unencrypted private key in slack space in the database file.
448 CDB::Rewrite(strWalletFile);
451 NotifyStatusChanged(this);
456 bool CWallet::DecryptWallet(const SecureString& strWalletPassphrase)
462 CKeyingMaterial vMasterKey;
466 for (const MasterKeyMap::value_type& pMasterKey : mapMasterKeys)
468 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
470 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
472 if (!CCryptoKeyStore::Unlock(vMasterKey))
478 pwalletdbDecryption = new CWalletDB(strWalletFile);
479 if (!pwalletdbDecryption->TxnBegin())
483 if (!DecryptKeys(vMasterKey))
486 pwalletdbDecryption->TxnAbort();
487 exit(1); //We now probably have half of our keys decrypted in memory, and half not...die and let the user reload their encrypted wallet.
492 // Overwrite crypted keys
493 KeyMap::const_iterator mi = mapKeys.begin();
494 while (mi != mapKeys.end())
497 key.SetSecret((*mi).second.first, (*mi).second.second);
498 pwalletdbDecryption->EraseCryptedKey(key.GetPubKey());
499 pwalletdbDecryption->WriteKey(key.GetPubKey(), key.GetPrivKey(), mapKeyMetadata[CBitcoinAddress(mi->first)]);
503 MalleableKeyMap::const_iterator mi2 = mapMalleableKeys.begin();
504 while (mi2 != mapMalleableKeys.end())
506 const CSecret &vchSecretH = mi2->second;
507 const CMalleableKeyView &keyView = mi2->first;
508 pwalletdbDecryption->EraseCryptedMalleableKey(keyView);
509 pwalletdbDecryption->WriteMalleableKey(keyView, vchSecretH, mapKeyMetadata[CBitcoinAddress(keyView.GetMalleablePubKey())]);
514 MasterKeyMap::const_iterator mk = mapMasterKeys.begin();
515 while (mk != mapMasterKeys.end())
517 pwalletdbDecryption->EraseMasterKey((*mk).first);
521 if (!pwalletdbDecryption->TxnCommit())
522 exit(1); //We now have keys decrypted in memory, but no on disk...die to avoid confusion and let the user reload their encrypted wallet.
524 delete pwalletdbDecryption;
525 pwalletdbDecryption = NULL;
528 // Need to completely rewrite the wallet file; if we don't, bdb might keep
529 // encrypted private keys in the database file which can be a reason of consistency issues.
530 CDB::Rewrite(strWalletFile);
532 NotifyStatusChanged(this);
537 int64_t CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
539 int64_t nRet = nOrderPosNext++;
541 pwalletdb->WriteOrderPosNext(nOrderPosNext);
543 CWalletDB(strWalletFile).WriteOrderPosNext(nOrderPosNext);
548 CWallet::TxItems CWallet::OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount)
550 CWalletDB walletdb(strWalletFile);
552 // First: get all CWalletTx and CAccountingEntry into a sorted-by-order multimap.
555 // Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry
556 // would make this much faster for applications that do this a lot.
557 for (auto & it : mapWallet)
559 CWalletTx* wtx = &(it.second);
560 txOrdered.insert(make_pair(wtx->nOrderPos, TxPair(wtx, (CAccountingEntry*)nullptr)));
563 walletdb.ListAccountCreditDebit(strAccount, acentries);
564 for (CAccountingEntry& entry : acentries)
566 txOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)nullptr, &entry)));
572 void CWallet::WalletUpdateSpent(const CTransaction &tx, bool fBlock)
574 // Anytime a signature is successfully verified, it's proof the outpoint is spent.
575 // Update the wallet spent flag if it doesn't know due to wallet.dat being
576 // restored from backup or the user making copies of wallet.dat.
579 for (const CTxIn& txin : tx.vin)
581 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
582 if (mi != mapWallet.end())
584 CWalletTx& wtx = (*mi).second;
585 if (txin.prevout.n >= wtx.vout.size())
586 printf("WalletUpdateSpent: bad wtx %s\n", wtx.GetHash().ToString().c_str());
587 else if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n]))
589 printf("WalletUpdateSpent found spent coin %snvc %s\n", FormatMoney(wtx.GetCredit(MINE_ALL)).c_str(), wtx.GetHash().ToString().c_str());
590 wtx.MarkSpent(txin.prevout.n);
592 NotifyTransactionChanged(this, txin.prevout.hash, CT_UPDATED);
593 vMintingWalletUpdated.push_back(txin.prevout.hash);
600 uint256 hash = tx.GetHash();
601 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hash);
602 CWalletTx& wtx = (*mi).second;
604 for (const CTxOut& txout : tx.vout)
608 wtx.MarkUnspent(&txout - &tx.vout[0]);
610 NotifyTransactionChanged(this, hash, CT_UPDATED);
611 vMintingWalletUpdated.push_back(hash);
619 void CWallet::MarkDirty()
623 for (auto& item : mapWallet)
624 item.second.MarkDirty();
628 bool CWallet::AddToWallet(const CWalletTx& wtxIn)
630 uint256 hash = wtxIn.GetHash();
633 // Inserts only if not already there, returns tx inserted or tx found
634 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
635 CWalletTx& wtx = (*ret.first).second;
636 wtx.BindWallet(this);
637 bool fInsertedNew = ret.second;
640 wtx.nTimeReceived = GetAdjustedTime();
641 wtx.nOrderPos = IncOrderPosNext();
643 wtx.nTimeSmart = wtx.nTimeReceived;
644 if (wtxIn.hashBlock != 0)
646 if (mapBlockIndex.count(wtxIn.hashBlock))
648 unsigned int latestNow = wtx.nTimeReceived;
649 unsigned int latestEntry = 0;
651 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
652 int64_t latestTolerated = latestNow + 300;
653 std::list<CAccountingEntry> acentries;
654 TxItems txOrdered = OrderedTxItems(acentries);
655 for (TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
657 CWalletTx *const pwtx = (*it).second.first;
660 CAccountingEntry *const pacentry = (*it).second.second;
664 nSmartTime = pwtx->nTimeSmart;
666 nSmartTime = pwtx->nTimeReceived;
669 nSmartTime = pacentry->nTime;
670 if (nSmartTime <= latestTolerated)
672 latestEntry = nSmartTime;
673 if (nSmartTime > latestNow)
674 latestNow = nSmartTime;
680 unsigned int& blocktime = mapBlockIndex[wtxIn.hashBlock]->nTime;
681 wtx.nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
684 printf("AddToWallet() : found %s in block %s not in index\n",
685 wtxIn.GetHash().ToString().substr(0,10).c_str(),
686 wtxIn.hashBlock.ToString().c_str());
690 bool fUpdated = false;
694 if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
696 wtx.hashBlock = wtxIn.hashBlock;
699 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
701 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
702 wtx.nIndex = wtxIn.nIndex;
705 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
707 wtx.fFromMe = wtxIn.fFromMe;
710 fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);
714 printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
717 if (fInsertedNew || fUpdated)
718 if (!wtx.WriteToDisk())
721 // If default receiving address gets used, replace it with a new one
722 CScript scriptDefaultKey;
723 scriptDefaultKey.SetDestination(vchDefaultKey.GetID());
724 for (const CTxOut& txout : wtx.vout)
726 if (txout.scriptPubKey == scriptDefaultKey)
728 CPubKey newDefaultKey;
729 if (GetKeyFromPool(newDefaultKey, false))
731 SetDefaultKey(newDefaultKey);
732 SetAddressBookName(vchDefaultKey.GetID(), "");
737 // since AddToWallet is called directly for self-originating transactions, check for consumption of own coins
738 WalletUpdateSpent(wtx, (wtxIn.hashBlock != 0));
740 // Notify UI of new or updated transaction
741 NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
742 vMintingWalletUpdated.push_back(hash);
743 // notify an external script when a wallet transaction comes in or is updated
744 std::string strCmd = GetArg("-walletnotify", "");
746 if ( !strCmd.empty())
748 boost::thread t(runCommand, regex_replace(strCmd, static_cast<std::regex>("%s"), wtxIn.GetHash().GetHex()));
754 // Add a transaction to the wallet, or update it.
755 // pblock is optional, but should be provided if the transaction is known to be in a block.
756 // If fUpdate is true, existing transactions will be updated.
757 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate)
759 uint256 hash = tx.GetHash();
762 bool fExisted = mapWallet.count(hash) != 0;
763 if (fExisted && !fUpdate) return false;
764 if (fExisted || IsMine(tx) || IsFromMe(tx))
766 CWalletTx wtx(this,tx);
767 // Get merkle branch if transaction was found in a block
769 wtx.SetMerkleBranch(pblock);
770 return AddToWallet(wtx);
773 WalletUpdateSpent(tx);
778 bool CWallet::EraseFromWallet(uint256 hash)
784 if (mapWallet.erase(hash))
785 CWalletDB(strWalletFile).EraseTx(hash);
791 isminetype CWallet::IsMine(const CTxIn &txin) const
795 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
796 if (mi != mapWallet.end())
798 const CWalletTx& prev = (*mi).second;
799 if (txin.prevout.n < prev.vout.size())
800 return IsMine(prev.vout[txin.prevout.n]);
806 // marks certain txout's as spent
807 // returns true if any update took place
808 bool CWalletTx::UpdateSpent(const std::vector<char>& vfNewSpent)
810 bool fReturn = false;
811 for (unsigned int i = 0; i < vfNewSpent.size(); i++)
813 if (i == vfSpent.size())
816 if (vfNewSpent[i] && !vfSpent[i])
820 fAvailableCreditCached = fAvailableWatchCreditCached = false;
826 // make sure balances are recalculated
827 void CWalletTx::MarkDirty()
829 fCreditCached = false;
830 fAvailableCreditCached = fAvailableWatchCreditCached = false;
831 fDebitCached = fWatchDebitCached = false;
832 fChangeCached = false;
835 void CWalletTx::BindWallet(CWallet *pwalletIn)
841 void CWalletTx::MarkSpent(unsigned int nOut)
843 if (nOut >= vout.size())
844 throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
845 vfSpent.resize(vout.size());
848 vfSpent[nOut] = true;
849 fAvailableCreditCached = fAvailableWatchCreditCached = false;
853 void CWalletTx::MarkUnspent(unsigned int nOut)
855 if (nOut >= vout.size())
856 throw std::runtime_error("CWalletTx::MarkUnspent() : nOut out of range");
857 vfSpent.resize(vout.size());
860 vfSpent[nOut] = false;
861 fAvailableCreditCached = fAvailableWatchCreditCached = false;
865 bool CWalletTx::IsSpent(unsigned int nOut) const
867 if (nOut >= vout.size())
868 throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
869 if (nOut >= vfSpent.size())
871 return (!!vfSpent[nOut]);
874 int64_t CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
878 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
879 if (mi != mapWallet.end())
881 const CWalletTx& prev = (*mi).second;
882 if (txin.prevout.n < prev.vout.size())
883 if (IsMine(prev.vout[txin.prevout.n]) & filter)
884 return prev.vout[txin.prevout.n].nValue;
890 isminetype CWallet::IsMine(const CTxOut& txout) const
892 return ::IsMine(*this, txout.scriptPubKey);
895 int64_t CWallet::GetCredit(const CTxOut& txout, const isminefilter& filter) const
897 if (!MoneyRange(txout.nValue))
898 throw std::runtime_error("CWallet::GetCredit() : value out of range");
899 return (IsMine(txout) & filter ? txout.nValue : 0);
902 bool CWallet::IsChange(const CTxOut& txout) const
904 // TODO: fix handling of 'change' outputs. The assumption is that any
905 // payment to a script that is ours, but isn't in the address book
906 // is change. That assumption is likely to break when we implement multisignature
907 // wallets that return change back into a multi-signature-protected address;
908 // a better way of identifying which outputs are 'the send' and which are
909 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
910 // which output, if any, was change).
911 if (::IsMine(*this, txout.scriptPubKey))
913 CTxDestination address;
914 if (!ExtractDestination(txout.scriptPubKey, address))
918 if (!mapAddressBook.count(address))
924 int64_t CWallet::GetChange(const CTxOut& txout) const
926 if (!MoneyRange(txout.nValue))
927 throw std::runtime_error("CWallet::GetChange() : value out of range");
928 return (IsChange(txout) ? txout.nValue : 0);
931 bool CWallet::IsMine(const CTransaction& tx) const
933 for (const CTxOut& txout : tx.vout)
934 if (IsMine(txout) && txout.nValue >= nMinimumInputValue)
939 bool CWallet::IsFromMe(const CTransaction& tx) const
941 return (GetDebit(tx, MINE_ALL) > 0);
944 int64_t CWallet::GetDebit(const CTransaction& tx, const isminefilter& filter) const
947 for (const CTxIn& txin : tx.vin)
949 nDebit += GetDebit(txin, filter);
950 if (!MoneyRange(nDebit))
951 throw std::runtime_error("CWallet::GetDebit() : value out of range");
956 int64_t CWallet::GetCredit(const CTransaction& tx, const isminefilter& filter) const
959 for (const CTxOut& txout : tx.vout)
961 nCredit += GetCredit(txout, filter);
962 if (!MoneyRange(nCredit))
963 throw std::runtime_error("CWallet::GetCredit() : value out of range");
968 int64_t CWallet::GetChange(const CTransaction& tx) const
971 for (const CTxOut& txout : tx.vout)
973 nChange += GetChange(txout);
974 if (!MoneyRange(nChange))
975 throw std::runtime_error("CWallet::GetChange() : value out of range");
980 int64_t CWalletTx::GetTxTime() const
985 int CWalletTx::GetRequestCount() const
987 // Returns -1 if it wasn't being tracked
990 LOCK(pwallet->cs_wallet);
991 if (IsCoinBase() || IsCoinStake())
996 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
997 if (mi != pwallet->mapRequestCount.end())
998 nRequests = (*mi).second;
1003 // Did anyone request this transaction?
1004 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
1005 if (mi != pwallet->mapRequestCount.end())
1007 nRequests = (*mi).second;
1009 // How about the block it's in?
1010 if (nRequests == 0 && hashBlock != 0)
1012 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
1013 if (mi != pwallet->mapRequestCount.end())
1014 nRequests = (*mi).second;
1016 nRequests = 1; // If it's in someone else's block it must have got out
1024 bool CWalletTx::InMempool() const
1027 if (mempool.exists(GetHash())) {
1033 bool CWalletTx::IsTrusted() const
1035 // Quick answer in most cases
1038 int nDepth = GetDepthInMainChain();
1043 if (!fConfChange || !IsFromMe(MINE_ALL)) // using wtx's cached debit
1046 // Don't trust unconfirmed transactions from us unless they are in the mempool.
1050 // Trusted if all inputs are from us and are in the mempool:
1051 for (const CTxIn& txin : vin)
1053 // Transactions not sent by us: not trusted
1054 const CWalletTx* parent = pwallet->GetWalletTx(txin.prevout.hash);
1057 const CTxOut& parentOut = parent->vout[txin.prevout.n];
1058 if (pwallet->IsMine(parentOut) != MINE_SPENDABLE)
1064 int64_t CWalletTx::GetDebit(const isminefilter& filter) const
1070 if (filter & MINE_SPENDABLE)
1073 nDebit += nDebitCached;
1076 nDebitCached = pwallet->GetDebit(*this, MINE_SPENDABLE);
1077 fDebitCached = true;
1078 nDebit += nDebitCached;
1081 if (filter & MINE_WATCH_ONLY)
1083 if (fWatchDebitCached)
1084 nDebit += nWatchDebitCached;
1087 nWatchDebitCached = pwallet->GetDebit(*this, MINE_WATCH_ONLY);
1088 fWatchDebitCached = true;
1089 nDebit += nWatchDebitCached;
1095 int64_t CWalletTx::GetCredit(const isminefilter& filter) const
1097 // Must wait until coinbase is safely deep enough in the chain before valuing it
1098 if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
1102 if (filter & MINE_SPENDABLE)
1104 // GetBalance can assume transactions in mapWallet won't change
1106 credit += nCreditCached;
1109 nCreditCached = pwallet->GetCredit(*this, MINE_SPENDABLE);
1110 fCreditCached = true;
1111 credit += nCreditCached;
1114 if (filter & MINE_WATCH_ONLY)
1116 if (fWatchCreditCached)
1117 credit += nWatchCreditCached;
1120 nWatchCreditCached = pwallet->GetCredit(*this, MINE_WATCH_ONLY);
1121 fWatchCreditCached = true;
1122 credit += nWatchCreditCached;
1128 int64_t CWalletTx::GetImmatureCredit(bool fUseCache) const
1130 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1132 if (fUseCache && fImmatureCreditCached)
1133 return nImmatureCreditCached;
1134 nImmatureCreditCached = pwallet->GetCredit(*this, MINE_SPENDABLE);
1135 fImmatureCreditCached = true;
1136 return nImmatureCreditCached;
1142 int64_t CWalletTx::GetImmatureWatchOnlyCredit(bool fUseCache) const
1144 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1146 if (fUseCache && fImmatureWatchCreditCached)
1147 return nImmatureWatchCreditCached;
1148 nImmatureWatchCreditCached = pwallet->GetCredit(*this, MINE_WATCH_ONLY);
1149 fImmatureWatchCreditCached = true;
1150 return nImmatureWatchCreditCached;
1157 int64_t CWalletTx::GetAvailableCredit(bool fUseCache) const
1159 // Must wait until coinbase is safely deep enough in the chain before valuing it
1160 if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
1164 if (fAvailableCreditCached)
1165 return nAvailableCreditCached;
1168 int64_t nCredit = 0;
1169 for (unsigned int i = 0; i < vout.size(); i++)
1173 const CTxOut &txout = vout[i];
1174 nCredit += pwallet->GetCredit(txout, MINE_SPENDABLE);
1175 if (!MoneyRange(nCredit))
1176 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
1180 nAvailableCreditCached = nCredit;
1181 fAvailableCreditCached = true;
1186 int64_t CWalletTx::GetAvailableWatchCredit(bool fUseCache) const
1188 // Must wait until coinbase is safely deep enough in the chain before valuing it
1189 if ((IsCoinBase() || IsCoinStake()) && GetBlocksToMaturity() > 0)
1193 if (fAvailableWatchCreditCached)
1194 return nAvailableWatchCreditCached;
1197 int64_t nCredit = 0;
1198 for (unsigned int i = 0; i < vout.size(); i++)
1202 const CTxOut &txout = vout[i];
1203 nCredit += pwallet->GetCredit(txout, MINE_WATCH_ONLY);
1204 if (!MoneyRange(nCredit))
1205 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
1209 nAvailableWatchCreditCached = nCredit;
1210 fAvailableWatchCreditCached = true;
1215 int64_t CWalletTx::GetChange() const
1218 return nChangeCached;
1219 nChangeCached = pwallet->GetChange(*this);
1220 fChangeCached = true;
1221 return nChangeCached;
1224 void CWalletTx::GetAmounts(int64_t& nGeneratedImmature, int64_t& nGeneratedMature, list<pair<CBitcoinAddress, int64_t> >& listReceived,
1225 list<pair<CBitcoinAddress, int64_t> >& listSent, int64_t& nFee, string& strSentAccount, const isminefilter& filter) const
1227 nGeneratedImmature = nGeneratedMature = nFee = 0;
1228 listReceived.clear();
1230 strSentAccount = strFromAccount;
1232 if (IsCoinBase() || IsCoinStake())
1234 if (GetBlocksToMaturity() > 0)
1235 nGeneratedImmature = pwallet->GetCredit(*this, filter);
1237 nGeneratedMature = GetCredit(filter);
1242 int64_t nDebit = GetDebit(filter);
1243 if (nDebit > 0) // debit>0 means we signed/sent this transaction
1245 int64_t nValueOut = GetValueOut();
1246 nFee = nDebit - nValueOut;
1250 for (const CTxOut& txout : vout)
1252 isminetype fIsMine = pwallet->IsMine(txout);
1253 // Only need to handle txouts if AT LEAST one of these is true:
1254 // 1) they debit from us (sent)
1255 // 2) the output is to us (received)
1258 // Don't report 'change' txouts
1259 if (pwallet->IsChange(txout))
1262 else if (!(fIsMine & filter))
1265 // In either case, we need to get the destination address
1266 CBitcoinAddress address;
1267 if (!ExtractAddress(*pwallet, txout.scriptPubKey, address))
1269 printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
1270 this->GetHash().ToString().c_str());
1271 address = CBitcoinAddress();
1274 // If we are debited by the transaction, add the output as a "sent" entry
1276 listSent.push_back(make_pair(address, txout.nValue));
1278 // If we are receiving the output, add it as a "received" entry
1279 if (fIsMine & filter)
1280 listReceived.push_back(make_pair(address, txout.nValue));
1285 void CWalletTx::GetAccountAmounts(const string& strAccount, int64_t& nGenerated, int64_t& nReceived,
1286 int64_t& nSent, int64_t& nFee, const isminefilter& filter) const
1288 nGenerated = nReceived = nSent = nFee = 0;
1290 int64_t allGeneratedImmature, allGeneratedMature, allFee;
1291 allGeneratedImmature = allGeneratedMature = allFee = 0;
1292 string strSentAccount;
1293 list<pair<CBitcoinAddress, int64_t> > listReceived;
1294 list<pair<CBitcoinAddress, int64_t> > listSent;
1295 GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount, filter);
1297 if (strAccount.empty())
1298 nGenerated = allGeneratedMature;
1299 if (strAccount == strSentAccount)
1301 for (const auto& s : listSent)
1306 LOCK(pwallet->cs_wallet);
1307 for (const auto& r : listReceived)
1309 if (pwallet->mapAddressBook.count(r.first))
1311 map<CBitcoinAddress, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);
1312 if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)
1313 nReceived += r.second;
1315 else if (strAccount.empty())
1317 nReceived += r.second;
1323 bool CWalletTx::IsFromMe(const isminefilter &filter) const
1325 return (GetDebit(filter) > 0);
1328 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
1332 const int COPY_DEPTH = 3;
1333 if (SetMerkleBranch() < COPY_DEPTH)
1335 vector<uint256> vWorkQueue;
1336 for (const CTxIn& txin : vin)
1337 vWorkQueue.push_back(txin.prevout.hash);
1339 // This critsect is OK because txdb is already open
1341 LOCK(pwallet->cs_wallet);
1342 map<uint256, const CMerkleTx*> mapWalletPrev;
1343 set<uint256> setAlreadyDone;
1344 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
1346 uint256 hash = vWorkQueue[i];
1347 if (setAlreadyDone.count(hash))
1349 setAlreadyDone.insert(hash);
1352 map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
1353 if (mi != pwallet->mapWallet.end())
1356 for (const CMerkleTx& txWalletPrev : (*mi).second.vtxPrev)
1357 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
1359 else if (mapWalletPrev.count(hash))
1361 tx = *mapWalletPrev[hash];
1363 else if (!fClient && txdb.ReadDiskTx(hash, tx))
1369 printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
1373 int nDepth = tx.SetMerkleBranch();
1374 vtxPrev.push_back(tx);
1376 if (nDepth < COPY_DEPTH)
1378 for (const CTxIn& txin : tx.vin)
1379 vWorkQueue.push_back(txin.prevout.hash);
1385 reverse(vtxPrev.begin(), vtxPrev.end());
1388 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
1393 // Add previous supporting transactions first
1394 for (CMerkleTx& tx : vtxPrev)
1396 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
1398 uint256 hash = tx.GetHash();
1399 if (!mempool.exists(hash) && !txdb.ContainsTx(hash))
1400 tx.AcceptToMemoryPool(txdb, fCheckInputs);
1403 return AcceptToMemoryPool(txdb, fCheckInputs);
1408 bool CWalletTx::AcceptWalletTransaction()
1411 return AcceptWalletTransaction(txdb);
1414 bool CWalletTx::WriteToDisk()
1416 return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
1419 // Scan the block chain (starting in pindexStart) for transactions
1420 // from or to us. If fUpdate is true, found transactions that already
1421 // exist in the wallet will be updated.
1422 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
1426 CBlockIndex* pindex = pindexStart;
1432 block.ReadFromDisk(pindex, true);
1433 for (CTransaction& tx : block.vtx)
1435 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
1438 pindex = pindex->pnext;
1444 int CWallet::ScanForWalletTransaction(const uint256& hashTx)
1447 tx.ReadFromDisk(COutPoint(hashTx, 0));
1448 if (AddToWalletIfInvolvingMe(tx, NULL, true))
1453 void CWallet::ReacceptWalletTransactions()
1456 bool fRepeat = true;
1461 vector<CDiskTxPos> vMissingTx;
1462 for (auto& item : mapWallet)
1464 CWalletTx& wtx = item.second;
1465 if ((wtx.IsCoinBase() && wtx.IsSpent(0)) || (wtx.IsCoinStake() && wtx.IsSpent(1)))
1469 bool fUpdated = false;
1470 if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
1472 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
1473 if (txindex.vSpent.size() != wtx.vout.size())
1475 printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %" PRIszu " != wtx.vout.size() %" PRIszu "\n", txindex.vSpent.size(), wtx.vout.size());
1478 for (unsigned int i = 0; i < txindex.vSpent.size(); i++)
1482 if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i]))
1486 vMissingTx.push_back(txindex.vSpent[i]);
1491 printf("ReacceptWalletTransactions found spent coin %snvc %s\n", FormatMoney(wtx.GetCredit(MINE_ALL)).c_str(), wtx.GetHash().ToString().c_str());
1498 // Re-accept any txes of ours that aren't already in a block
1499 if (!(wtx.IsCoinBase() || wtx.IsCoinStake()))
1500 wtx.AcceptWalletTransaction(txdb, false);
1503 if (!vMissingTx.empty())
1505 // TODO: optimize this to scan just part of the block chain?
1506 if (ScanForWalletTransactions(pindexGenesisBlock))
1507 fRepeat = true; // Found missing transactions: re-do re-accept.
1512 bool CWalletTx::RelayWalletTransaction(CTxDB& txdb)
1514 uint256 hash = GetHash();
1515 if (IsCoinBase() || IsCoinStake() || txdb.ContainsTx(hash) || !InMempool())
1518 for(std::vector<CMerkleTx>::const_iterator it = vtxPrev.begin(); it != vtxPrev.end(); it++)
1520 const CMerkleTx& tx = *it;
1521 uint256 hash = tx.GetHash();
1523 if (tx.IsCoinBase() || tx.IsCoinStake())
1526 if (!txdb.ContainsTx(hash))
1527 RelayTransaction((CTransaction)tx, hash);
1530 printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
1531 RelayTransaction((CTransaction)*this, hash);
1535 bool CWalletTx::RelayWalletTransaction()
1538 return RelayWalletTransaction(txdb);
1541 std::vector<uint256> CWallet::ResendWalletTransactionsBefore(int64_t nTime)
1543 std::vector<uint256> result;
1546 // Sort them in chronological order
1547 map<unsigned int, CWalletTx*> mapSorted;
1548 for (auto& item : mapWallet)
1550 CWalletTx& wtx = item.second;
1551 // Don't rebroadcast if newer than nTime:
1552 if (wtx.nTimeReceived > nTime)
1554 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
1556 for (auto& item : mapSorted)
1558 CWalletTx& wtx = *item.second;
1559 if (wtx.RelayWalletTransaction())
1560 result.push_back(wtx.GetHash());
1565 void CWallet::ResendWalletTransactions(int64_t nBestBlockTime)
1567 int64_t nNow = GetTime();
1569 // Do this infrequently and randomly to avoid giving away
1570 // that these are our transactions.
1571 if (nNow < nNextResend)
1573 bool fFirst = (nNextResend == 0);
1574 nNextResend = PoissonNextSend(nNow, 5*60);
1578 // Only do it if there's been a new block since last time
1579 if (nBestBlockTime < nLastResend)
1583 // Rebroadcast unconfirmed txes older than 5 minutes before the last
1585 std::vector<uint256> relayed = ResendWalletTransactionsBefore(nBestBlockTime - 5*60);
1586 if (!relayed.empty())
1587 printf("CWallet::ResendWalletTransactions: rebroadcast %" PRIszu " unconfirmed transactions\n", relayed.size());
1591 //////////////////////////////////////////////////////////////////////////////
1597 int64_t CWallet::GetBalance() const
1602 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1604 const CWalletTx* pcoin = &(*it).second;
1605 if (pcoin->IsTrusted())
1606 nTotal += pcoin->GetAvailableCredit();
1613 int64_t CWallet::GetWatchOnlyBalance() const
1618 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1620 const CWalletTx* pcoin = &(*it).second;
1621 if (pcoin->IsTrusted())
1622 nTotal += pcoin->GetAvailableWatchCredit();
1629 int64_t CWallet::GetUnconfirmedBalance() const
1634 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1636 const CWalletTx* pcoin = &(*it).second;
1637 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
1638 nTotal += pcoin->GetAvailableCredit();
1644 int64_t CWallet::GetUnconfirmedWatchOnlyBalance() const
1649 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1651 const CWalletTx* pcoin = &(*it).second;
1652 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
1653 nTotal += pcoin->GetAvailableWatchCredit();
1659 int64_t CWallet::GetImmatureBalance() const
1664 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1666 const CWalletTx* pcoin = &(*it).second;
1667 nTotal += pcoin->GetImmatureCredit();
1673 int64_t CWallet::GetImmatureWatchOnlyBalance() const
1678 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1680 const CWalletTx* pcoin = &(*it).second;
1681 nTotal += pcoin->GetImmatureWatchOnlyCredit();
1687 // populate vCoins with vector of spendable COutputs
1688 void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl) const
1694 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1696 const CWalletTx* pcoin = &(*it).second;
1698 if (!pcoin->IsFinal())
1701 if (fOnlyConfirmed && !pcoin->IsTrusted())
1704 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
1707 if(pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0)
1710 for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
1711 isminetype mine = IsMine(pcoin->vout[i]);
1712 if (!(pcoin->IsSpent(i)) && mine != MINE_NO &&
1713 pcoin->vout[i].nValue >= nMinimumInputValue &&
1714 (!coinControl || !coinControl->HasSelected() || coinControl->IsSelected((*it).first, i)))
1716 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain(), mine == MINE_SPENDABLE));
1723 void CWallet::AvailableCoinsMinConf(vector<COutput>& vCoins, int nConf, int64_t nMinValue, int64_t nMaxValue) const
1729 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1731 const CWalletTx* pcoin = &(*it).second;
1733 if (!pcoin->IsFinal())
1736 if(pcoin->GetDepthInMainChain() < nConf)
1739 for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
1740 isminetype mine = IsMine(pcoin->vout[i]);
1742 // ignore coin if it was already spent or we don't own it
1743 if (pcoin->IsSpent(i) || mine == MINE_NO)
1746 // if coin value is between required limits then add new item to vector
1747 if (pcoin->vout[i].nValue >= nMinValue && pcoin->vout[i].nValue < nMaxValue)
1748 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain(), mine == MINE_SPENDABLE));
1754 static void ApproximateBestSubset(vector<pair<int64_t, pair<const CWalletTx*,unsigned int> > >vValue, int64_t nTotalLower, int64_t nTargetValue,
1755 vector<char>& vfBest, int64_t& nBest, int iterations = 1000)
1757 vector<char> vfIncluded;
1759 vfBest.assign(vValue.size(), true);
1760 nBest = nTotalLower;
1762 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
1764 vfIncluded.assign(vValue.size(), false);
1766 bool fReachedTarget = false;
1767 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
1769 for (unsigned int i = 0; i < vValue.size(); i++)
1771 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
1773 nTotal += vValue[i].first;
1774 vfIncluded[i] = true;
1775 if (nTotal >= nTargetValue)
1777 fReachedTarget = true;
1781 vfBest = vfIncluded;
1783 nTotal -= vValue[i].first;
1784 vfIncluded[i] = false;
1792 int64_t CWallet::GetStake() const
1796 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1798 const CWalletTx* pcoin = &(*it).second;
1799 if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1800 nTotal += CWallet::GetCredit(*pcoin, MINE_ALL);
1805 int64_t CWallet::GetWatchOnlyStake() const
1809 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1811 const CWalletTx* pcoin = &(*it).second;
1812 if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1813 nTotal += CWallet::GetCredit(*pcoin, MINE_WATCH_ONLY);
1818 int64_t CWallet::GetNewMint() const
1822 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1824 const CWalletTx* pcoin = &(*it).second;
1825 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1826 nTotal += CWallet::GetCredit(*pcoin, MINE_ALL);
1831 int64_t CWallet::GetWatchOnlyNewMint() const
1835 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1837 const CWalletTx* pcoin = &(*it).second;
1838 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1839 nTotal += CWallet::GetCredit(*pcoin, MINE_WATCH_ONLY);
1844 bool CWallet::SelectCoinsMinConf(int64_t nTargetValue, unsigned int nSpendTime, int nConfMine, int nConfTheirs, vector<COutput> vCoins, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64_t& nValueRet) const
1846 setCoinsRet.clear();
1849 // List of values less than target
1850 pair<int64_t, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
1851 coinLowestLarger.first = std::numeric_limits<int64_t>::max();
1852 coinLowestLarger.second.first = NULL;
1853 vector<pair<int64_t, pair<const CWalletTx*,unsigned int> > > vValue;
1854 int64_t nTotalLower = 0;
1856 std::random_device rd;
1857 std::mt19937 g(rd());
1858 shuffle(vCoins.begin(), vCoins.end(), g);
1860 for (const COutput &output : vCoins)
1862 if (!output.fSpendable)
1865 const CWalletTx *pcoin = output.tx;
1867 if (output.nDepth < (pcoin->IsFromMe(MINE_ALL) ? nConfMine : nConfTheirs))
1872 // Follow the timestamp rules
1873 if (pcoin->nTime > nSpendTime)
1876 int64_t n = pcoin->vout[i].nValue;
1878 pair<int64_t,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1880 if (n == nTargetValue)
1882 setCoinsRet.insert(coin.second);
1883 nValueRet += coin.first;
1886 else if (n < nTargetValue + CENT)
1888 vValue.push_back(coin);
1891 else if (n < coinLowestLarger.first)
1893 coinLowestLarger = coin;
1897 if (nTotalLower == nTargetValue)
1899 for (unsigned int i = 0; i < vValue.size(); ++i)
1901 setCoinsRet.insert(vValue[i].second);
1902 nValueRet += vValue[i].first;
1907 if (nTotalLower < nTargetValue)
1909 if (coinLowestLarger.second.first == NULL)
1911 setCoinsRet.insert(coinLowestLarger.second);
1912 nValueRet += coinLowestLarger.first;
1916 // Solve subset sum by stochastic approximation
1917 std::sort(vValue.begin(), vValue.end(), CompareValueOnly());
1918 std::reverse(vValue.begin(), vValue.end());
1919 vector<char> vfBest;
1922 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);
1923 if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT)
1924 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000);
1926 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
1927 // or the next bigger coin is closer), return the bigger coin
1928 if (coinLowestLarger.second.first &&
1929 ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest))
1931 setCoinsRet.insert(coinLowestLarger.second);
1932 nValueRet += coinLowestLarger.first;
1935 for (unsigned int i = 0; i < vValue.size(); i++)
1938 setCoinsRet.insert(vValue[i].second);
1939 nValueRet += vValue[i].first;
1942 if (fDebug && GetBoolArg("-printpriority"))
1945 printf("SelectCoins() best subset: ");
1946 for (unsigned int i = 0; i < vValue.size(); i++)
1948 printf("%s ", FormatMoney(vValue[i].first).c_str());
1949 printf("total %s\n", FormatMoney(nBest).c_str());
1956 bool CWallet::SelectCoins(int64_t nTargetValue, unsigned int nSpendTime, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64_t& nValueRet, const CCoinControl* coinControl) const
1958 vector<COutput> vCoins;
1959 AvailableCoins(vCoins, true, coinControl);
1961 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
1962 if (coinControl && coinControl->HasSelected())
1964 for (const COutput& out : vCoins)
1968 nValueRet += out.tx->vout[out.i].nValue;
1969 setCoinsRet.insert(make_pair(out.tx, out.i));
1971 return (nValueRet >= nTargetValue);
1974 return (SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 6, vCoins, setCoinsRet, nValueRet) ||
1975 SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 1, vCoins, setCoinsRet, nValueRet) ||
1976 SelectCoinsMinConf(nTargetValue, nSpendTime, 0, 1, vCoins, setCoinsRet, nValueRet));
1984 CWallet::CWallet(std::string strWalletFileIn)
1988 strWalletFile = strWalletFileIn;
1992 void CWallet::SetNull()
1994 nWalletVersion = FEATURE_BASE;
1995 nWalletMaxVersion = FEATURE_BASE;
1996 fFileBacked = false;
1997 nMasterKeyMaxID = 0;
1998 pwalletdbEncryption = NULL;
1999 pwalletdbDecryption = NULL;
2008 // Select some coins without random shuffle or best subset approximation
2009 bool CWallet::SelectCoinsSimple(int64_t nTargetValue, int64_t nMinValue, int64_t nMaxValue, unsigned int nSpendTime, int nMinConf, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64_t& nValueRet) const
2011 vector<COutput> vCoins;
2012 AvailableCoinsMinConf(vCoins, nMinConf, nMinValue, nMaxValue);
2014 setCoinsRet.clear();
2017 for (COutput output : vCoins)
2019 if(!output.fSpendable)
2021 const CWalletTx *pcoin = output.tx;
2024 // Ignore immature coins
2025 if (pcoin->GetBlocksToMaturity() > 0)
2028 // Stop if we've chosen enough inputs
2029 if (nValueRet >= nTargetValue)
2032 // Follow the timestamp rules
2033 if (pcoin->nTime > nSpendTime)
2036 int64_t n = pcoin->vout[i].nValue;
2038 pair<int64_t,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
2040 if (n >= nTargetValue)
2042 // If input value is greater or equal to target then simply insert
2043 // it into the current subset and exit
2044 setCoinsRet.insert(coin.second);
2045 nValueRet += coin.first;
2048 else if (n < nTargetValue + CENT)
2050 setCoinsRet.insert(coin.second);
2051 nValueRet += coin.first;
2058 bool CWallet::CreateTransaction(const vector<pair<CScript, int64_t> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl* coinControl)
2061 for (const auto& s : vecSend)
2067 if (vecSend.empty() || nValue < 0)
2070 wtxNew.BindWallet(this);
2073 LOCK2(cs_main, cs_wallet);
2074 // txdb must be opened before the mapWallet lock
2077 nFeeRet = nTransactionFee;
2081 wtxNew.vout.clear();
2082 wtxNew.fFromMe = true;
2084 int64_t nTotalValue = nValue + nFeeRet;
2085 double dPriority = 0;
2086 // vouts to the payees
2087 for (const auto& s : vecSend)
2088 wtxNew.vout.push_back(CTxOut(s.second, s.first));
2090 // Choose coins to use
2091 set<pair<const CWalletTx*,unsigned int> > setCoins;
2092 int64_t nValueIn = 0;
2093 if (!SelectCoins(nTotalValue, wtxNew.nTime, setCoins, nValueIn, coinControl))
2095 for (auto pcoin : setCoins)
2097 int64_t nCredit = pcoin.first->vout[pcoin.second].nValue;
2098 dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
2101 int64_t nChange = nValueIn - nValue - nFeeRet;
2104 // Fill a vout to ourself
2105 // TODO: pass in scriptChange instead of reservekey so
2106 // change transaction isn't always pay-to-bitcoin-address
2107 CScript scriptChange;
2109 // coin control: send change to custom address
2110 if (coinControl && coinControl->destChange.IsValid())
2111 scriptChange.SetAddress(coinControl->destChange);
2113 // no coin control: send change to newly generated address
2116 // Note: We use a new key here to keep it from being obvious which side is the change.
2117 // The drawback is that by not reusing a previous key, the change may be lost if a
2118 // backup is restored, if the backup doesn't have the new private key for the change.
2119 // If we reused the old key, it would be possible to add code to look for and
2120 // rediscover unknown transactions that were written with keys of ours to recover
2121 // post-backup change.
2123 // Reserve a new key pair from key pool
2124 CPubKey vchPubKey = reservekey.GetReservedKey();
2126 scriptChange.SetDestination(vchPubKey.GetID());
2129 // Insert change txn at random position:
2130 vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
2131 wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
2134 reservekey.ReturnKey();
2137 for (const auto& coin : setCoins)
2138 wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
2142 for (const auto& coin : setCoins)
2143 if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
2147 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
2148 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
2150 dPriority /= nBytes;
2152 // Check that enough fee is included
2153 bool fAllowFree = CTransaction::AllowFree(dPriority);
2154 int64_t nPayFee = nTransactionFee * (1 + (int64_t)nBytes / 1000);
2155 int64_t nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
2157 if (nFeeRet < max(nPayFee, nMinFee))
2159 nFeeRet = max(nPayFee, nMinFee);
2163 // Fill vtxPrev by copying from previous transactions vtxPrev
2164 wtxNew.AddSupportingTransactions(txdb);
2165 wtxNew.fTimeReceivedIsTxTime = true;
2174 bool CWallet::CreateTransaction(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl* coinControl)
2176 vector< pair<CScript, int64_t> > vecSend;
2177 vecSend.push_back(make_pair(scriptPubKey, nValue));
2178 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, coinControl);
2181 void CWallet::GetStakeWeightFromValue(const int64_t& nTime, const int64_t& nValue, uint64_t& nWeight)
2183 int64_t nTimeWeight = GetWeight(nTime, GetTime());
2185 // If time weight is lower or equal to zero then weight is zero.
2186 if (nTimeWeight <= 0)
2192 CBigNum bnCoinDayWeight = CBigNum(nValue) * nTimeWeight / COIN / nOneDay;
2193 nWeight = bnCoinDayWeight.getuint64();
2196 bool CWallet::MergeCoins(const int64_t& nAmount, const int64_t& nMinValue, const int64_t& nOutputValue, list<uint256>& listMerged)
2198 int64_t nBalance = GetBalance();
2200 if (nAmount > nBalance)
2204 int64_t nValueIn = 0;
2205 set<pair<const CWalletTx*,unsigned int> > setCoins;
2207 // Simple coins selection - no randomization
2208 if (!SelectCoinsSimple(nAmount, nMinValue, nOutputValue, GetTime(), 1, setCoins, nValueIn))
2211 if (setCoins.empty())
2215 vector<const CWalletTx*> vwtxPrev;
2217 // Reserve a new key pair from key pool
2218 CReserveKey reservekey(this);
2219 CPubKey vchPubKey = reservekey.GetReservedKey();
2222 CScript scriptOutput;
2223 scriptOutput.SetDestination(vchPubKey.GetID());
2226 wtxNew.vout.push_back(CTxOut(0, scriptOutput));
2229 for (auto pcoin : setCoins)
2231 int64_t nCredit = pcoin.first->vout[pcoin.second].nValue;
2233 // Add current coin to inputs list and add its credit to transaction output
2234 wtxNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
2235 wtxNew.vout[0].nValue += nCredit;
2236 vwtxPrev.push_back(pcoin.first);
2239 // Replaced with estimation for performance purposes
2241 for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
2242 const CWalletTx *txin = vwtxPrev[i];
2244 // Sign scripts to get actual transaction size for fee calculation
2245 if (!SignSignature(*this, *txin, wtxNew, i))
2250 // Assuming that average scriptsig size is 110 bytes
2251 int64_t nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION) + wtxNew.vin.size() * 110;
2252 dWeight += (double)nCredit * pcoin.first->GetDepthInMainChain();
2254 double dFinalPriority = dWeight /= nBytes;
2255 bool fAllowFree = CTransaction::AllowFree(dFinalPriority);
2257 // Get actual transaction fee according to its estimated size and priority
2258 int64_t nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
2260 // Prepare transaction for commit if sum is enough ot its size is too big
2261 if (nBytes >= MAX_BLOCK_SIZE_GEN/6 || wtxNew.vout[0].nValue >= nOutputValue)
2263 wtxNew.vout[0].nValue -= nMinFee; // Set actual fee
2265 for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
2266 const CWalletTx *txin = vwtxPrev[i];
2269 if (!SignSignature(*this, *txin, wtxNew, i))
2273 // Try to commit, return false on failure
2274 if (!CommitTransaction(wtxNew, reservekey))
2277 listMerged.push_back(wtxNew.GetHash()); // Add to hashes list
2279 dWeight = 0; // Reset all temporary values
2282 wtxNew.vout.push_back(CTxOut(0, scriptOutput));
2286 // Create transactions if there are some unhandled coins left
2287 if (wtxNew.vout[0].nValue > 0) {
2288 int64_t nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION) + wtxNew.vin.size() * 110;
2290 double dFinalPriority = dWeight / nBytes;
2291 bool fAllowFree = CTransaction::AllowFree(dFinalPriority);
2293 // Get actual transaction fee according to its size and priority
2294 int64_t nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
2296 wtxNew.vout[0].nValue -= nMinFee; // Set actual fee
2298 if (wtxNew.vout[0].nValue <= 0)
2301 for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
2302 const CWalletTx *txin = vwtxPrev[i];
2304 // Sign all scripts again
2305 if (!SignSignature(*this, *txin, wtxNew, i))
2309 // Try to commit, return false on failure
2310 if (!CommitTransaction(wtxNew, reservekey))
2313 listMerged.push_back(wtxNew.GetHash()); // Add to hashes list
2319 bool CWallet::CreateCoinStake(uint256 &hashTx, uint32_t nOut, uint32_t nGenerationTime, uint32_t nBits, CTransaction &txNew, CKey& key)
2322 if (!GetTransaction(hashTx, wtx))
2323 return error("Transaction %s is not found\n", hashTx.GetHex().c_str());
2325 vector<valtype> vSolutions;
2326 txnouttype whichType;
2327 CScript scriptPubKeyOut;
2328 CScript scriptPubKeyKernel = wtx.vout[nOut].scriptPubKey;
2329 if (!Solver(scriptPubKeyKernel, whichType, vSolutions))
2330 return error("CreateCoinStake : failed to parse kernel\n");
2332 if (fDebug && GetBoolArg("-printcoinstake"))
2333 printf("CreateCoinStake : parsed kernel type=%d\n", whichType);
2335 if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH)
2336 return error("CreateCoinStake : no support for kernel type=%d\n", whichType);
2338 if (whichType == TX_PUBKEYHASH) // pay to address type
2340 // convert to pay to public key type
2341 if (!GetKey(uint160(vSolutions[0]), key))
2342 return error("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
2344 scriptPubKeyOut << key.GetPubKey() << OP_CHECKSIG;
2346 if (whichType == TX_PUBKEY)
2348 valtype& vchPubKey = vSolutions[0];
2349 if (!GetKey(Hash160(vchPubKey), key))
2350 return error("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
2351 if (key.GetPubKey() != vchPubKey)
2352 return error("CreateCoinStake : invalid key for kernel type=%d\n", whichType); // keys mismatch
2353 scriptPubKeyOut = scriptPubKeyKernel;
2356 // The following combine threshold is important to security
2357 // Should not be adjusted if you don't understand the consequences
2358 int64_t nCombineThreshold = GetProofOfWorkReward(GetLastBlockIndex(pindexBest, false)->nBits) / 3;
2360 int64_t nBalance = GetBalance();
2361 int64_t nCredit = wtx.vout[nOut].nValue;
2366 // List of constake dependencies
2367 vector<const CWalletTx*> vwtxPrev;
2368 vwtxPrev.push_back(&wtx);
2370 // Set generation time, and kernel input
2371 txNew.nTime = nGenerationTime;
2372 txNew.vin.push_back(CTxIn(hashTx, nOut));
2374 // Mark coin stake transaction with empty vout[0]
2375 CScript scriptEmpty;
2376 scriptEmpty.clear();
2377 txNew.vout.push_back(CTxOut(0, scriptEmpty));
2379 if (fDebug && GetBoolArg("-printcoinstake"))
2380 printf("CreateCoinStake : added kernel type=%d\n", whichType);
2382 int64_t nValueIn = 0;
2384 if (!SelectCoinsSimple(nBalance - nReserveBalance, MIN_TX_FEE, MAX_MONEY, nGenerationTime, nCoinbaseMaturity * 10, setCoins, nValueIn))
2387 if (setCoins.empty())
2390 bool fDontSplitCoins = false;
2391 if (GetWeight((int64_t)wtx.nTime, (int64_t)nGenerationTime) == nStakeMaxAge)
2393 // Only one output for old kernel inputs
2394 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
2396 // Iterate through set of (wtx*, nout) in order to find some additional inputs for our new coinstake transaction.
2398 // * Value is higher than 0.01 NVC;
2399 // * Only add inputs of the same key/address as kernel;
2400 // * Input hash and kernel parent hash should be different.
2401 for(CoinsSet::iterator pcoin = setCoins.begin(); pcoin != setCoins.end(); pcoin++)
2403 // Stop adding more inputs if already too many inputs
2404 if (txNew.vin.size() >= 100)
2406 // Stop adding more inputs if value is already pretty significant
2407 if (nCredit > nCombineThreshold)
2409 // Stop adding inputs if reached reserve limit
2410 if (nCredit + pcoin->first->vout[pcoin->second].nValue > nBalance - nReserveBalance)
2413 int64_t nTimeWeight = GetWeight((int64_t)pcoin->first->nTime, (int64_t)nGenerationTime);
2415 // Do not add input that is still too young
2416 if (nTimeWeight < nStakeMaxAge)
2418 // Do not add input if key/address is not the same as kernel
2419 if (pcoin->first->vout[pcoin->second].scriptPubKey != scriptPubKeyKernel && pcoin->first->vout[pcoin->second].scriptPubKey != txNew.vout[1].scriptPubKey)
2421 // Do not add input if parents are the same
2422 if (pcoin->first->GetHash() != txNew.vin[0].prevout.hash)
2424 // Do not add additional significant input
2425 if (pcoin->first->vout[pcoin->second].nValue > nCombineThreshold)
2428 txNew.vin.push_back(CTxIn(pcoin->first->GetHash(), pcoin->second));
2429 nCredit += pcoin->first->vout[pcoin->second].nValue;
2430 vwtxPrev.push_back(pcoin->first);
2433 fDontSplitCoins = true;
2437 int64_t nSplitThreshold = GetArg("-splitthreshold", nCombineThreshold);
2439 if (fDebug && GetBoolArg("-printcoinstake"))
2440 printf("CreateCoinStake : nSplitThreshold=%" PRId64 "\n", nSplitThreshold);
2442 if (nCredit > nSplitThreshold)
2444 // Split stake input if credit is lower than combine threshold and maximum weight isn't reached yet
2445 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
2446 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
2448 if (fDebug && GetBoolArg("-printcoinstake"))
2449 printf("CreateCoinStake : splitting coinstake\n");
2453 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
2454 fDontSplitCoins = true;
2458 // Calculate coin age reward
2461 if (!txNew.GetCoinAge(txdb, nCoinAge))
2462 return error("CreateCoinStake : failed to calculate coin age\n");
2463 nCredit += GetProofOfStakeReward(nCoinAge, nBits, nGenerationTime);
2465 int64_t nMinFee = 0;
2468 // Set output amount
2469 if (fDontSplitCoins)
2470 txNew.vout[1].nValue = nCredit - nMinFee;
2473 txNew.vout[1].nValue = ((nCredit - nMinFee) / 2 / CENT) * CENT;
2474 txNew.vout[2].nValue = nCredit - nMinFee - txNew.vout[1].nValue;
2479 for (const CWalletTx* pcoin : vwtxPrev)
2481 if (!SignSignature(*this, *pcoin, txNew, nIn++))
2482 return error("CreateCoinStake : failed to sign coinstake\n");
2486 unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION);
2487 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
2488 return error("CreateCoinStake : exceeded coinstake size limit\n");
2490 // Check enough fee is paid
2491 if (nMinFee < txNew.GetMinFee(1, false, GMF_BLOCK, nBytes) - CENT)
2493 nMinFee = txNew.GetMinFee(1, false, GMF_BLOCK, nBytes) - CENT;
2494 continue; // try signing again
2498 if (fDebug && GetBoolArg("-printfee"))
2499 printf("CreateCoinStake : fee for coinstake %s\n", FormatMoney(nMinFee).c_str());
2504 // Successfully created coinstake
2508 // Call after CreateTransaction unless you want to abort
2509 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
2512 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
2514 // Track how many getdata requests our transaction gets
2515 mapRequestCount[wtxNew.GetHash()] = 0;
2517 // Try to broadcast before saving
2518 if (!wtxNew.AcceptToMemoryPool())
2520 // This must not fail. The transaction has already been signed.
2521 printf("CommitTransaction() : Error: Transaction not valid");
2525 wtxNew.RelayWalletTransaction();
2528 LOCK2(cs_main, cs_wallet);
2530 // This is only to keep the database open to defeat the auto-flush for the
2531 // duration of this scope. This is the only place where this optimization
2532 // maybe makes sense; please don't do it anywhere else.
2533 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
2535 // Take key pair from key pool so it won't be used again
2536 reservekey.KeepKey();
2538 // Add tx to wallet, because if it has change it's also ours,
2539 // otherwise just for transaction history.
2540 AddToWallet(wtxNew);
2542 // Mark old coins as spent
2543 for (const CTxIn& txin : wtxNew.vin)
2545 CWalletTx &coin = mapWallet[txin.prevout.hash];
2546 coin.BindWallet(this);
2547 coin.MarkSpent(txin.prevout.n);
2549 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
2550 vMintingWalletUpdated.push_back(coin.GetHash());
2563 string CWallet::SendMoney(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, bool fAskFee)
2567 return _("Invalid amount");
2568 if (nValue + nTransactionFee > GetBalance())
2569 return _("Insufficient funds");
2571 CReserveKey reservekey(this);
2572 int64_t nFeeRequired;
2576 string strError = _("Error: Wallet locked, unable to create transaction ");
2577 printf("SendMoney() : %s", strError.c_str());
2580 if (fWalletUnlockMintOnly)
2582 string strError = _("Error: Wallet unlocked for block minting only, unable to create transaction.");
2583 printf("SendMoney() : %s", strError.c_str());
2586 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
2589 if (nValue + nFeeRequired > GetBalance())
2590 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());
2592 strError = _("Error: Transaction creation failed ");
2593 printf("SendMoney() : %s", strError.c_str());
2597 if (fAskFee && !uiInterface.ThreadSafeAskFee(nFeeRequired, _("Sending...")))
2600 if (!CommitTransaction(wtxNew, reservekey))
2601 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.");
2606 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
2610 fFirstRunRet = false;
2611 DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
2612 if (nLoadWalletRet == DB_NEED_REWRITE)
2614 if (CDB::Rewrite(strWalletFile, "\x04pool"))
2617 // Note: can't top-up keypool here, because wallet is locked.
2618 // User will be prompted to unlock wallet the next operation
2619 // the requires a new key.
2623 if (nLoadWalletRet != DB_LOAD_OK)
2624 return nLoadWalletRet;
2625 fFirstRunRet = !vchDefaultKey.IsValid();
2627 NewThread(ThreadFlushWalletDB, &strWalletFile);
2631 DBErrors CWallet::ZapWalletTx()
2635 DBErrors nZapWalletTxRet = CWalletDB(strWalletFile,"cr+").ZapWalletTx(this);
2636 if (nZapWalletTxRet == DB_NEED_REWRITE)
2638 if (CDB::Rewrite(strWalletFile, "\x04pool"))
2642 // Note: can't top-up keypool here, because wallet is locked.
2643 // User will be prompted to unlock wallet the next operation
2644 // the requires a new key.
2648 if (nZapWalletTxRet != DB_LOAD_OK)
2649 return nZapWalletTxRet;
2654 bool CWallet::SetAddressBookName(const CTxDestination& address, const string& strName)
2656 return SetAddressBookName(CBitcoinAddress(address), strName);
2659 bool CWallet::SetAddressBookName(const CBitcoinAddress& address, const string& strName)
2661 std::map<CBitcoinAddress, string>::iterator mi = mapAddressBook.find(address);
2662 mapAddressBook[address] = strName;
2663 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != MINE_NO, (mi == mapAddressBook.end()) ? CT_NEW : CT_UPDATED);
2666 return CWalletDB(strWalletFile).WriteName(address.ToString(), strName);
2669 bool CWallet::DelAddressBookName(const CBitcoinAddress& address)
2671 mapAddressBook.erase(address);
2672 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != MINE_NO, CT_DELETED);
2675 return CWalletDB(strWalletFile).EraseName(address.ToString());
2679 void CWallet::PrintWallet(const CBlock& block)
2683 if (block.IsProofOfStake() && mapWallet.count(block.vtx[1].GetHash()))
2685 CWalletTx& wtx = mapWallet[block.vtx[1].GetHash()];
2686 printf(" PoS: %d %d %" PRId64 "", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit(MINE_ALL));
2688 else if (mapWallet.count(block.vtx[0].GetHash()))
2690 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
2691 printf(" PoW: %d %d %" PRId64 "", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit(MINE_ALL));
2697 void CWallet::Inventory(const uint256 &hash)
2701 std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
2702 if (mi != mapRequestCount.end())
2707 unsigned int CWallet::GetKeyPoolSize()
2709 return (unsigned int)(setKeyPool.size());
2712 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
2716 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
2717 if (mi != mapWallet.end())
2726 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
2730 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
2733 vchDefaultKey = vchPubKey;
2737 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
2739 if (!pwallet->fFileBacked)
2741 strWalletFileOut = pwallet->strWalletFile;
2746 // Mark old keypool keys as used,
2747 // and generate all new keys
2749 bool CWallet::NewKeyPool(unsigned int nSize)
2753 CWalletDB walletdb(strWalletFile);
2754 for (int64_t nIndex : setKeyPool)
2755 walletdb.ErasePool(nIndex);
2765 nKeys = max<uint64_t>(GetArg("-keypool", 100), 0);
2767 for (uint64_t i = 0; i < nKeys; i++)
2769 uint64_t nIndex = i+1;
2770 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
2771 setKeyPool.insert(nIndex);
2773 printf("CWallet::NewKeyPool wrote %" PRIu64 " new keys\n", nKeys);
2778 bool CWallet::TopUpKeyPool(unsigned int nSize)
2786 CWalletDB walletdb(strWalletFile);
2789 uint64_t nTargetSize;
2791 nTargetSize = nSize;
2793 nTargetSize = max<uint64_t>(GetArg("-keypool", 100), 0);
2795 while (setKeyPool.size() < (nTargetSize + 1))
2798 if (!setKeyPool.empty())
2799 nEnd = *(--setKeyPool.end()) + 1;
2800 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
2801 throw runtime_error("TopUpKeyPool() : writing generated key failed");
2802 setKeyPool.insert(nEnd);
2803 printf("keypool added key %" PRIu64 ", size=%" PRIszu "\n", nEnd, setKeyPool.size());
2809 void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool)
2812 keypool.vchPubKey = CPubKey();
2819 // Get the oldest key
2820 if(setKeyPool.empty())
2823 CWalletDB walletdb(strWalletFile);
2825 nIndex = *(setKeyPool.begin());
2826 setKeyPool.erase(setKeyPool.begin());
2827 if (!walletdb.ReadPool(nIndex, keypool))
2828 throw runtime_error("ReserveKeyFromKeyPool() : read failed");
2829 if (!HaveKey(keypool.vchPubKey.GetID()))
2830 throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
2831 assert(keypool.vchPubKey.IsValid());
2832 if (fDebug && GetBoolArg("-printkeypool"))
2833 printf("keypool reserve %" PRId64 "\n", nIndex);
2837 int64_t CWallet::AddReserveKey(const CKeyPool& keypool)
2840 LOCK2(cs_main, cs_wallet);
2841 CWalletDB walletdb(strWalletFile);
2843 int64_t nIndex = 1 + *(--setKeyPool.end());
2844 if (!walletdb.WritePool(nIndex, keypool))
2845 throw runtime_error("AddReserveKey() : writing added key failed");
2846 setKeyPool.insert(nIndex);
2852 void CWallet::KeepKey(int64_t nIndex)
2854 // Remove from key pool
2857 CWalletDB walletdb(strWalletFile);
2858 walletdb.ErasePool(nIndex);
2861 printf("keypool keep %" PRId64 "\n", nIndex);
2864 void CWallet::ReturnKey(int64_t nIndex)
2866 // Return to key pool
2869 setKeyPool.insert(nIndex);
2872 printf("keypool return %" PRId64 "\n", nIndex);
2875 bool CWallet::GetKeyFromPool(CPubKey& result, bool fAllowReuse)
2881 ReserveKeyFromKeyPool(nIndex, keypool);
2884 if (fAllowReuse && vchDefaultKey.IsValid())
2886 result = vchDefaultKey;
2889 if (IsLocked()) return false;
2890 result = GenerateNewKey();
2894 result = keypool.vchPubKey;
2899 int64_t CWallet::GetOldestKeyPoolTime()
2903 ReserveKeyFromKeyPool(nIndex, keypool);
2907 return keypool.nTime;
2910 std::map<CBitcoinAddress, int64_t> CWallet::GetAddressBalances()
2912 map<CBitcoinAddress, int64_t> balances;
2916 for (auto walletEntry : mapWallet)
2918 CWalletTx *pcoin = &walletEntry.second;
2920 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
2923 if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0)
2926 int nDepth = pcoin->GetDepthInMainChain();
2927 if (nDepth < (pcoin->IsFromMe(MINE_ALL) ? 0 : 1))
2930 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2932 CBitcoinAddress addr;
2933 if (!IsMine(pcoin->vout[i]))
2935 if(!ExtractAddress(*this, pcoin->vout[i].scriptPubKey, addr))
2938 int64_t n = pcoin->IsSpent(i) ? 0 : pcoin->vout[i].nValue;
2940 if (!balances.count(addr))
2942 balances[addr] += n;
2950 set< set<CBitcoinAddress> > CWallet::GetAddressGroupings()
2952 set< set<CBitcoinAddress> > groupings;
2953 set<CBitcoinAddress> grouping;
2955 for (auto& walletEntry : mapWallet)
2957 CWalletTx *pcoin = &walletEntry.second;
2959 if (pcoin->vin.size() > 0)
2961 bool any_mine = false;
2962 // group all input addresses with each other
2963 for (CTxIn txin : pcoin->vin)
2965 CBitcoinAddress address;
2966 if(!IsMine(txin)) // If this input isn't mine, ignore it
2968 if(!ExtractAddress(*this, mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
2970 grouping.insert(address);
2974 // group change with input addresses
2977 for (CTxOut txout : pcoin->vout)
2978 if (IsChange(txout))
2980 CBitcoinAddress txoutAddr;
2981 if(!ExtractAddress(*this, txout.scriptPubKey, txoutAddr))
2983 grouping.insert(txoutAddr);
2986 if (!grouping.empty())
2988 groupings.insert(grouping);
2993 // group lone addrs by themselves
2994 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2995 if (IsMine(pcoin->vout[i]))
2997 CBitcoinAddress address;
2998 if(!ExtractAddress(*this, pcoin->vout[i].scriptPubKey, address))
3000 grouping.insert(address);
3001 groupings.insert(grouping);
3006 set< set<CBitcoinAddress>* > uniqueGroupings; // a set of pointers to groups of addresses
3007 map< CBitcoinAddress, set<CBitcoinAddress>* > setmap; // map addresses to the unique group containing it
3008 for (set<CBitcoinAddress> grouping : groupings)
3010 // make a set of all the groups hit by this new group
3011 set< set<CBitcoinAddress>* > hits;
3012 map< CBitcoinAddress, set<CBitcoinAddress>* >::iterator it;
3013 for (CBitcoinAddress address : grouping)
3014 if ((it = setmap.find(address)) != setmap.end())
3015 hits.insert((*it).second);
3017 // merge all hit groups into a new single group and delete old groups
3018 set<CBitcoinAddress>* merged = new set<CBitcoinAddress>(grouping);
3019 for (set<CBitcoinAddress>* hit : hits)
3021 merged->insert(hit->begin(), hit->end());
3022 uniqueGroupings.erase(hit);
3025 uniqueGroupings.insert(merged);
3028 for (CBitcoinAddress element : *merged)
3029 setmap[element] = merged;
3032 set< set<CBitcoinAddress> > ret;
3033 for (set<CBitcoinAddress>* uniqueGrouping : uniqueGroupings)
3035 ret.insert(*uniqueGrouping);
3036 delete uniqueGrouping;
3042 // ppcoin: check 'spent' consistency between wallet and txindex
3043 // ppcoin: fix wallet spent state according to txindex
3044 void CWallet::FixSpentCoins(int& nMismatchFound, int64_t& nBalanceInQuestion, bool fCheckOnly)
3047 nBalanceInQuestion = 0;
3050 vector<CWalletTx*> vCoins;
3051 vCoins.reserve(mapWallet.size());
3052 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
3053 vCoins.push_back(&(*it).second);
3056 for (CWalletTx* pcoin : vCoins)
3058 // Find the corresponding transaction index
3060 if (!txdb.ReadTxIndex(pcoin->GetHash(), txindex))
3062 for (unsigned int n=0; n < pcoin->vout.size(); n++)
3064 if (IsMine(pcoin->vout[n]) && pcoin->IsSpent(n) && (txindex.vSpent.size() <= n || txindex.vSpent[n].IsNull()))
3066 printf("FixSpentCoins found lost coin %sppc %s[%u], %s\n",
3067 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
3069 nBalanceInQuestion += pcoin->vout[n].nValue;
3072 pcoin->MarkUnspent(n);
3073 pcoin->WriteToDisk();
3076 else if (IsMine(pcoin->vout[n]) && !pcoin->IsSpent(n) && (txindex.vSpent.size() > n && !txindex.vSpent[n].IsNull()))
3078 printf("FixSpentCoins found spent coin %sppc %s[%u], %s\n",
3079 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
3081 nBalanceInQuestion += pcoin->vout[n].nValue;
3084 pcoin->MarkSpent(n);
3085 pcoin->WriteToDisk();
3091 if(IsMine((CTransaction)*pcoin) && (pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetDepthInMainChain() == 0)
3093 printf("FixSpentCoins %s tx %s\n", fCheckOnly ? "found" : "removed", pcoin->GetHash().ToString().c_str());
3096 EraseFromWallet(pcoin->GetHash());
3102 // ppcoin: disable transaction (only for coinstake)
3103 void CWallet::DisableTransaction(const CTransaction &tx)
3105 if (!tx.IsCoinStake() || !IsFromMe(tx))
3106 return; // only disconnecting coinstake requires marking input unspent
3109 for (const CTxIn& txin : tx.vin)
3111 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
3112 if (mi != mapWallet.end())
3114 CWalletTx& prev = (*mi).second;
3115 if (txin.prevout.n < prev.vout.size() && IsMine(prev.vout[txin.prevout.n]))
3117 prev.MarkUnspent(txin.prevout.n);
3124 CPubKey CReserveKey::GetReservedKey()
3129 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
3131 vchPubKey = keypool.vchPubKey;
3134 printf("CReserveKey::GetReservedKey(): Warning: Using default key instead of a new key, top up your keypool!");
3135 vchPubKey = pwallet->vchDefaultKey;
3138 assert(vchPubKey.IsValid());
3142 void CReserveKey::KeepKey()
3145 pwallet->KeepKey(nIndex);
3147 vchPubKey = CPubKey();
3150 CReserveKey::CReserveKey(CWallet *pwalletIn)
3153 pwallet = pwalletIn;
3156 CReserveKey::~CReserveKey()
3162 void CReserveKey::ReturnKey()
3165 pwallet->ReturnKey(nIndex);
3167 vchPubKey = CPubKey();
3170 void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
3174 CWalletDB walletdb(strWalletFile);
3176 LOCK2(cs_main, cs_wallet);
3177 for (const int64_t& id : setKeyPool)
3180 if (!walletdb.ReadPool(id, keypool))
3181 throw runtime_error("GetAllReserveKeyHashes() : read failed");
3182 assert(keypool.vchPubKey.IsValid());
3183 CKeyID keyID = keypool.vchPubKey.GetID();
3184 if (!HaveKey(keyID))
3185 throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
3186 setAddress.insert(keyID);
3190 void CWallet::UpdatedTransaction(const uint256 &hashTx)
3194 // Only notify UI if this transaction is in this wallet
3195 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
3196 if (mi != mapWallet.end())
3198 NotifyTransactionChanged(this, hashTx, CT_UPDATED);
3199 vMintingWalletUpdated.push_back(hashTx);
3204 void CWallet::GetAddresses(std::map<CBitcoinAddress, int64_t> &mapAddresses) const {
3205 mapAddresses.clear();
3207 // get birth times for keys with metadata
3208 for (std::map<CBitcoinAddress, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++) {
3209 mapAddresses[it->first] = it->second.nCreateTime ? it->second.nCreateTime : 0;
3212 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
3213 // iterate over all wallet transactions...
3214 const CWalletTx &wtx = (*it).second;
3215 if (wtx.hashBlock == 0)
3216 continue; // skip unconfirmed transactions
3218 for(std::vector<CTxOut>::const_iterator it2 = wtx.vout.begin(); it2 != wtx.vout.end(); it2++) {
3219 const CTxOut &out = (*it2);
3220 // iterate over all their outputs
3221 CBitcoinAddress addressRet;
3222 if (ExtractAddress(*this, out.scriptPubKey, addressRet)) {
3223 if (mapAddresses.find(addressRet) != mapAddresses.end() && (mapAddresses[addressRet] == 0 || mapAddresses[addressRet] > wtx.nTime))
3224 mapAddresses[addressRet] = wtx.nTime;
3227 // multisig output affects more than one key
3228 std::vector<CKeyID> vAffected;
3229 ::ExtractAffectedKeys(*this, out.scriptPubKey, vAffected);
3231 for(std::vector<CKeyID>::const_iterator it3 = vAffected.begin(); it3 != vAffected.end(); it3++) {
3232 CBitcoinAddress addrAffected(*it3);
3233 if (mapAddresses.find(addrAffected) != mapAddresses.end() && (mapAddresses[addrAffected] == 0 || mapAddresses[addrAffected] > wtx.nTime))
3234 mapAddresses[addrAffected] = wtx.nTime;
3242 void CWallet::ClearOrphans()
3244 list<uint256> orphans;
3247 for(map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
3249 const CWalletTx *wtx = &(*it).second;
3250 if((wtx->IsCoinBase() || wtx->IsCoinStake()) && !wtx->IsInMainChain())
3252 orphans.push_back(wtx->GetHash());
3256 for(list<uint256>::const_iterator it = orphans.begin(); it != orphans.end(); ++it)
3257 EraseFromWallet(*it);
3261 CWalletTx::CWalletTx()
3266 CWalletTx::CWalletTx(const CWallet *pwalletIn)
3271 CWalletTx::CWalletTx(const CWallet *pwalletIn, const CMerkleTx &txIn) : CMerkleTx(txIn)
3276 CWalletTx::CWalletTx(const CWallet *pwalletIn, const CTransaction &txIn) : CMerkleTx(txIn)
3281 void CWalletTx::Init(const CWallet *pwalletIn)
3283 pwallet = pwalletIn;
3287 fTimeReceivedIsTxTime = false;
3291 strFromAccount.clear();
3293 fDebitCached = false;
3294 fWatchDebitCached = false;
3295 fCreditCached = false;
3296 fWatchCreditCached = false;
3297 fAvailableCreditCached = false;
3298 fAvailableWatchCreditCached = false;
3299 fImmatureCreditCached = false;
3300 fImmatureWatchCreditCached = false;
3301 fChangeCached = false;
3303 nWatchDebitCached = 0;
3305 nWatchCreditCached = 0;
3306 nAvailableCreditCached = 0;
3307 nAvailableWatchCreditCached = 0;
3308 nImmatureCreditCached = 0;
3309 nImmatureWatchCreditCached = 0;
3314 COutput::COutput(const CWalletTx *txIn, int iIn, int nDepthIn, bool fSpendableIn)
3316 tx = txIn; i = iIn; nDepth = nDepthIn; fSpendable = fSpendableIn;
3319 string COutput::ToString() const
3321 return strprintf("COutput(%s, %d, %d, %d) [%s]", tx->GetHash().ToString().substr(0,10).c_str(), i, fSpendable, nDepth, FormatMoney(tx->vout[i].nValue).c_str());
3324 CAccount::CAccount()
3329 void CAccount::SetNull()
3331 vchPubKey = CPubKey();
3334 CAccountingEntry::CAccountingEntry()
3339 void CAccountingEntry::SetNull()
3344 strOtherAccount.clear();
3349 CWalletKey::CWalletKey(int64_t nExpires)
3351 nTimeCreated = (nExpires ? GetTime() : 0);
3352 nTimeExpires = nExpires;
3355 CKeyPool::CKeyPool()
3360 CKeyPool::CKeyPool(const CPubKey &vchPubKeyIn)
3363 vchPubKey = vchPubKeyIn;