Add new rpc call: abandontransaction
[bitcoinplatinum.git] / src / wallet / wallet.cpp
blob68e3b2fe5895ad3bd24d0fe492a9dc652c228317
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2015 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 #include "wallet/wallet.h"
8 #include "base58.h"
9 #include "checkpoints.h"
10 #include "chain.h"
11 #include "coincontrol.h"
12 #include "consensus/consensus.h"
13 #include "consensus/validation.h"
14 #include "key.h"
15 #include "keystore.h"
16 #include "main.h"
17 #include "net.h"
18 #include "policy/policy.h"
19 #include "primitives/block.h"
20 #include "primitives/transaction.h"
21 #include "script/script.h"
22 #include "script/sign.h"
23 #include "timedata.h"
24 #include "txmempool.h"
25 #include "util.h"
26 #include "utilmoneystr.h"
28 #include <assert.h>
30 #include <boost/algorithm/string/replace.hpp>
31 #include <boost/filesystem.hpp>
32 #include <boost/thread.hpp>
34 using namespace std;
36 /**
37 * Settings
39 CFeeRate payTxFee(DEFAULT_TRANSACTION_FEE);
40 CAmount maxTxFee = DEFAULT_TRANSACTION_MAXFEE;
41 unsigned int nTxConfirmTarget = DEFAULT_TX_CONFIRM_TARGET;
42 bool bSpendZeroConfChange = DEFAULT_SPEND_ZEROCONF_CHANGE;
43 bool fSendFreeTransactions = DEFAULT_SEND_FREE_TRANSACTIONS;
45 /**
46 * Fees smaller than this (in satoshi) are considered zero fee (for transaction creation)
47 * Override with -mintxfee
49 CFeeRate CWallet::minTxFee = CFeeRate(DEFAULT_TRANSACTION_MINFEE);
51 const uint256 CMerkleTx::ABANDON_HASH(uint256S("0000000000000000000000000000000000000000000000000000000000000001"));
53 /** @defgroup mapWallet
55 * @{
58 struct CompareValueOnly
60 bool operator()(const pair<CAmount, pair<const CWalletTx*, unsigned int> >& t1,
61 const pair<CAmount, pair<const CWalletTx*, unsigned int> >& t2) const
63 return t1.first < t2.first;
67 std::string COutput::ToString() const
69 return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString(), i, nDepth, FormatMoney(tx->vout[i].nValue));
72 const CWalletTx* CWallet::GetWalletTx(const uint256& hash) const
74 LOCK(cs_wallet);
75 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(hash);
76 if (it == mapWallet.end())
77 return NULL;
78 return &(it->second);
81 CPubKey CWallet::GenerateNewKey()
83 AssertLockHeld(cs_wallet); // mapKeyMetadata
84 bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
86 CKey secret;
87 secret.MakeNewKey(fCompressed);
89 // Compressed public keys were introduced in version 0.6.0
90 if (fCompressed)
91 SetMinVersion(FEATURE_COMPRPUBKEY);
93 CPubKey pubkey = secret.GetPubKey();
94 assert(secret.VerifyPubKey(pubkey));
96 // Create new metadata
97 int64_t nCreationTime = GetTime();
98 mapKeyMetadata[pubkey.GetID()] = CKeyMetadata(nCreationTime);
99 if (!nTimeFirstKey || nCreationTime < nTimeFirstKey)
100 nTimeFirstKey = nCreationTime;
102 if (!AddKeyPubKey(secret, pubkey))
103 throw std::runtime_error("CWallet::GenerateNewKey(): AddKey failed");
104 return pubkey;
107 bool CWallet::AddKeyPubKey(const CKey& secret, const CPubKey &pubkey)
109 AssertLockHeld(cs_wallet); // mapKeyMetadata
110 if (!CCryptoKeyStore::AddKeyPubKey(secret, pubkey))
111 return false;
113 // check if we need to remove from watch-only
114 CScript script;
115 script = GetScriptForDestination(pubkey.GetID());
116 if (HaveWatchOnly(script))
117 RemoveWatchOnly(script);
118 script = GetScriptForRawPubKey(pubkey);
119 if (HaveWatchOnly(script))
120 RemoveWatchOnly(script);
122 if (!fFileBacked)
123 return true;
124 if (!IsCrypted()) {
125 return CWalletDB(strWalletFile).WriteKey(pubkey,
126 secret.GetPrivKey(),
127 mapKeyMetadata[pubkey.GetID()]);
129 return true;
132 bool CWallet::AddCryptedKey(const CPubKey &vchPubKey,
133 const vector<unsigned char> &vchCryptedSecret)
135 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
136 return false;
137 if (!fFileBacked)
138 return true;
140 LOCK(cs_wallet);
141 if (pwalletdbEncryption)
142 return pwalletdbEncryption->WriteCryptedKey(vchPubKey,
143 vchCryptedSecret,
144 mapKeyMetadata[vchPubKey.GetID()]);
145 else
146 return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey,
147 vchCryptedSecret,
148 mapKeyMetadata[vchPubKey.GetID()]);
150 return false;
153 bool CWallet::LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &meta)
155 AssertLockHeld(cs_wallet); // mapKeyMetadata
156 if (meta.nCreateTime && (!nTimeFirstKey || meta.nCreateTime < nTimeFirstKey))
157 nTimeFirstKey = meta.nCreateTime;
159 mapKeyMetadata[pubkey.GetID()] = meta;
160 return true;
163 bool CWallet::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
165 return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret);
168 bool CWallet::AddCScript(const CScript& redeemScript)
170 if (!CCryptoKeyStore::AddCScript(redeemScript))
171 return false;
172 if (!fFileBacked)
173 return true;
174 return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript);
177 bool CWallet::LoadCScript(const CScript& redeemScript)
179 /* A sanity check was added in pull #3843 to avoid adding redeemScripts
180 * that never can be redeemed. However, old wallets may still contain
181 * these. Do not add them to the wallet and warn. */
182 if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
184 std::string strAddr = CBitcoinAddress(CScriptID(redeemScript)).ToString();
185 LogPrintf("%s: Warning: This wallet contains a redeemScript of size %i which exceeds maximum size %i thus can never be redeemed. Do not use address %s.\n",
186 __func__, redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr);
187 return true;
190 return CCryptoKeyStore::AddCScript(redeemScript);
193 bool CWallet::AddWatchOnly(const CScript &dest)
195 if (!CCryptoKeyStore::AddWatchOnly(dest))
196 return false;
197 nTimeFirstKey = 1; // No birthday information for watch-only keys.
198 NotifyWatchonlyChanged(true);
199 if (!fFileBacked)
200 return true;
201 return CWalletDB(strWalletFile).WriteWatchOnly(dest);
204 bool CWallet::RemoveWatchOnly(const CScript &dest)
206 AssertLockHeld(cs_wallet);
207 if (!CCryptoKeyStore::RemoveWatchOnly(dest))
208 return false;
209 if (!HaveWatchOnly())
210 NotifyWatchonlyChanged(false);
211 if (fFileBacked)
212 if (!CWalletDB(strWalletFile).EraseWatchOnly(dest))
213 return false;
215 return true;
218 bool CWallet::LoadWatchOnly(const CScript &dest)
220 return CCryptoKeyStore::AddWatchOnly(dest);
223 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
225 CCrypter crypter;
226 CKeyingMaterial vMasterKey;
229 LOCK(cs_wallet);
230 BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
232 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
233 return false;
234 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
235 continue; // try another master key
236 if (CCryptoKeyStore::Unlock(vMasterKey))
237 return true;
240 return false;
243 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
245 bool fWasLocked = IsLocked();
248 LOCK(cs_wallet);
249 Lock();
251 CCrypter crypter;
252 CKeyingMaterial vMasterKey;
253 BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
255 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
256 return false;
257 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
258 return false;
259 if (CCryptoKeyStore::Unlock(vMasterKey))
261 int64_t nStartTime = GetTimeMillis();
262 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
263 pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
265 nStartTime = GetTimeMillis();
266 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
267 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
269 if (pMasterKey.second.nDeriveIterations < 25000)
270 pMasterKey.second.nDeriveIterations = 25000;
272 LogPrintf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
274 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
275 return false;
276 if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
277 return false;
278 CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
279 if (fWasLocked)
280 Lock();
281 return true;
286 return false;
289 void CWallet::SetBestChain(const CBlockLocator& loc)
291 CWalletDB walletdb(strWalletFile);
292 walletdb.WriteBestBlock(loc);
295 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
297 LOCK(cs_wallet); // nWalletVersion
298 if (nWalletVersion >= nVersion)
299 return true;
301 // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
302 if (fExplicit && nVersion > nWalletMaxVersion)
303 nVersion = FEATURE_LATEST;
305 nWalletVersion = nVersion;
307 if (nVersion > nWalletMaxVersion)
308 nWalletMaxVersion = nVersion;
310 if (fFileBacked)
312 CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile);
313 if (nWalletVersion > 40000)
314 pwalletdb->WriteMinVersion(nWalletVersion);
315 if (!pwalletdbIn)
316 delete pwalletdb;
319 return true;
322 bool CWallet::SetMaxVersion(int nVersion)
324 LOCK(cs_wallet); // nWalletVersion, nWalletMaxVersion
325 // cannot downgrade below current version
326 if (nWalletVersion > nVersion)
327 return false;
329 nWalletMaxVersion = nVersion;
331 return true;
334 set<uint256> CWallet::GetConflicts(const uint256& txid) const
336 set<uint256> result;
337 AssertLockHeld(cs_wallet);
339 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(txid);
340 if (it == mapWallet.end())
341 return result;
342 const CWalletTx& wtx = it->second;
344 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
346 BOOST_FOREACH(const CTxIn& txin, wtx.vin)
348 if (mapTxSpends.count(txin.prevout) <= 1)
349 continue; // No conflict if zero or one spends
350 range = mapTxSpends.equal_range(txin.prevout);
351 for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
352 result.insert(it->second);
354 return result;
357 void CWallet::Flush(bool shutdown)
359 bitdb.Flush(shutdown);
362 bool CWallet::Verify(const string& walletFile, string& warningString, string& errorString)
364 if (!bitdb.Open(GetDataDir()))
366 // try moving the database env out of the way
367 boost::filesystem::path pathDatabase = GetDataDir() / "database";
368 boost::filesystem::path pathDatabaseBak = GetDataDir() / strprintf("database.%d.bak", GetTime());
369 try {
370 boost::filesystem::rename(pathDatabase, pathDatabaseBak);
371 LogPrintf("Moved old %s to %s. Retrying.\n", pathDatabase.string(), pathDatabaseBak.string());
372 } catch (const boost::filesystem::filesystem_error&) {
373 // failure is ok (well, not really, but it's not worse than what we started with)
376 // try again
377 if (!bitdb.Open(GetDataDir())) {
378 // if it still fails, it probably means we can't even create the database env
379 string msg = strprintf(_("Error initializing wallet database environment %s!"), GetDataDir());
380 errorString += msg;
381 return true;
385 if (GetBoolArg("-salvagewallet", false))
387 // Recover readable keypairs:
388 if (!CWalletDB::Recover(bitdb, walletFile, true))
389 return false;
392 if (boost::filesystem::exists(GetDataDir() / walletFile))
394 CDBEnv::VerifyResult r = bitdb.Verify(walletFile, CWalletDB::Recover);
395 if (r == CDBEnv::RECOVER_OK)
397 warningString += strprintf(_("Warning: wallet.dat corrupt, data salvaged!"
398 " Original wallet.dat saved as wallet.{timestamp}.bak in %s; if"
399 " your balance or transactions are incorrect you should"
400 " restore from a backup."), GetDataDir());
402 if (r == CDBEnv::RECOVER_FAIL)
403 errorString += _("wallet.dat corrupt, salvage failed");
406 return true;
409 void CWallet::SyncMetaData(pair<TxSpends::iterator, TxSpends::iterator> range)
411 // We want all the wallet transactions in range to have the same metadata as
412 // the oldest (smallest nOrderPos).
413 // So: find smallest nOrderPos:
415 int nMinOrderPos = std::numeric_limits<int>::max();
416 const CWalletTx* copyFrom = NULL;
417 for (TxSpends::iterator it = range.first; it != range.second; ++it)
419 const uint256& hash = it->second;
420 int n = mapWallet[hash].nOrderPos;
421 if (n < nMinOrderPos)
423 nMinOrderPos = n;
424 copyFrom = &mapWallet[hash];
427 // Now copy data from copyFrom to rest:
428 for (TxSpends::iterator it = range.first; it != range.second; ++it)
430 const uint256& hash = it->second;
431 CWalletTx* copyTo = &mapWallet[hash];
432 if (copyFrom == copyTo) continue;
433 if (!copyFrom->IsEquivalentTo(*copyTo)) continue;
434 copyTo->mapValue = copyFrom->mapValue;
435 copyTo->vOrderForm = copyFrom->vOrderForm;
436 // fTimeReceivedIsTxTime not copied on purpose
437 // nTimeReceived not copied on purpose
438 copyTo->nTimeSmart = copyFrom->nTimeSmart;
439 copyTo->fFromMe = copyFrom->fFromMe;
440 copyTo->strFromAccount = copyFrom->strFromAccount;
441 // nOrderPos not copied on purpose
442 // cached members not copied on purpose
447 * Outpoint is spent if any non-conflicted transaction
448 * spends it:
450 bool CWallet::IsSpent(const uint256& hash, unsigned int n) const
452 const COutPoint outpoint(hash, n);
453 pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
454 range = mapTxSpends.equal_range(outpoint);
456 for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
458 const uint256& wtxid = it->second;
459 std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
460 if (mit != mapWallet.end()) {
461 int depth = mit->second.GetDepthInMainChain();
462 if (depth > 0 || (depth == 0 && !mit->second.isAbandoned()))
463 return true; // Spent
466 return false;
469 void CWallet::AddToSpends(const COutPoint& outpoint, const uint256& wtxid)
471 mapTxSpends.insert(make_pair(outpoint, wtxid));
473 pair<TxSpends::iterator, TxSpends::iterator> range;
474 range = mapTxSpends.equal_range(outpoint);
475 SyncMetaData(range);
479 void CWallet::AddToSpends(const uint256& wtxid)
481 assert(mapWallet.count(wtxid));
482 CWalletTx& thisTx = mapWallet[wtxid];
483 if (thisTx.IsCoinBase()) // Coinbases don't spend anything!
484 return;
486 BOOST_FOREACH(const CTxIn& txin, thisTx.vin)
487 AddToSpends(txin.prevout, wtxid);
490 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
492 if (IsCrypted())
493 return false;
495 CKeyingMaterial vMasterKey;
496 RandAddSeedPerfmon();
498 vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
499 GetRandBytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
501 CMasterKey kMasterKey;
502 RandAddSeedPerfmon();
504 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
505 GetRandBytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
507 CCrypter crypter;
508 int64_t nStartTime = GetTimeMillis();
509 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
510 kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
512 nStartTime = GetTimeMillis();
513 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
514 kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
516 if (kMasterKey.nDeriveIterations < 25000)
517 kMasterKey.nDeriveIterations = 25000;
519 LogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
521 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
522 return false;
523 if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
524 return false;
527 LOCK(cs_wallet);
528 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
529 if (fFileBacked)
531 assert(!pwalletdbEncryption);
532 pwalletdbEncryption = new CWalletDB(strWalletFile);
533 if (!pwalletdbEncryption->TxnBegin()) {
534 delete pwalletdbEncryption;
535 pwalletdbEncryption = NULL;
536 return false;
538 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
541 if (!EncryptKeys(vMasterKey))
543 if (fFileBacked) {
544 pwalletdbEncryption->TxnAbort();
545 delete pwalletdbEncryption;
547 // We now probably have half of our keys encrypted in memory, and half not...
548 // die and let the user reload the unencrypted wallet.
549 assert(false);
552 // Encryption was introduced in version 0.4.0
553 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
555 if (fFileBacked)
557 if (!pwalletdbEncryption->TxnCommit()) {
558 delete pwalletdbEncryption;
559 // We now have keys encrypted in memory, but not on disk...
560 // die to avoid confusion and let the user reload the unencrypted wallet.
561 assert(false);
564 delete pwalletdbEncryption;
565 pwalletdbEncryption = NULL;
568 Lock();
569 Unlock(strWalletPassphrase);
570 NewKeyPool();
571 Lock();
573 // Need to completely rewrite the wallet file; if we don't, bdb might keep
574 // bits of the unencrypted private key in slack space in the database file.
575 CDB::Rewrite(strWalletFile);
578 NotifyStatusChanged(this);
580 return true;
583 int64_t CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
585 AssertLockHeld(cs_wallet); // nOrderPosNext
586 int64_t nRet = nOrderPosNext++;
587 if (pwalletdb) {
588 pwalletdb->WriteOrderPosNext(nOrderPosNext);
589 } else {
590 CWalletDB(strWalletFile).WriteOrderPosNext(nOrderPosNext);
592 return nRet;
595 void CWallet::MarkDirty()
598 LOCK(cs_wallet);
599 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
600 item.second.MarkDirty();
604 bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFromLoadWallet, CWalletDB* pwalletdb)
606 uint256 hash = wtxIn.GetHash();
608 if (fFromLoadWallet)
610 mapWallet[hash] = wtxIn;
611 CWalletTx& wtx = mapWallet[hash];
612 wtx.BindWallet(this);
613 wtxOrdered.insert(make_pair(wtx.nOrderPos, TxPair(&wtx, (CAccountingEntry*)0)));
614 AddToSpends(hash);
615 BOOST_FOREACH(const CTxIn& txin, wtx.vin) {
616 if (mapWallet.count(txin.prevout.hash)) {
617 CWalletTx& prevtx = mapWallet[txin.prevout.hash];
618 if (prevtx.nIndex == -1 && !prevtx.hashUnset()) {
619 MarkConflicted(prevtx.hashBlock, wtx.GetHash());
624 else
626 LOCK(cs_wallet);
627 // Inserts only if not already there, returns tx inserted or tx found
628 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
629 CWalletTx& wtx = (*ret.first).second;
630 wtx.BindWallet(this);
631 bool fInsertedNew = ret.second;
632 if (fInsertedNew)
634 wtx.nTimeReceived = GetAdjustedTime();
635 wtx.nOrderPos = IncOrderPosNext(pwalletdb);
636 wtxOrdered.insert(make_pair(wtx.nOrderPos, TxPair(&wtx, (CAccountingEntry*)0)));
638 wtx.nTimeSmart = wtx.nTimeReceived;
639 if (!wtxIn.hashUnset())
641 if (mapBlockIndex.count(wtxIn.hashBlock))
643 int64_t latestNow = wtx.nTimeReceived;
644 int64_t latestEntry = 0;
646 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
647 int64_t latestTolerated = latestNow + 300;
648 const TxItems & txOrdered = wtxOrdered;
649 for (TxItems::const_reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
651 CWalletTx *const pwtx = (*it).second.first;
652 if (pwtx == &wtx)
653 continue;
654 CAccountingEntry *const pacentry = (*it).second.second;
655 int64_t nSmartTime;
656 if (pwtx)
658 nSmartTime = pwtx->nTimeSmart;
659 if (!nSmartTime)
660 nSmartTime = pwtx->nTimeReceived;
662 else
663 nSmartTime = pacentry->nTime;
664 if (nSmartTime <= latestTolerated)
666 latestEntry = nSmartTime;
667 if (nSmartTime > latestNow)
668 latestNow = nSmartTime;
669 break;
674 int64_t blocktime = mapBlockIndex[wtxIn.hashBlock]->GetBlockTime();
675 wtx.nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
677 else
678 LogPrintf("AddToWallet(): found %s in block %s not in index\n",
679 wtxIn.GetHash().ToString(),
680 wtxIn.hashBlock.ToString());
682 AddToSpends(hash);
685 bool fUpdated = false;
686 if (!fInsertedNew)
688 // Merge
689 if (!wtxIn.hashUnset() && wtxIn.hashBlock != wtx.hashBlock)
691 wtx.hashBlock = wtxIn.hashBlock;
692 fUpdated = true;
694 // If no longer abandoned, update
695 if (wtxIn.hashBlock.IsNull() && wtx.isAbandoned())
697 wtx.hashBlock = wtxIn.hashBlock;
698 fUpdated = true;
700 if (wtxIn.nIndex != -1 && (wtxIn.nIndex != wtx.nIndex))
702 wtx.nIndex = wtxIn.nIndex;
703 fUpdated = true;
705 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
707 wtx.fFromMe = wtxIn.fFromMe;
708 fUpdated = true;
712 //// debug print
713 LogPrintf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
715 // Write to disk
716 if (fInsertedNew || fUpdated)
717 if (!wtx.WriteToDisk(pwalletdb))
718 return false;
720 // Break debit/credit balance caches:
721 wtx.MarkDirty();
723 // Notify UI of new or updated transaction
724 NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
726 // notify an external script when a wallet transaction comes in or is updated
727 std::string strCmd = GetArg("-walletnotify", "");
729 if ( !strCmd.empty())
731 boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
732 boost::thread t(runCommand, strCmd); // thread runs free
736 return true;
740 * Add a transaction to the wallet, or update it.
741 * pblock is optional, but should be provided if the transaction is known to be in a block.
742 * If fUpdate is true, existing transactions will be updated.
744 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate)
747 AssertLockHeld(cs_wallet);
749 if (pblock) {
750 BOOST_FOREACH(const CTxIn& txin, tx.vin) {
751 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range = mapTxSpends.equal_range(txin.prevout);
752 while (range.first != range.second) {
753 if (range.first->second != tx.GetHash()) {
754 LogPrintf("Transaction %s (in block %s) conflicts with wallet transaction %s (both spend %s:%i)\n", tx.GetHash().ToString(), pblock->GetHash().ToString(), range.first->second.ToString(), range.first->first.hash.ToString(), range.first->first.n);
755 MarkConflicted(pblock->GetHash(), range.first->second);
757 range.first++;
762 bool fExisted = mapWallet.count(tx.GetHash()) != 0;
763 if (fExisted && !fUpdate) return false;
764 if (fExisted || IsMine(tx) || IsFromMe(tx))
766 CWalletTx wtx(this,tx);
768 // Get merkle branch if transaction was found in a block
769 if (pblock)
770 wtx.SetMerkleBranch(*pblock);
772 // Do not flush the wallet here for performance reasons
773 // this is safe, as in case of a crash, we rescan the necessary blocks on startup through our SetBestChain-mechanism
774 CWalletDB walletdb(strWalletFile, "r+", false);
776 return AddToWallet(wtx, false, &walletdb);
779 return false;
782 bool CWallet::AbandonTransaction(const uint256& hashTx)
784 LOCK2(cs_main, cs_wallet);
786 // Do not flush the wallet here for performance reasons
787 CWalletDB walletdb(strWalletFile, "r+", false);
789 std::set<uint256> todo;
790 std::set<uint256> done;
792 // Can't mark abandoned if confirmed or in mempool
793 assert(mapWallet.count(hashTx));
794 CWalletTx& origtx = mapWallet[hashTx];
795 if (origtx.GetDepthInMainChain() > 0 || origtx.InMempool()) {
796 return false;
799 todo.insert(hashTx);
801 while (!todo.empty()) {
802 uint256 now = *todo.begin();
803 todo.erase(now);
804 done.insert(now);
805 assert(mapWallet.count(now));
806 CWalletTx& wtx = mapWallet[now];
807 int currentconfirm = wtx.GetDepthInMainChain();
808 // If the orig tx was not in block, none of its spends can be
809 assert(currentconfirm <= 0);
810 // if (currentconfirm < 0) {Tx and spends are already conflicted, no need to abandon}
811 if (currentconfirm == 0 && !wtx.isAbandoned()) {
812 // If the orig tx was not in block/mempool, none of its spends can be in mempool
813 assert(!wtx.InMempool());
814 wtx.nIndex = -1;
815 wtx.setAbandoned();
816 wtx.MarkDirty();
817 wtx.WriteToDisk(&walletdb);
818 // Iterate over all its outputs, and mark transactions in the wallet that spend them abandoned too
819 TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(hashTx, 0));
820 while (iter != mapTxSpends.end() && iter->first.hash == now) {
821 if (!done.count(iter->second)) {
822 todo.insert(iter->second);
824 iter++;
826 // If a transaction changes 'conflicted' state, that changes the balance
827 // available of the outputs it spends. So force those to be recomputed
828 BOOST_FOREACH(const CTxIn& txin, wtx.vin)
830 if (mapWallet.count(txin.prevout.hash))
831 mapWallet[txin.prevout.hash].MarkDirty();
836 return true;
839 void CWallet::MarkConflicted(const uint256& hashBlock, const uint256& hashTx)
841 LOCK2(cs_main, cs_wallet);
843 CBlockIndex* pindex;
844 assert(mapBlockIndex.count(hashBlock));
845 pindex = mapBlockIndex[hashBlock];
846 int conflictconfirms = 0;
847 if (chainActive.Contains(pindex)) {
848 conflictconfirms = -(chainActive.Height() - pindex->nHeight + 1);
850 assert(conflictconfirms < 0);
852 // Do not flush the wallet here for performance reasons
853 CWalletDB walletdb(strWalletFile, "r+", false);
855 std::set<uint256> todo;
856 std::set<uint256> done;
858 todo.insert(hashTx);
860 while (!todo.empty()) {
861 uint256 now = *todo.begin();
862 todo.erase(now);
863 done.insert(now);
864 assert(mapWallet.count(now));
865 CWalletTx& wtx = mapWallet[now];
866 int currentconfirm = wtx.GetDepthInMainChain();
867 if (conflictconfirms < currentconfirm) {
868 // Block is 'more conflicted' than current confirm; update.
869 // Mark transaction as conflicted with this block.
870 wtx.nIndex = -1;
871 wtx.hashBlock = hashBlock;
872 wtx.MarkDirty();
873 wtx.WriteToDisk(&walletdb);
874 // Iterate over all its outputs, and mark transactions in the wallet that spend them conflicted too
875 TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(now, 0));
876 while (iter != mapTxSpends.end() && iter->first.hash == now) {
877 if (!done.count(iter->second)) {
878 todo.insert(iter->second);
880 iter++;
882 // If a transaction changes 'conflicted' state, that changes the balance
883 // available of the outputs it spends. So force those to be recomputed
884 BOOST_FOREACH(const CTxIn& txin, wtx.vin)
886 if (mapWallet.count(txin.prevout.hash))
887 mapWallet[txin.prevout.hash].MarkDirty();
893 void CWallet::SyncTransaction(const CTransaction& tx, const CBlock* pblock)
895 LOCK2(cs_main, cs_wallet);
897 if (!AddToWalletIfInvolvingMe(tx, pblock, true))
898 return; // Not one of ours
900 // If a transaction changes 'conflicted' state, that changes the balance
901 // available of the outputs it spends. So force those to be
902 // recomputed, also:
903 BOOST_FOREACH(const CTxIn& txin, tx.vin)
905 if (mapWallet.count(txin.prevout.hash))
906 mapWallet[txin.prevout.hash].MarkDirty();
911 isminetype CWallet::IsMine(const CTxIn &txin) const
914 LOCK(cs_wallet);
915 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
916 if (mi != mapWallet.end())
918 const CWalletTx& prev = (*mi).second;
919 if (txin.prevout.n < prev.vout.size())
920 return IsMine(prev.vout[txin.prevout.n]);
923 return ISMINE_NO;
926 CAmount CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
929 LOCK(cs_wallet);
930 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
931 if (mi != mapWallet.end())
933 const CWalletTx& prev = (*mi).second;
934 if (txin.prevout.n < prev.vout.size())
935 if (IsMine(prev.vout[txin.prevout.n]) & filter)
936 return prev.vout[txin.prevout.n].nValue;
939 return 0;
942 isminetype CWallet::IsMine(const CTxOut& txout) const
944 return ::IsMine(*this, txout.scriptPubKey);
947 CAmount CWallet::GetCredit(const CTxOut& txout, const isminefilter& filter) const
949 if (!MoneyRange(txout.nValue))
950 throw std::runtime_error("CWallet::GetCredit(): value out of range");
951 return ((IsMine(txout) & filter) ? txout.nValue : 0);
954 bool CWallet::IsChange(const CTxOut& txout) const
956 // TODO: fix handling of 'change' outputs. The assumption is that any
957 // payment to a script that is ours, but is not in the address book
958 // is change. That assumption is likely to break when we implement multisignature
959 // wallets that return change back into a multi-signature-protected address;
960 // a better way of identifying which outputs are 'the send' and which are
961 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
962 // which output, if any, was change).
963 if (::IsMine(*this, txout.scriptPubKey))
965 CTxDestination address;
966 if (!ExtractDestination(txout.scriptPubKey, address))
967 return true;
969 LOCK(cs_wallet);
970 if (!mapAddressBook.count(address))
971 return true;
973 return false;
976 CAmount CWallet::GetChange(const CTxOut& txout) const
978 if (!MoneyRange(txout.nValue))
979 throw std::runtime_error("CWallet::GetChange(): value out of range");
980 return (IsChange(txout) ? txout.nValue : 0);
983 bool CWallet::IsMine(const CTransaction& tx) const
985 BOOST_FOREACH(const CTxOut& txout, tx.vout)
986 if (IsMine(txout))
987 return true;
988 return false;
991 bool CWallet::IsFromMe(const CTransaction& tx) const
993 return (GetDebit(tx, ISMINE_ALL) > 0);
996 CAmount CWallet::GetDebit(const CTransaction& tx, const isminefilter& filter) const
998 CAmount nDebit = 0;
999 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1001 nDebit += GetDebit(txin, filter);
1002 if (!MoneyRange(nDebit))
1003 throw std::runtime_error("CWallet::GetDebit(): value out of range");
1005 return nDebit;
1008 CAmount CWallet::GetCredit(const CTransaction& tx, const isminefilter& filter) const
1010 CAmount nCredit = 0;
1011 BOOST_FOREACH(const CTxOut& txout, tx.vout)
1013 nCredit += GetCredit(txout, filter);
1014 if (!MoneyRange(nCredit))
1015 throw std::runtime_error("CWallet::GetCredit(): value out of range");
1017 return nCredit;
1020 CAmount CWallet::GetChange(const CTransaction& tx) const
1022 CAmount nChange = 0;
1023 BOOST_FOREACH(const CTxOut& txout, tx.vout)
1025 nChange += GetChange(txout);
1026 if (!MoneyRange(nChange))
1027 throw std::runtime_error("CWallet::GetChange(): value out of range");
1029 return nChange;
1032 int64_t CWalletTx::GetTxTime() const
1034 int64_t n = nTimeSmart;
1035 return n ? n : nTimeReceived;
1038 int CWalletTx::GetRequestCount() const
1040 // Returns -1 if it wasn't being tracked
1041 int nRequests = -1;
1043 LOCK(pwallet->cs_wallet);
1044 if (IsCoinBase())
1046 // Generated block
1047 if (!hashUnset())
1049 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
1050 if (mi != pwallet->mapRequestCount.end())
1051 nRequests = (*mi).second;
1054 else
1056 // Did anyone request this transaction?
1057 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
1058 if (mi != pwallet->mapRequestCount.end())
1060 nRequests = (*mi).second;
1062 // How about the block it's in?
1063 if (nRequests == 0 && !hashUnset())
1065 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
1066 if (mi != pwallet->mapRequestCount.end())
1067 nRequests = (*mi).second;
1068 else
1069 nRequests = 1; // If it's in someone else's block it must have got out
1074 return nRequests;
1077 void CWalletTx::GetAmounts(list<COutputEntry>& listReceived,
1078 list<COutputEntry>& listSent, CAmount& nFee, string& strSentAccount, const isminefilter& filter) const
1080 nFee = 0;
1081 listReceived.clear();
1082 listSent.clear();
1083 strSentAccount = strFromAccount;
1085 // Compute fee:
1086 CAmount nDebit = GetDebit(filter);
1087 if (nDebit > 0) // debit>0 means we signed/sent this transaction
1089 CAmount nValueOut = GetValueOut();
1090 nFee = nDebit - nValueOut;
1093 // Sent/received.
1094 for (unsigned int i = 0; i < vout.size(); ++i)
1096 const CTxOut& txout = vout[i];
1097 isminetype fIsMine = pwallet->IsMine(txout);
1098 // Only need to handle txouts if AT LEAST one of these is true:
1099 // 1) they debit from us (sent)
1100 // 2) the output is to us (received)
1101 if (nDebit > 0)
1103 // Don't report 'change' txouts
1104 if (pwallet->IsChange(txout))
1105 continue;
1107 else if (!(fIsMine & filter))
1108 continue;
1110 // In either case, we need to get the destination address
1111 CTxDestination address;
1113 if (!ExtractDestination(txout.scriptPubKey, address) && !txout.scriptPubKey.IsUnspendable())
1115 LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
1116 this->GetHash().ToString());
1117 address = CNoDestination();
1120 COutputEntry output = {address, txout.nValue, (int)i};
1122 // If we are debited by the transaction, add the output as a "sent" entry
1123 if (nDebit > 0)
1124 listSent.push_back(output);
1126 // If we are receiving the output, add it as a "received" entry
1127 if (fIsMine & filter)
1128 listReceived.push_back(output);
1133 void CWalletTx::GetAccountAmounts(const string& strAccount, CAmount& nReceived,
1134 CAmount& nSent, CAmount& nFee, const isminefilter& filter) const
1136 nReceived = nSent = nFee = 0;
1138 CAmount allFee;
1139 string strSentAccount;
1140 list<COutputEntry> listReceived;
1141 list<COutputEntry> listSent;
1142 GetAmounts(listReceived, listSent, allFee, strSentAccount, filter);
1144 if (strAccount == strSentAccount)
1146 BOOST_FOREACH(const COutputEntry& s, listSent)
1147 nSent += s.amount;
1148 nFee = allFee;
1151 LOCK(pwallet->cs_wallet);
1152 BOOST_FOREACH(const COutputEntry& r, listReceived)
1154 if (pwallet->mapAddressBook.count(r.destination))
1156 map<CTxDestination, CAddressBookData>::const_iterator mi = pwallet->mapAddressBook.find(r.destination);
1157 if (mi != pwallet->mapAddressBook.end() && (*mi).second.name == strAccount)
1158 nReceived += r.amount;
1160 else if (strAccount.empty())
1162 nReceived += r.amount;
1169 bool CWalletTx::WriteToDisk(CWalletDB *pwalletdb)
1171 return pwalletdb->WriteTx(GetHash(), *this);
1175 * Scan the block chain (starting in pindexStart) for transactions
1176 * from or to us. If fUpdate is true, found transactions that already
1177 * exist in the wallet will be updated.
1179 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
1181 int ret = 0;
1182 int64_t nNow = GetTime();
1183 const CChainParams& chainParams = Params();
1185 CBlockIndex* pindex = pindexStart;
1187 LOCK2(cs_main, cs_wallet);
1189 // no need to read and scan block, if block was created before
1190 // our wallet birthday (as adjusted for block time variability)
1191 while (pindex && nTimeFirstKey && (pindex->GetBlockTime() < (nTimeFirstKey - 7200)))
1192 pindex = chainActive.Next(pindex);
1194 ShowProgress(_("Rescanning..."), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup
1195 double dProgressStart = Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), pindex, false);
1196 double dProgressTip = Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), chainActive.Tip(), false);
1197 while (pindex)
1199 if (pindex->nHeight % 100 == 0 && dProgressTip - dProgressStart > 0.0)
1200 ShowProgress(_("Rescanning..."), std::max(1, std::min(99, (int)((Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), pindex, false) - dProgressStart) / (dProgressTip - dProgressStart) * 100))));
1202 CBlock block;
1203 ReadBlockFromDisk(block, pindex, Params().GetConsensus());
1204 BOOST_FOREACH(CTransaction& tx, block.vtx)
1206 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
1207 ret++;
1209 pindex = chainActive.Next(pindex);
1210 if (GetTime() >= nNow + 60) {
1211 nNow = GetTime();
1212 LogPrintf("Still rescanning. At block %d. Progress=%f\n", pindex->nHeight, Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), pindex));
1215 ShowProgress(_("Rescanning..."), 100); // hide progress dialog in GUI
1217 return ret;
1220 void CWallet::ReacceptWalletTransactions()
1222 // If transactions aren't being broadcasted, don't let them into local mempool either
1223 if (!fBroadcastTransactions)
1224 return;
1225 LOCK2(cs_main, cs_wallet);
1226 std::map<int64_t, CWalletTx*> mapSorted;
1228 // Sort pending wallet transactions based on their initial wallet insertion order
1229 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1231 const uint256& wtxid = item.first;
1232 CWalletTx& wtx = item.second;
1233 assert(wtx.GetHash() == wtxid);
1235 int nDepth = wtx.GetDepthInMainChain();
1237 if (!wtx.IsCoinBase() && (nDepth == 0 && !wtx.isAbandoned())) {
1238 mapSorted.insert(std::make_pair(wtx.nOrderPos, &wtx));
1242 // Try to add wallet transactions to memory pool
1243 BOOST_FOREACH(PAIRTYPE(const int64_t, CWalletTx*)& item, mapSorted)
1245 CWalletTx& wtx = *(item.second);
1247 LOCK(mempool.cs);
1248 wtx.AcceptToMemoryPool(false);
1252 bool CWalletTx::RelayWalletTransaction()
1254 assert(pwallet->GetBroadcastTransactions());
1255 if (!IsCoinBase())
1257 if (GetDepthInMainChain() == 0 && !isAbandoned()) {
1258 LogPrintf("Relaying wtx %s\n", GetHash().ToString());
1259 RelayTransaction((CTransaction)*this);
1260 return true;
1263 return false;
1266 set<uint256> CWalletTx::GetConflicts() const
1268 set<uint256> result;
1269 if (pwallet != NULL)
1271 uint256 myHash = GetHash();
1272 result = pwallet->GetConflicts(myHash);
1273 result.erase(myHash);
1275 return result;
1278 CAmount CWalletTx::GetDebit(const isminefilter& filter) const
1280 if (vin.empty())
1281 return 0;
1283 CAmount debit = 0;
1284 if(filter & ISMINE_SPENDABLE)
1286 if (fDebitCached)
1287 debit += nDebitCached;
1288 else
1290 nDebitCached = pwallet->GetDebit(*this, ISMINE_SPENDABLE);
1291 fDebitCached = true;
1292 debit += nDebitCached;
1295 if(filter & ISMINE_WATCH_ONLY)
1297 if(fWatchDebitCached)
1298 debit += nWatchDebitCached;
1299 else
1301 nWatchDebitCached = pwallet->GetDebit(*this, ISMINE_WATCH_ONLY);
1302 fWatchDebitCached = true;
1303 debit += nWatchDebitCached;
1306 return debit;
1309 CAmount CWalletTx::GetCredit(const isminefilter& filter) const
1311 // Must wait until coinbase is safely deep enough in the chain before valuing it
1312 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1313 return 0;
1315 int64_t credit = 0;
1316 if (filter & ISMINE_SPENDABLE)
1318 // GetBalance can assume transactions in mapWallet won't change
1319 if (fCreditCached)
1320 credit += nCreditCached;
1321 else
1323 nCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
1324 fCreditCached = true;
1325 credit += nCreditCached;
1328 if (filter & ISMINE_WATCH_ONLY)
1330 if (fWatchCreditCached)
1331 credit += nWatchCreditCached;
1332 else
1334 nWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
1335 fWatchCreditCached = true;
1336 credit += nWatchCreditCached;
1339 return credit;
1342 CAmount CWalletTx::GetImmatureCredit(bool fUseCache) const
1344 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1346 if (fUseCache && fImmatureCreditCached)
1347 return nImmatureCreditCached;
1348 nImmatureCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
1349 fImmatureCreditCached = true;
1350 return nImmatureCreditCached;
1353 return 0;
1356 CAmount CWalletTx::GetAvailableCredit(bool fUseCache) const
1358 if (pwallet == 0)
1359 return 0;
1361 // Must wait until coinbase is safely deep enough in the chain before valuing it
1362 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1363 return 0;
1365 if (fUseCache && fAvailableCreditCached)
1366 return nAvailableCreditCached;
1368 CAmount nCredit = 0;
1369 uint256 hashTx = GetHash();
1370 for (unsigned int i = 0; i < vout.size(); i++)
1372 if (!pwallet->IsSpent(hashTx, i))
1374 const CTxOut &txout = vout[i];
1375 nCredit += pwallet->GetCredit(txout, ISMINE_SPENDABLE);
1376 if (!MoneyRange(nCredit))
1377 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
1381 nAvailableCreditCached = nCredit;
1382 fAvailableCreditCached = true;
1383 return nCredit;
1386 CAmount CWalletTx::GetImmatureWatchOnlyCredit(const bool& fUseCache) const
1388 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1390 if (fUseCache && fImmatureWatchCreditCached)
1391 return nImmatureWatchCreditCached;
1392 nImmatureWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
1393 fImmatureWatchCreditCached = true;
1394 return nImmatureWatchCreditCached;
1397 return 0;
1400 CAmount CWalletTx::GetAvailableWatchOnlyCredit(const bool& fUseCache) const
1402 if (pwallet == 0)
1403 return 0;
1405 // Must wait until coinbase is safely deep enough in the chain before valuing it
1406 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1407 return 0;
1409 if (fUseCache && fAvailableWatchCreditCached)
1410 return nAvailableWatchCreditCached;
1412 CAmount nCredit = 0;
1413 for (unsigned int i = 0; i < vout.size(); i++)
1415 if (!pwallet->IsSpent(GetHash(), i))
1417 const CTxOut &txout = vout[i];
1418 nCredit += pwallet->GetCredit(txout, ISMINE_WATCH_ONLY);
1419 if (!MoneyRange(nCredit))
1420 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
1424 nAvailableWatchCreditCached = nCredit;
1425 fAvailableWatchCreditCached = true;
1426 return nCredit;
1429 CAmount CWalletTx::GetChange() const
1431 if (fChangeCached)
1432 return nChangeCached;
1433 nChangeCached = pwallet->GetChange(*this);
1434 fChangeCached = true;
1435 return nChangeCached;
1438 bool CWalletTx::InMempool() const
1440 LOCK(mempool.cs);
1441 if (mempool.exists(GetHash())) {
1442 return true;
1444 return false;
1447 bool CWalletTx::IsTrusted() const
1449 // Quick answer in most cases
1450 if (!CheckFinalTx(*this))
1451 return false;
1452 int nDepth = GetDepthInMainChain();
1453 if (nDepth >= 1)
1454 return true;
1455 if (nDepth < 0)
1456 return false;
1457 if (!bSpendZeroConfChange || !IsFromMe(ISMINE_ALL)) // using wtx's cached debit
1458 return false;
1460 // Don't trust unconfirmed transactions from us unless they are in the mempool.
1461 if (!InMempool())
1462 return false;
1464 // Trusted if all inputs are from us and are in the mempool:
1465 BOOST_FOREACH(const CTxIn& txin, vin)
1467 // Transactions not sent by us: not trusted
1468 const CWalletTx* parent = pwallet->GetWalletTx(txin.prevout.hash);
1469 if (parent == NULL)
1470 return false;
1471 const CTxOut& parentOut = parent->vout[txin.prevout.n];
1472 if (pwallet->IsMine(parentOut) != ISMINE_SPENDABLE)
1473 return false;
1475 return true;
1478 bool CWalletTx::IsEquivalentTo(const CWalletTx& tx) const
1480 CMutableTransaction tx1 = *this;
1481 CMutableTransaction tx2 = tx;
1482 for (unsigned int i = 0; i < tx1.vin.size(); i++) tx1.vin[i].scriptSig = CScript();
1483 for (unsigned int i = 0; i < tx2.vin.size(); i++) tx2.vin[i].scriptSig = CScript();
1484 return CTransaction(tx1) == CTransaction(tx2);
1487 std::vector<uint256> CWallet::ResendWalletTransactionsBefore(int64_t nTime)
1489 std::vector<uint256> result;
1491 LOCK(cs_wallet);
1492 // Sort them in chronological order
1493 multimap<unsigned int, CWalletTx*> mapSorted;
1494 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1496 CWalletTx& wtx = item.second;
1497 // Don't rebroadcast if newer than nTime:
1498 if (wtx.nTimeReceived > nTime)
1499 continue;
1500 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
1502 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
1504 CWalletTx& wtx = *item.second;
1505 if (wtx.RelayWalletTransaction())
1506 result.push_back(wtx.GetHash());
1508 return result;
1511 void CWallet::ResendWalletTransactions(int64_t nBestBlockTime)
1513 // Do this infrequently and randomly to avoid giving away
1514 // that these are our transactions.
1515 if (GetTime() < nNextResend || !fBroadcastTransactions)
1516 return;
1517 bool fFirst = (nNextResend == 0);
1518 nNextResend = GetTime() + GetRand(30 * 60);
1519 if (fFirst)
1520 return;
1522 // Only do it if there's been a new block since last time
1523 if (nBestBlockTime < nLastResend)
1524 return;
1525 nLastResend = GetTime();
1527 // Rebroadcast unconfirmed txes older than 5 minutes before the last
1528 // block was found:
1529 std::vector<uint256> relayed = ResendWalletTransactionsBefore(nBestBlockTime-5*60);
1530 if (!relayed.empty())
1531 LogPrintf("%s: rebroadcast %u unconfirmed transactions\n", __func__, relayed.size());
1534 /** @} */ // end of mapWallet
1539 /** @defgroup Actions
1541 * @{
1545 CAmount CWallet::GetBalance() const
1547 CAmount nTotal = 0;
1549 LOCK2(cs_main, cs_wallet);
1550 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1552 const CWalletTx* pcoin = &(*it).second;
1553 if (pcoin->IsTrusted())
1554 nTotal += pcoin->GetAvailableCredit();
1558 return nTotal;
1561 CAmount CWallet::GetUnconfirmedBalance() const
1563 CAmount nTotal = 0;
1565 LOCK2(cs_main, cs_wallet);
1566 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1568 const CWalletTx* pcoin = &(*it).second;
1569 if (!CheckFinalTx(*pcoin) || (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0))
1570 nTotal += pcoin->GetAvailableCredit();
1573 return nTotal;
1576 CAmount CWallet::GetImmatureBalance() const
1578 CAmount nTotal = 0;
1580 LOCK2(cs_main, cs_wallet);
1581 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1583 const CWalletTx* pcoin = &(*it).second;
1584 nTotal += pcoin->GetImmatureCredit();
1587 return nTotal;
1590 CAmount CWallet::GetWatchOnlyBalance() const
1592 CAmount nTotal = 0;
1594 LOCK2(cs_main, cs_wallet);
1595 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1597 const CWalletTx* pcoin = &(*it).second;
1598 if (pcoin->IsTrusted())
1599 nTotal += pcoin->GetAvailableWatchOnlyCredit();
1603 return nTotal;
1606 CAmount CWallet::GetUnconfirmedWatchOnlyBalance() const
1608 CAmount nTotal = 0;
1610 LOCK2(cs_main, cs_wallet);
1611 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1613 const CWalletTx* pcoin = &(*it).second;
1614 if (!CheckFinalTx(*pcoin) || (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0))
1615 nTotal += pcoin->GetAvailableWatchOnlyCredit();
1618 return nTotal;
1621 CAmount CWallet::GetImmatureWatchOnlyBalance() const
1623 CAmount nTotal = 0;
1625 LOCK2(cs_main, cs_wallet);
1626 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1628 const CWalletTx* pcoin = &(*it).second;
1629 nTotal += pcoin->GetImmatureWatchOnlyCredit();
1632 return nTotal;
1635 void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl, bool fIncludeZeroValue) const
1637 vCoins.clear();
1640 LOCK2(cs_main, cs_wallet);
1641 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1643 const uint256& wtxid = it->first;
1644 const CWalletTx* pcoin = &(*it).second;
1646 if (!CheckFinalTx(*pcoin))
1647 continue;
1649 if (fOnlyConfirmed && !pcoin->IsTrusted())
1650 continue;
1652 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
1653 continue;
1655 int nDepth = pcoin->GetDepthInMainChain();
1656 if (nDepth < 0)
1657 continue;
1659 for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
1660 isminetype mine = IsMine(pcoin->vout[i]);
1661 if (!(IsSpent(wtxid, i)) && mine != ISMINE_NO &&
1662 !IsLockedCoin((*it).first, i) && (pcoin->vout[i].nValue > 0 || fIncludeZeroValue) &&
1663 (!coinControl || !coinControl->HasSelected() || coinControl->fAllowOtherInputs || coinControl->IsSelected((*it).first, i)))
1664 vCoins.push_back(COutput(pcoin, i, nDepth,
1665 ((mine & ISMINE_SPENDABLE) != ISMINE_NO) ||
1666 (coinControl && coinControl->fAllowWatchOnly && (mine & ISMINE_WATCH_SOLVABLE) != ISMINE_NO)));
1672 static void ApproximateBestSubset(vector<pair<CAmount, pair<const CWalletTx*,unsigned int> > >vValue, const CAmount& nTotalLower, const CAmount& nTargetValue,
1673 vector<char>& vfBest, CAmount& nBest, int iterations = 1000)
1675 vector<char> vfIncluded;
1677 vfBest.assign(vValue.size(), true);
1678 nBest = nTotalLower;
1680 seed_insecure_rand();
1682 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
1684 vfIncluded.assign(vValue.size(), false);
1685 CAmount nTotal = 0;
1686 bool fReachedTarget = false;
1687 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
1689 for (unsigned int i = 0; i < vValue.size(); i++)
1691 //The solver here uses a randomized algorithm,
1692 //the randomness serves no real security purpose but is just
1693 //needed to prevent degenerate behavior and it is important
1694 //that the rng is fast. We do not use a constant random sequence,
1695 //because there may be some privacy improvement by making
1696 //the selection random.
1697 if (nPass == 0 ? insecure_rand()&1 : !vfIncluded[i])
1699 nTotal += vValue[i].first;
1700 vfIncluded[i] = true;
1701 if (nTotal >= nTargetValue)
1703 fReachedTarget = true;
1704 if (nTotal < nBest)
1706 nBest = nTotal;
1707 vfBest = vfIncluded;
1709 nTotal -= vValue[i].first;
1710 vfIncluded[i] = false;
1717 //Reduces the approximate best subset by removing any inputs that are smaller than the surplus of nTotal beyond nTargetValue.
1718 for (unsigned int i = 0; i < vValue.size(); i++)
1720 if (vfBest[i] && (nBest - vValue[i].first) >= nTargetValue )
1722 vfBest[i] = false;
1723 nBest -= vValue[i].first;
1728 bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, int nConfMine, int nConfTheirs, vector<COutput> vCoins,
1729 set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet) const
1731 setCoinsRet.clear();
1732 nValueRet = 0;
1734 // List of values less than target
1735 pair<CAmount, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
1736 coinLowestLarger.first = std::numeric_limits<CAmount>::max();
1737 coinLowestLarger.second.first = NULL;
1738 vector<pair<CAmount, pair<const CWalletTx*,unsigned int> > > vValue;
1739 CAmount nTotalLower = 0;
1741 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
1743 BOOST_FOREACH(const COutput &output, vCoins)
1745 if (!output.fSpendable)
1746 continue;
1748 const CWalletTx *pcoin = output.tx;
1750 if (output.nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? nConfMine : nConfTheirs))
1751 continue;
1753 int i = output.i;
1754 CAmount n = pcoin->vout[i].nValue;
1756 pair<CAmount,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1758 if (n == nTargetValue)
1760 setCoinsRet.insert(coin.second);
1761 nValueRet += coin.first;
1762 return true;
1764 else if (n < nTargetValue + MIN_CHANGE)
1766 vValue.push_back(coin);
1767 nTotalLower += n;
1769 else if (n < coinLowestLarger.first)
1771 coinLowestLarger = coin;
1775 if (nTotalLower == nTargetValue)
1777 for (unsigned int i = 0; i < vValue.size(); ++i)
1779 setCoinsRet.insert(vValue[i].second);
1780 nValueRet += vValue[i].first;
1782 return true;
1785 if (nTotalLower < nTargetValue)
1787 if (coinLowestLarger.second.first == NULL)
1788 return false;
1789 setCoinsRet.insert(coinLowestLarger.second);
1790 nValueRet += coinLowestLarger.first;
1791 return true;
1794 // Solve subset sum by stochastic approximation
1795 sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
1796 vector<char> vfBest;
1797 CAmount nBest;
1799 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest);
1800 if (nBest != nTargetValue && nTotalLower >= nTargetValue + MIN_CHANGE)
1801 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + MIN_CHANGE, vfBest, nBest);
1803 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
1804 // or the next bigger coin is closer), return the bigger coin
1805 if (coinLowestLarger.second.first &&
1806 ((nBest != nTargetValue && nBest < nTargetValue + MIN_CHANGE) || coinLowestLarger.first <= nBest))
1808 setCoinsRet.insert(coinLowestLarger.second);
1809 nValueRet += coinLowestLarger.first;
1811 else {
1812 for (unsigned int i = 0; i < vValue.size(); i++)
1813 if (vfBest[i])
1815 setCoinsRet.insert(vValue[i].second);
1816 nValueRet += vValue[i].first;
1819 LogPrint("selectcoins", "SelectCoins() best subset: ");
1820 for (unsigned int i = 0; i < vValue.size(); i++)
1821 if (vfBest[i])
1822 LogPrint("selectcoins", "%s ", FormatMoney(vValue[i].first));
1823 LogPrint("selectcoins", "total %s\n", FormatMoney(nBest));
1826 return true;
1829 bool CWallet::SelectCoins(const CAmount& nTargetValue, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet, const CCoinControl* coinControl) const
1831 vector<COutput> vCoins;
1832 AvailableCoins(vCoins, true, coinControl);
1834 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
1835 if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs)
1837 BOOST_FOREACH(const COutput& out, vCoins)
1839 if (!out.fSpendable)
1840 continue;
1841 nValueRet += out.tx->vout[out.i].nValue;
1842 setCoinsRet.insert(make_pair(out.tx, out.i));
1844 return (nValueRet >= nTargetValue);
1847 // calculate value from preset inputs and store them
1848 set<pair<const CWalletTx*, uint32_t> > setPresetCoins;
1849 CAmount nValueFromPresetInputs = 0;
1851 std::vector<COutPoint> vPresetInputs;
1852 if (coinControl)
1853 coinControl->ListSelected(vPresetInputs);
1854 BOOST_FOREACH(const COutPoint& outpoint, vPresetInputs)
1856 map<uint256, CWalletTx>::const_iterator it = mapWallet.find(outpoint.hash);
1857 if (it != mapWallet.end())
1859 const CWalletTx* pcoin = &it->second;
1860 // Clearly invalid input, fail
1861 if (pcoin->vout.size() <= outpoint.n)
1862 return false;
1863 nValueFromPresetInputs += pcoin->vout[outpoint.n].nValue;
1864 setPresetCoins.insert(make_pair(pcoin, outpoint.n));
1865 } else
1866 return false; // TODO: Allow non-wallet inputs
1869 // remove preset inputs from vCoins
1870 for (vector<COutput>::iterator it = vCoins.begin(); it != vCoins.end() && coinControl && coinControl->HasSelected();)
1872 if (setPresetCoins.count(make_pair(it->tx, it->i)))
1873 it = vCoins.erase(it);
1874 else
1875 ++it;
1878 bool res = nTargetValue <= nValueFromPresetInputs ||
1879 SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 6, vCoins, setCoinsRet, nValueRet) ||
1880 SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 1, vCoins, setCoinsRet, nValueRet) ||
1881 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, vCoins, setCoinsRet, nValueRet));
1883 // because SelectCoinsMinConf clears the setCoinsRet, we now add the possible inputs to the coinset
1884 setCoinsRet.insert(setPresetCoins.begin(), setPresetCoins.end());
1886 // add preset inputs to the total value selected
1887 nValueRet += nValueFromPresetInputs;
1889 return res;
1892 bool CWallet::FundTransaction(CMutableTransaction& tx, CAmount &nFeeRet, int& nChangePosRet, std::string& strFailReason, bool includeWatching)
1894 vector<CRecipient> vecSend;
1896 // Turn the txout set into a CRecipient vector
1897 BOOST_FOREACH(const CTxOut& txOut, tx.vout)
1899 CRecipient recipient = {txOut.scriptPubKey, txOut.nValue, false};
1900 vecSend.push_back(recipient);
1903 CCoinControl coinControl;
1904 coinControl.fAllowOtherInputs = true;
1905 coinControl.fAllowWatchOnly = includeWatching;
1906 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1907 coinControl.Select(txin.prevout);
1909 CReserveKey reservekey(this);
1910 CWalletTx wtx;
1911 if (!CreateTransaction(vecSend, wtx, reservekey, nFeeRet, nChangePosRet, strFailReason, &coinControl, false))
1912 return false;
1914 if (nChangePosRet != -1)
1915 tx.vout.insert(tx.vout.begin() + nChangePosRet, wtx.vout[nChangePosRet]);
1917 // Add new txins (keeping original txin scriptSig/order)
1918 BOOST_FOREACH(const CTxIn& txin, wtx.vin)
1920 bool found = false;
1921 BOOST_FOREACH(const CTxIn& origTxIn, tx.vin)
1923 if (txin.prevout.hash == origTxIn.prevout.hash && txin.prevout.n == origTxIn.prevout.n)
1925 found = true;
1926 break;
1929 if (!found)
1930 tx.vin.push_back(txin);
1933 return true;
1936 bool CWallet::CreateTransaction(const vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet,
1937 int& nChangePosRet, std::string& strFailReason, const CCoinControl* coinControl, bool sign)
1939 CAmount nValue = 0;
1940 unsigned int nSubtractFeeFromAmount = 0;
1941 BOOST_FOREACH (const CRecipient& recipient, vecSend)
1943 if (nValue < 0 || recipient.nAmount < 0)
1945 strFailReason = _("Transaction amounts must be positive");
1946 return false;
1948 nValue += recipient.nAmount;
1950 if (recipient.fSubtractFeeFromAmount)
1951 nSubtractFeeFromAmount++;
1953 if (vecSend.empty() || nValue < 0)
1955 strFailReason = _("Transaction amounts must be positive");
1956 return false;
1959 wtxNew.fTimeReceivedIsTxTime = true;
1960 wtxNew.BindWallet(this);
1961 CMutableTransaction txNew;
1963 // Discourage fee sniping.
1965 // For a large miner the value of the transactions in the best block and
1966 // the mempool can exceed the cost of deliberately attempting to mine two
1967 // blocks to orphan the current best block. By setting nLockTime such that
1968 // only the next block can include the transaction, we discourage this
1969 // practice as the height restricted and limited blocksize gives miners
1970 // considering fee sniping fewer options for pulling off this attack.
1972 // A simple way to think about this is from the wallet's point of view we
1973 // always want the blockchain to move forward. By setting nLockTime this
1974 // way we're basically making the statement that we only want this
1975 // transaction to appear in the next block; we don't want to potentially
1976 // encourage reorgs by allowing transactions to appear at lower heights
1977 // than the next block in forks of the best chain.
1979 // Of course, the subsidy is high enough, and transaction volume low
1980 // enough, that fee sniping isn't a problem yet, but by implementing a fix
1981 // now we ensure code won't be written that makes assumptions about
1982 // nLockTime that preclude a fix later.
1983 txNew.nLockTime = chainActive.Height();
1985 // Secondly occasionally randomly pick a nLockTime even further back, so
1986 // that transactions that are delayed after signing for whatever reason,
1987 // e.g. high-latency mix networks and some CoinJoin implementations, have
1988 // better privacy.
1989 if (GetRandInt(10) == 0)
1990 txNew.nLockTime = std::max(0, (int)txNew.nLockTime - GetRandInt(100));
1992 assert(txNew.nLockTime <= (unsigned int)chainActive.Height());
1993 assert(txNew.nLockTime < LOCKTIME_THRESHOLD);
1996 LOCK2(cs_main, cs_wallet);
1998 nFeeRet = 0;
1999 // Start with no fee and loop until there is enough fee
2000 while (true)
2002 txNew.vin.clear();
2003 txNew.vout.clear();
2004 wtxNew.fFromMe = true;
2005 nChangePosRet = -1;
2006 bool fFirst = true;
2008 CAmount nValueToSelect = nValue;
2009 if (nSubtractFeeFromAmount == 0)
2010 nValueToSelect += nFeeRet;
2011 double dPriority = 0;
2012 // vouts to the payees
2013 BOOST_FOREACH (const CRecipient& recipient, vecSend)
2015 CTxOut txout(recipient.nAmount, recipient.scriptPubKey);
2017 if (recipient.fSubtractFeeFromAmount)
2019 txout.nValue -= nFeeRet / nSubtractFeeFromAmount; // Subtract fee equally from each selected recipient
2021 if (fFirst) // first receiver pays the remainder not divisible by output count
2023 fFirst = false;
2024 txout.nValue -= nFeeRet % nSubtractFeeFromAmount;
2028 if (txout.IsDust(::minRelayTxFee))
2030 if (recipient.fSubtractFeeFromAmount && nFeeRet > 0)
2032 if (txout.nValue < 0)
2033 strFailReason = _("The transaction amount is too small to pay the fee");
2034 else
2035 strFailReason = _("The transaction amount is too small to send after the fee has been deducted");
2037 else
2038 strFailReason = _("Transaction amount too small");
2039 return false;
2041 txNew.vout.push_back(txout);
2044 // Choose coins to use
2045 set<pair<const CWalletTx*,unsigned int> > setCoins;
2046 CAmount nValueIn = 0;
2047 if (!SelectCoins(nValueToSelect, setCoins, nValueIn, coinControl))
2049 strFailReason = _("Insufficient funds");
2050 return false;
2052 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
2054 CAmount nCredit = pcoin.first->vout[pcoin.second].nValue;
2055 //The coin age after the next block (depth+1) is used instead of the current,
2056 //reflecting an assumption the user would accept a bit more delay for
2057 //a chance at a free transaction.
2058 //But mempool inputs might still be in the mempool, so their age stays 0
2059 int age = pcoin.first->GetDepthInMainChain();
2060 assert(age >= 0);
2061 if (age != 0)
2062 age += 1;
2063 dPriority += (double)nCredit * age;
2066 const CAmount nChange = nValueIn - nValueToSelect;
2067 if (nChange > 0)
2069 // Fill a vout to ourself
2070 // TODO: pass in scriptChange instead of reservekey so
2071 // change transaction isn't always pay-to-bitcoin-address
2072 CScript scriptChange;
2074 // coin control: send change to custom address
2075 if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange))
2076 scriptChange = GetScriptForDestination(coinControl->destChange);
2078 // no coin control: send change to newly generated address
2079 else
2081 // Note: We use a new key here to keep it from being obvious which side is the change.
2082 // The drawback is that by not reusing a previous key, the change may be lost if a
2083 // backup is restored, if the backup doesn't have the new private key for the change.
2084 // If we reused the old key, it would be possible to add code to look for and
2085 // rediscover unknown transactions that were written with keys of ours to recover
2086 // post-backup change.
2088 // Reserve a new key pair from key pool
2089 CPubKey vchPubKey;
2090 bool ret;
2091 ret = reservekey.GetReservedKey(vchPubKey);
2092 assert(ret); // should never fail, as we just unlocked
2094 scriptChange = GetScriptForDestination(vchPubKey.GetID());
2097 CTxOut newTxOut(nChange, scriptChange);
2099 // We do not move dust-change to fees, because the sender would end up paying more than requested.
2100 // This would be against the purpose of the all-inclusive feature.
2101 // So instead we raise the change and deduct from the recipient.
2102 if (nSubtractFeeFromAmount > 0 && newTxOut.IsDust(::minRelayTxFee))
2104 CAmount nDust = newTxOut.GetDustThreshold(::minRelayTxFee) - newTxOut.nValue;
2105 newTxOut.nValue += nDust; // raise change until no more dust
2106 for (unsigned int i = 0; i < vecSend.size(); i++) // subtract from first recipient
2108 if (vecSend[i].fSubtractFeeFromAmount)
2110 txNew.vout[i].nValue -= nDust;
2111 if (txNew.vout[i].IsDust(::minRelayTxFee))
2113 strFailReason = _("The transaction amount is too small to send after the fee has been deducted");
2114 return false;
2116 break;
2121 // Never create dust outputs; if we would, just
2122 // add the dust to the fee.
2123 if (newTxOut.IsDust(::minRelayTxFee))
2125 nFeeRet += nChange;
2126 reservekey.ReturnKey();
2128 else
2130 // Insert change txn at random position:
2131 nChangePosRet = GetRandInt(txNew.vout.size()+1);
2132 vector<CTxOut>::iterator position = txNew.vout.begin()+nChangePosRet;
2133 txNew.vout.insert(position, newTxOut);
2136 else
2137 reservekey.ReturnKey();
2139 // Fill vin
2141 // Note how the sequence number is set to max()-1 so that the
2142 // nLockTime set above actually works.
2143 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
2144 txNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second,CScript(),
2145 std::numeric_limits<unsigned int>::max()-1));
2147 // Sign
2148 int nIn = 0;
2149 CTransaction txNewConst(txNew);
2150 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
2152 bool signSuccess;
2153 const CScript& scriptPubKey = coin.first->vout[coin.second].scriptPubKey;
2154 CScript& scriptSigRes = txNew.vin[nIn].scriptSig;
2155 if (sign)
2156 signSuccess = ProduceSignature(TransactionSignatureCreator(this, &txNewConst, nIn, SIGHASH_ALL), scriptPubKey, scriptSigRes);
2157 else
2158 signSuccess = ProduceSignature(DummySignatureCreator(this), scriptPubKey, scriptSigRes);
2160 if (!signSuccess)
2162 strFailReason = _("Signing transaction failed");
2163 return false;
2165 nIn++;
2168 unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION);
2170 // Remove scriptSigs if we used dummy signatures for fee calculation
2171 if (!sign) {
2172 BOOST_FOREACH (CTxIn& vin, txNew.vin)
2173 vin.scriptSig = CScript();
2176 // Embed the constructed transaction data in wtxNew.
2177 *static_cast<CTransaction*>(&wtxNew) = CTransaction(txNew);
2179 // Limit size
2180 if (nBytes >= MAX_STANDARD_TX_SIZE)
2182 strFailReason = _("Transaction too large");
2183 return false;
2186 dPriority = wtxNew.ComputePriority(dPriority, nBytes);
2188 // Can we complete this as a free transaction?
2189 if (fSendFreeTransactions && nBytes <= MAX_FREE_TRANSACTION_CREATE_SIZE)
2191 // Not enough fee: enough priority?
2192 double dPriorityNeeded = mempool.estimateSmartPriority(nTxConfirmTarget);
2193 // Require at least hard-coded AllowFree.
2194 if (dPriority >= dPriorityNeeded && AllowFree(dPriority))
2195 break;
2198 CAmount nFeeNeeded = GetMinimumFee(nBytes, nTxConfirmTarget, mempool);
2199 if (coinControl && nFeeNeeded > 0 && coinControl->nMinimumTotalFee > nFeeNeeded) {
2200 nFeeNeeded = coinControl->nMinimumTotalFee;
2203 // If we made it here and we aren't even able to meet the relay fee on the next pass, give up
2204 // because we must be at the maximum allowed fee.
2205 if (nFeeNeeded < ::minRelayTxFee.GetFee(nBytes))
2207 strFailReason = _("Transaction too large for fee policy");
2208 return false;
2211 if (nFeeRet >= nFeeNeeded)
2212 break; // Done, enough fee included.
2214 // Include more fee and try again.
2215 nFeeRet = nFeeNeeded;
2216 continue;
2221 return true;
2225 * Call after CreateTransaction unless you want to abort
2227 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
2230 LOCK2(cs_main, cs_wallet);
2231 LogPrintf("CommitTransaction:\n%s", wtxNew.ToString());
2233 // This is only to keep the database open to defeat the auto-flush for the
2234 // duration of this scope. This is the only place where this optimization
2235 // maybe makes sense; please don't do it anywhere else.
2236 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r+") : NULL;
2238 // Take key pair from key pool so it won't be used again
2239 reservekey.KeepKey();
2241 // Add tx to wallet, because if it has change it's also ours,
2242 // otherwise just for transaction history.
2243 AddToWallet(wtxNew, false, pwalletdb);
2245 // Notify that old coins are spent
2246 set<CWalletTx*> setCoins;
2247 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
2249 CWalletTx &coin = mapWallet[txin.prevout.hash];
2250 coin.BindWallet(this);
2251 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
2254 if (fFileBacked)
2255 delete pwalletdb;
2258 // Track how many getdata requests our transaction gets
2259 mapRequestCount[wtxNew.GetHash()] = 0;
2261 if (fBroadcastTransactions)
2263 // Broadcast
2264 if (!wtxNew.AcceptToMemoryPool(false))
2266 // This must not fail. The transaction has already been signed and recorded.
2267 LogPrintf("CommitTransaction(): Error: Transaction not valid\n");
2268 return false;
2270 wtxNew.RelayWalletTransaction();
2273 return true;
2276 bool CWallet::AddAccountingEntry(const CAccountingEntry& acentry, CWalletDB & pwalletdb)
2278 if (!pwalletdb.WriteAccountingEntry_Backend(acentry))
2279 return false;
2281 laccentries.push_back(acentry);
2282 CAccountingEntry & entry = laccentries.back();
2283 wtxOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
2285 return true;
2288 CAmount CWallet::GetRequiredFee(unsigned int nTxBytes)
2290 return std::max(minTxFee.GetFee(nTxBytes), ::minRelayTxFee.GetFee(nTxBytes));
2293 CAmount CWallet::GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool& pool)
2295 // payTxFee is user-set "I want to pay this much"
2296 CAmount nFeeNeeded = payTxFee.GetFee(nTxBytes);
2297 // User didn't set: use -txconfirmtarget to estimate...
2298 if (nFeeNeeded == 0) {
2299 int estimateFoundTarget = nConfirmTarget;
2300 nFeeNeeded = pool.estimateSmartFee(nConfirmTarget, &estimateFoundTarget).GetFee(nTxBytes);
2301 // ... unless we don't have enough mempool data for our desired target
2302 // so we make sure we're paying at least minTxFee
2303 if (nFeeNeeded == 0 || (unsigned int)estimateFoundTarget > nConfirmTarget)
2304 nFeeNeeded = std::max(nFeeNeeded, GetRequiredFee(nTxBytes));
2306 // prevent user from paying a non-sense fee (like 1 satoshi): 0 < fee < minRelayFee
2307 if (nFeeNeeded < ::minRelayTxFee.GetFee(nTxBytes))
2308 nFeeNeeded = ::minRelayTxFee.GetFee(nTxBytes);
2309 // But always obey the maximum
2310 if (nFeeNeeded > maxTxFee)
2311 nFeeNeeded = maxTxFee;
2312 return nFeeNeeded;
2318 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
2320 if (!fFileBacked)
2321 return DB_LOAD_OK;
2322 fFirstRunRet = false;
2323 DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
2324 if (nLoadWalletRet == DB_NEED_REWRITE)
2326 if (CDB::Rewrite(strWalletFile, "\x04pool"))
2328 LOCK(cs_wallet);
2329 setKeyPool.clear();
2330 // Note: can't top-up keypool here, because wallet is locked.
2331 // User will be prompted to unlock wallet the next operation
2332 // that requires a new key.
2336 if (nLoadWalletRet != DB_LOAD_OK)
2337 return nLoadWalletRet;
2338 fFirstRunRet = !vchDefaultKey.IsValid();
2340 uiInterface.LoadWallet(this);
2342 return DB_LOAD_OK;
2346 DBErrors CWallet::ZapWalletTx(std::vector<CWalletTx>& vWtx)
2348 if (!fFileBacked)
2349 return DB_LOAD_OK;
2350 DBErrors nZapWalletTxRet = CWalletDB(strWalletFile,"cr+").ZapWalletTx(this, vWtx);
2351 if (nZapWalletTxRet == DB_NEED_REWRITE)
2353 if (CDB::Rewrite(strWalletFile, "\x04pool"))
2355 LOCK(cs_wallet);
2356 setKeyPool.clear();
2357 // Note: can't top-up keypool here, because wallet is locked.
2358 // User will be prompted to unlock wallet the next operation
2359 // that requires a new key.
2363 if (nZapWalletTxRet != DB_LOAD_OK)
2364 return nZapWalletTxRet;
2366 return DB_LOAD_OK;
2370 bool CWallet::SetAddressBook(const CTxDestination& address, const string& strName, const string& strPurpose)
2372 bool fUpdated = false;
2374 LOCK(cs_wallet); // mapAddressBook
2375 std::map<CTxDestination, CAddressBookData>::iterator mi = mapAddressBook.find(address);
2376 fUpdated = mi != mapAddressBook.end();
2377 mapAddressBook[address].name = strName;
2378 if (!strPurpose.empty()) /* update purpose only if requested */
2379 mapAddressBook[address].purpose = strPurpose;
2381 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != ISMINE_NO,
2382 strPurpose, (fUpdated ? CT_UPDATED : CT_NEW) );
2383 if (!fFileBacked)
2384 return false;
2385 if (!strPurpose.empty() && !CWalletDB(strWalletFile).WritePurpose(CBitcoinAddress(address).ToString(), strPurpose))
2386 return false;
2387 return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName);
2390 bool CWallet::DelAddressBook(const CTxDestination& address)
2393 LOCK(cs_wallet); // mapAddressBook
2395 if(fFileBacked)
2397 // Delete destdata tuples associated with address
2398 std::string strAddress = CBitcoinAddress(address).ToString();
2399 BOOST_FOREACH(const PAIRTYPE(string, string) &item, mapAddressBook[address].destdata)
2401 CWalletDB(strWalletFile).EraseDestData(strAddress, item.first);
2404 mapAddressBook.erase(address);
2407 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != ISMINE_NO, "", CT_DELETED);
2409 if (!fFileBacked)
2410 return false;
2411 CWalletDB(strWalletFile).ErasePurpose(CBitcoinAddress(address).ToString());
2412 return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString());
2415 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
2417 if (fFileBacked)
2419 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
2420 return false;
2422 vchDefaultKey = vchPubKey;
2423 return true;
2427 * Mark old keypool keys as used,
2428 * and generate all new keys
2430 bool CWallet::NewKeyPool()
2433 LOCK(cs_wallet);
2434 CWalletDB walletdb(strWalletFile);
2435 BOOST_FOREACH(int64_t nIndex, setKeyPool)
2436 walletdb.ErasePool(nIndex);
2437 setKeyPool.clear();
2439 if (IsLocked())
2440 return false;
2442 int64_t nKeys = max(GetArg("-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t)0);
2443 for (int i = 0; i < nKeys; i++)
2445 int64_t nIndex = i+1;
2446 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
2447 setKeyPool.insert(nIndex);
2449 LogPrintf("CWallet::NewKeyPool wrote %d new keys\n", nKeys);
2451 return true;
2454 bool CWallet::TopUpKeyPool(unsigned int kpSize)
2457 LOCK(cs_wallet);
2459 if (IsLocked())
2460 return false;
2462 CWalletDB walletdb(strWalletFile);
2464 // Top up key pool
2465 unsigned int nTargetSize;
2466 if (kpSize > 0)
2467 nTargetSize = kpSize;
2468 else
2469 nTargetSize = max(GetArg("-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t) 0);
2471 while (setKeyPool.size() < (nTargetSize + 1))
2473 int64_t nEnd = 1;
2474 if (!setKeyPool.empty())
2475 nEnd = *(--setKeyPool.end()) + 1;
2476 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
2477 throw runtime_error("TopUpKeyPool(): writing generated key failed");
2478 setKeyPool.insert(nEnd);
2479 LogPrintf("keypool added key %d, size=%u\n", nEnd, setKeyPool.size());
2482 return true;
2485 void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool)
2487 nIndex = -1;
2488 keypool.vchPubKey = CPubKey();
2490 LOCK(cs_wallet);
2492 if (!IsLocked())
2493 TopUpKeyPool();
2495 // Get the oldest key
2496 if(setKeyPool.empty())
2497 return;
2499 CWalletDB walletdb(strWalletFile);
2501 nIndex = *(setKeyPool.begin());
2502 setKeyPool.erase(setKeyPool.begin());
2503 if (!walletdb.ReadPool(nIndex, keypool))
2504 throw runtime_error("ReserveKeyFromKeyPool(): read failed");
2505 if (!HaveKey(keypool.vchPubKey.GetID()))
2506 throw runtime_error("ReserveKeyFromKeyPool(): unknown key in key pool");
2507 assert(keypool.vchPubKey.IsValid());
2508 LogPrintf("keypool reserve %d\n", nIndex);
2512 void CWallet::KeepKey(int64_t nIndex)
2514 // Remove from key pool
2515 if (fFileBacked)
2517 CWalletDB walletdb(strWalletFile);
2518 walletdb.ErasePool(nIndex);
2520 LogPrintf("keypool keep %d\n", nIndex);
2523 void CWallet::ReturnKey(int64_t nIndex)
2525 // Return to key pool
2527 LOCK(cs_wallet);
2528 setKeyPool.insert(nIndex);
2530 LogPrintf("keypool return %d\n", nIndex);
2533 bool CWallet::GetKeyFromPool(CPubKey& result)
2535 int64_t nIndex = 0;
2536 CKeyPool keypool;
2538 LOCK(cs_wallet);
2539 ReserveKeyFromKeyPool(nIndex, keypool);
2540 if (nIndex == -1)
2542 if (IsLocked()) return false;
2543 result = GenerateNewKey();
2544 return true;
2546 KeepKey(nIndex);
2547 result = keypool.vchPubKey;
2549 return true;
2552 int64_t CWallet::GetOldestKeyPoolTime()
2554 int64_t nIndex = 0;
2555 CKeyPool keypool;
2556 ReserveKeyFromKeyPool(nIndex, keypool);
2557 if (nIndex == -1)
2558 return GetTime();
2559 ReturnKey(nIndex);
2560 return keypool.nTime;
2563 std::map<CTxDestination, CAmount> CWallet::GetAddressBalances()
2565 map<CTxDestination, CAmount> balances;
2568 LOCK(cs_wallet);
2569 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2571 CWalletTx *pcoin = &walletEntry.second;
2573 if (!CheckFinalTx(*pcoin) || !pcoin->IsTrusted())
2574 continue;
2576 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
2577 continue;
2579 int nDepth = pcoin->GetDepthInMainChain();
2580 if (nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? 0 : 1))
2581 continue;
2583 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2585 CTxDestination addr;
2586 if (!IsMine(pcoin->vout[i]))
2587 continue;
2588 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr))
2589 continue;
2591 CAmount n = IsSpent(walletEntry.first, i) ? 0 : pcoin->vout[i].nValue;
2593 if (!balances.count(addr))
2594 balances[addr] = 0;
2595 balances[addr] += n;
2600 return balances;
2603 set< set<CTxDestination> > CWallet::GetAddressGroupings()
2605 AssertLockHeld(cs_wallet); // mapWallet
2606 set< set<CTxDestination> > groupings;
2607 set<CTxDestination> grouping;
2609 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2611 CWalletTx *pcoin = &walletEntry.second;
2613 if (pcoin->vin.size() > 0)
2615 bool any_mine = false;
2616 // group all input addresses with each other
2617 BOOST_FOREACH(CTxIn txin, pcoin->vin)
2619 CTxDestination address;
2620 if(!IsMine(txin)) /* If this input isn't mine, ignore it */
2621 continue;
2622 if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
2623 continue;
2624 grouping.insert(address);
2625 any_mine = true;
2628 // group change with input addresses
2629 if (any_mine)
2631 BOOST_FOREACH(CTxOut txout, pcoin->vout)
2632 if (IsChange(txout))
2634 CTxDestination txoutAddr;
2635 if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
2636 continue;
2637 grouping.insert(txoutAddr);
2640 if (grouping.size() > 0)
2642 groupings.insert(grouping);
2643 grouping.clear();
2647 // group lone addrs by themselves
2648 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2649 if (IsMine(pcoin->vout[i]))
2651 CTxDestination address;
2652 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address))
2653 continue;
2654 grouping.insert(address);
2655 groupings.insert(grouping);
2656 grouping.clear();
2660 set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
2661 map< CTxDestination, set<CTxDestination>* > setmap; // map addresses to the unique group containing it
2662 BOOST_FOREACH(set<CTxDestination> grouping, groupings)
2664 // make a set of all the groups hit by this new group
2665 set< set<CTxDestination>* > hits;
2666 map< CTxDestination, set<CTxDestination>* >::iterator it;
2667 BOOST_FOREACH(CTxDestination address, grouping)
2668 if ((it = setmap.find(address)) != setmap.end())
2669 hits.insert((*it).second);
2671 // merge all hit groups into a new single group and delete old groups
2672 set<CTxDestination>* merged = new set<CTxDestination>(grouping);
2673 BOOST_FOREACH(set<CTxDestination>* hit, hits)
2675 merged->insert(hit->begin(), hit->end());
2676 uniqueGroupings.erase(hit);
2677 delete hit;
2679 uniqueGroupings.insert(merged);
2681 // update setmap
2682 BOOST_FOREACH(CTxDestination element, *merged)
2683 setmap[element] = merged;
2686 set< set<CTxDestination> > ret;
2687 BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings)
2689 ret.insert(*uniqueGrouping);
2690 delete uniqueGrouping;
2693 return ret;
2696 std::set<CTxDestination> CWallet::GetAccountAddresses(const std::string& strAccount) const
2698 LOCK(cs_wallet);
2699 set<CTxDestination> result;
2700 BOOST_FOREACH(const PAIRTYPE(CTxDestination, CAddressBookData)& item, mapAddressBook)
2702 const CTxDestination& address = item.first;
2703 const string& strName = item.second.name;
2704 if (strName == strAccount)
2705 result.insert(address);
2707 return result;
2710 bool CReserveKey::GetReservedKey(CPubKey& pubkey)
2712 if (nIndex == -1)
2714 CKeyPool keypool;
2715 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
2716 if (nIndex != -1)
2717 vchPubKey = keypool.vchPubKey;
2718 else {
2719 return false;
2722 assert(vchPubKey.IsValid());
2723 pubkey = vchPubKey;
2724 return true;
2727 void CReserveKey::KeepKey()
2729 if (nIndex != -1)
2730 pwallet->KeepKey(nIndex);
2731 nIndex = -1;
2732 vchPubKey = CPubKey();
2735 void CReserveKey::ReturnKey()
2737 if (nIndex != -1)
2738 pwallet->ReturnKey(nIndex);
2739 nIndex = -1;
2740 vchPubKey = CPubKey();
2743 void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
2745 setAddress.clear();
2747 CWalletDB walletdb(strWalletFile);
2749 LOCK2(cs_main, cs_wallet);
2750 BOOST_FOREACH(const int64_t& id, setKeyPool)
2752 CKeyPool keypool;
2753 if (!walletdb.ReadPool(id, keypool))
2754 throw runtime_error("GetAllReserveKeyHashes(): read failed");
2755 assert(keypool.vchPubKey.IsValid());
2756 CKeyID keyID = keypool.vchPubKey.GetID();
2757 if (!HaveKey(keyID))
2758 throw runtime_error("GetAllReserveKeyHashes(): unknown key in key pool");
2759 setAddress.insert(keyID);
2763 void CWallet::UpdatedTransaction(const uint256 &hashTx)
2766 LOCK(cs_wallet);
2767 // Only notify UI if this transaction is in this wallet
2768 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
2769 if (mi != mapWallet.end())
2770 NotifyTransactionChanged(this, hashTx, CT_UPDATED);
2774 void CWallet::GetScriptForMining(boost::shared_ptr<CReserveScript> &script)
2776 boost::shared_ptr<CReserveKey> rKey(new CReserveKey(this));
2777 CPubKey pubkey;
2778 if (!rKey->GetReservedKey(pubkey))
2779 return;
2781 script = rKey;
2782 script->reserveScript = CScript() << ToByteVector(pubkey) << OP_CHECKSIG;
2785 void CWallet::LockCoin(COutPoint& output)
2787 AssertLockHeld(cs_wallet); // setLockedCoins
2788 setLockedCoins.insert(output);
2791 void CWallet::UnlockCoin(COutPoint& output)
2793 AssertLockHeld(cs_wallet); // setLockedCoins
2794 setLockedCoins.erase(output);
2797 void CWallet::UnlockAllCoins()
2799 AssertLockHeld(cs_wallet); // setLockedCoins
2800 setLockedCoins.clear();
2803 bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const
2805 AssertLockHeld(cs_wallet); // setLockedCoins
2806 COutPoint outpt(hash, n);
2808 return (setLockedCoins.count(outpt) > 0);
2811 void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts)
2813 AssertLockHeld(cs_wallet); // setLockedCoins
2814 for (std::set<COutPoint>::iterator it = setLockedCoins.begin();
2815 it != setLockedCoins.end(); it++) {
2816 COutPoint outpt = (*it);
2817 vOutpts.push_back(outpt);
2821 /** @} */ // end of Actions
2823 class CAffectedKeysVisitor : public boost::static_visitor<void> {
2824 private:
2825 const CKeyStore &keystore;
2826 std::vector<CKeyID> &vKeys;
2828 public:
2829 CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector<CKeyID> &vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {}
2831 void Process(const CScript &script) {
2832 txnouttype type;
2833 std::vector<CTxDestination> vDest;
2834 int nRequired;
2835 if (ExtractDestinations(script, type, vDest, nRequired)) {
2836 BOOST_FOREACH(const CTxDestination &dest, vDest)
2837 boost::apply_visitor(*this, dest);
2841 void operator()(const CKeyID &keyId) {
2842 if (keystore.HaveKey(keyId))
2843 vKeys.push_back(keyId);
2846 void operator()(const CScriptID &scriptId) {
2847 CScript script;
2848 if (keystore.GetCScript(scriptId, script))
2849 Process(script);
2852 void operator()(const CNoDestination &none) {}
2855 void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const {
2856 AssertLockHeld(cs_wallet); // mapKeyMetadata
2857 mapKeyBirth.clear();
2859 // get birth times for keys with metadata
2860 for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++)
2861 if (it->second.nCreateTime)
2862 mapKeyBirth[it->first] = it->second.nCreateTime;
2864 // map in which we'll infer heights of other keys
2865 CBlockIndex *pindexMax = chainActive[std::max(0, chainActive.Height() - 144)]; // the tip can be reorganised; use a 144-block safety margin
2866 std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
2867 std::set<CKeyID> setKeys;
2868 GetKeys(setKeys);
2869 BOOST_FOREACH(const CKeyID &keyid, setKeys) {
2870 if (mapKeyBirth.count(keyid) == 0)
2871 mapKeyFirstBlock[keyid] = pindexMax;
2873 setKeys.clear();
2875 // if there are no such keys, we're done
2876 if (mapKeyFirstBlock.empty())
2877 return;
2879 // find first block that affects those keys, if there are any left
2880 std::vector<CKeyID> vAffected;
2881 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
2882 // iterate over all wallet transactions...
2883 const CWalletTx &wtx = (*it).second;
2884 BlockMap::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
2885 if (blit != mapBlockIndex.end() && chainActive.Contains(blit->second)) {
2886 // ... which are already in a block
2887 int nHeight = blit->second->nHeight;
2888 BOOST_FOREACH(const CTxOut &txout, wtx.vout) {
2889 // iterate over all their outputs
2890 CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey);
2891 BOOST_FOREACH(const CKeyID &keyid, vAffected) {
2892 // ... and all their affected keys
2893 std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
2894 if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
2895 rit->second = blit->second;
2897 vAffected.clear();
2902 // Extract block timestamps for those keys
2903 for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
2904 mapKeyBirth[it->first] = it->second->GetBlockTime() - 7200; // block times can be 2h off
2907 bool CWallet::AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
2909 if (boost::get<CNoDestination>(&dest))
2910 return false;
2912 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
2913 if (!fFileBacked)
2914 return true;
2915 return CWalletDB(strWalletFile).WriteDestData(CBitcoinAddress(dest).ToString(), key, value);
2918 bool CWallet::EraseDestData(const CTxDestination &dest, const std::string &key)
2920 if (!mapAddressBook[dest].destdata.erase(key))
2921 return false;
2922 if (!fFileBacked)
2923 return true;
2924 return CWalletDB(strWalletFile).EraseDestData(CBitcoinAddress(dest).ToString(), key);
2927 bool CWallet::LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
2929 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
2930 return true;
2933 bool CWallet::GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const
2935 std::map<CTxDestination, CAddressBookData>::const_iterator i = mapAddressBook.find(dest);
2936 if(i != mapAddressBook.end())
2938 CAddressBookData::StringMap::const_iterator j = i->second.destdata.find(key);
2939 if(j != i->second.destdata.end())
2941 if(value)
2942 *value = j->second;
2943 return true;
2946 return false;
2949 CKeyPool::CKeyPool()
2951 nTime = GetTime();
2954 CKeyPool::CKeyPool(const CPubKey& vchPubKeyIn)
2956 nTime = GetTime();
2957 vchPubKey = vchPubKeyIn;
2960 CWalletKey::CWalletKey(int64_t nExpires)
2962 nTimeCreated = (nExpires ? GetTime() : 0);
2963 nTimeExpires = nExpires;
2966 int CMerkleTx::SetMerkleBranch(const CBlock& block)
2968 AssertLockHeld(cs_main);
2969 CBlock blockTmp;
2971 // Update the tx's hashBlock
2972 hashBlock = block.GetHash();
2974 // Locate the transaction
2975 for (nIndex = 0; nIndex < (int)block.vtx.size(); nIndex++)
2976 if (block.vtx[nIndex] == *(CTransaction*)this)
2977 break;
2978 if (nIndex == (int)block.vtx.size())
2980 nIndex = -1;
2981 LogPrintf("ERROR: SetMerkleBranch(): couldn't find tx in block\n");
2982 return 0;
2985 // Is the tx in a block that's in the main chain
2986 BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
2987 if (mi == mapBlockIndex.end())
2988 return 0;
2989 const CBlockIndex* pindex = (*mi).second;
2990 if (!pindex || !chainActive.Contains(pindex))
2991 return 0;
2993 return chainActive.Height() - pindex->nHeight + 1;
2996 int CMerkleTx::GetDepthInMainChain(const CBlockIndex* &pindexRet) const
2998 if (hashUnset())
2999 return 0;
3001 AssertLockHeld(cs_main);
3003 // Find the block it claims to be in
3004 BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
3005 if (mi == mapBlockIndex.end())
3006 return 0;
3007 CBlockIndex* pindex = (*mi).second;
3008 if (!pindex || !chainActive.Contains(pindex))
3009 return 0;
3011 pindexRet = pindex;
3012 return ((nIndex == -1) ? (-1) : 1) * (chainActive.Height() - pindex->nHeight + 1);
3015 int CMerkleTx::GetBlocksToMaturity() const
3017 if (!IsCoinBase())
3018 return 0;
3019 return max(0, (COINBASE_MATURITY+1) - GetDepthInMainChain());
3023 bool CMerkleTx::AcceptToMemoryPool(bool fLimitFree, bool fRejectAbsurdFee)
3025 CValidationState state;
3026 return ::AcceptToMemoryPool(mempool, state, *this, fLimitFree, NULL, false, fRejectAbsurdFee);