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"
9 #include "checkpoints.h"
11 #include "coincontrol.h"
12 #include "consensus/consensus.h"
13 #include "consensus/validation.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"
24 #include "txmempool.h"
26 #include "utilmoneystr.h"
30 #include <boost/algorithm/string/replace.hpp>
31 #include <boost/filesystem.hpp>
32 #include <boost/thread.hpp>
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
;
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
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
75 std::map
<uint256
, CWalletTx
>::const_iterator it
= mapWallet
.find(hash
);
76 if (it
== mapWallet
.end())
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
87 secret
.MakeNewKey(fCompressed
);
89 // Compressed public keys were introduced in version 0.6.0
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");
107 bool CWallet::AddKeyPubKey(const CKey
& secret
, const CPubKey
&pubkey
)
109 AssertLockHeld(cs_wallet
); // mapKeyMetadata
110 if (!CCryptoKeyStore::AddKeyPubKey(secret
, pubkey
))
113 // check if we need to remove from watch-only
115 script
= GetScriptForDestination(pubkey
.GetID());
116 if (HaveWatchOnly(script
))
117 RemoveWatchOnly(script
);
118 script
= GetScriptForRawPubKey(pubkey
);
119 if (HaveWatchOnly(script
))
120 RemoveWatchOnly(script
);
125 return CWalletDB(strWalletFile
).WriteKey(pubkey
,
127 mapKeyMetadata
[pubkey
.GetID()]);
132 bool CWallet::AddCryptedKey(const CPubKey
&vchPubKey
,
133 const vector
<unsigned char> &vchCryptedSecret
)
135 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey
, vchCryptedSecret
))
141 if (pwalletdbEncryption
)
142 return pwalletdbEncryption
->WriteCryptedKey(vchPubKey
,
144 mapKeyMetadata
[vchPubKey
.GetID()]);
146 return CWalletDB(strWalletFile
).WriteCryptedKey(vchPubKey
,
148 mapKeyMetadata
[vchPubKey
.GetID()]);
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
;
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
))
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
);
190 return CCryptoKeyStore::AddCScript(redeemScript
);
193 bool CWallet::AddWatchOnly(const CScript
&dest
)
195 if (!CCryptoKeyStore::AddWatchOnly(dest
))
197 nTimeFirstKey
= 1; // No birthday information for watch-only keys.
198 NotifyWatchonlyChanged(true);
201 return CWalletDB(strWalletFile
).WriteWatchOnly(dest
);
204 bool CWallet::RemoveWatchOnly(const CScript
&dest
)
206 AssertLockHeld(cs_wallet
);
207 if (!CCryptoKeyStore::RemoveWatchOnly(dest
))
209 if (!HaveWatchOnly())
210 NotifyWatchonlyChanged(false);
212 if (!CWalletDB(strWalletFile
).EraseWatchOnly(dest
))
218 bool CWallet::LoadWatchOnly(const CScript
&dest
)
220 return CCryptoKeyStore::AddWatchOnly(dest
);
223 bool CWallet::Unlock(const SecureString
& strWalletPassphrase
)
226 CKeyingMaterial vMasterKey
;
230 BOOST_FOREACH(const MasterKeyMap::value_type
& pMasterKey
, mapMasterKeys
)
232 if(!crypter
.SetKeyFromPassphrase(strWalletPassphrase
, pMasterKey
.second
.vchSalt
, pMasterKey
.second
.nDeriveIterations
, pMasterKey
.second
.nDerivationMethod
))
234 if (!crypter
.Decrypt(pMasterKey
.second
.vchCryptedKey
, vMasterKey
))
235 continue; // try another master key
236 if (CCryptoKeyStore::Unlock(vMasterKey
))
243 bool CWallet::ChangeWalletPassphrase(const SecureString
& strOldWalletPassphrase
, const SecureString
& strNewWalletPassphrase
)
245 bool fWasLocked
= IsLocked();
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
))
257 if (!crypter
.Decrypt(pMasterKey
.second
.vchCryptedKey
, vMasterKey
))
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
))
276 if (!crypter
.Encrypt(vMasterKey
, pMasterKey
.second
.vchCryptedKey
))
278 CWalletDB(strWalletFile
).WriteMasterKey(pMasterKey
.first
, pMasterKey
.second
);
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
)
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
;
312 CWalletDB
* pwalletdb
= pwalletdbIn
? pwalletdbIn
: new CWalletDB(strWalletFile
);
313 if (nWalletVersion
> 40000)
314 pwalletdb
->WriteMinVersion(nWalletVersion
);
322 bool CWallet::SetMaxVersion(int nVersion
)
324 LOCK(cs_wallet
); // nWalletVersion, nWalletMaxVersion
325 // cannot downgrade below current version
326 if (nWalletVersion
> nVersion
)
329 nWalletMaxVersion
= nVersion
;
334 set
<uint256
> CWallet::GetConflicts(const uint256
& txid
) const
337 AssertLockHeld(cs_wallet
);
339 std::map
<uint256
, CWalletTx
>::const_iterator it
= mapWallet
.find(txid
);
340 if (it
== mapWallet
.end())
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
);
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());
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)
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());
385 if (GetBoolArg("-salvagewallet", false))
387 // Recover readable keypairs:
388 if (!CWalletDB::Recover(bitdb
, walletFile
, true))
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");
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
)
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
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
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
);
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!
486 BOOST_FOREACH(const CTxIn
& txin
, thisTx
.vin
)
487 AddToSpends(txin
.prevout
, wtxid
);
490 bool CWallet::EncryptWallet(const SecureString
& strWalletPassphrase
)
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
);
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
))
523 if (!crypter
.Encrypt(vMasterKey
, kMasterKey
.vchCryptedKey
))
528 mapMasterKeys
[++nMasterKeyMaxID
] = kMasterKey
;
531 assert(!pwalletdbEncryption
);
532 pwalletdbEncryption
= new CWalletDB(strWalletFile
);
533 if (!pwalletdbEncryption
->TxnBegin()) {
534 delete pwalletdbEncryption
;
535 pwalletdbEncryption
= NULL
;
538 pwalletdbEncryption
->WriteMasterKey(nMasterKeyMaxID
, kMasterKey
);
541 if (!EncryptKeys(vMasterKey
))
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.
552 // Encryption was introduced in version 0.4.0
553 SetMinVersion(FEATURE_WALLETCRYPT
, pwalletdbEncryption
, true);
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.
564 delete pwalletdbEncryption
;
565 pwalletdbEncryption
= NULL
;
569 Unlock(strWalletPassphrase
);
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);
583 int64_t CWallet::IncOrderPosNext(CWalletDB
*pwalletdb
)
585 AssertLockHeld(cs_wallet
); // nOrderPosNext
586 int64_t nRet
= nOrderPosNext
++;
588 pwalletdb
->WriteOrderPosNext(nOrderPosNext
);
590 CWalletDB(strWalletFile
).WriteOrderPosNext(nOrderPosNext
);
595 void CWallet::MarkDirty()
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();
610 mapWallet
[hash
] = wtxIn
;
611 CWalletTx
& wtx
= mapWallet
[hash
];
612 wtx
.BindWallet(this);
613 wtxOrdered
.insert(make_pair(wtx
.nOrderPos
, TxPair(&wtx
, (CAccountingEntry
*)0)));
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());
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
;
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
;
654 CAccountingEntry
*const pacentry
= (*it
).second
.second
;
658 nSmartTime
= pwtx
->nTimeSmart
;
660 nSmartTime
= pwtx
->nTimeReceived
;
663 nSmartTime
= pacentry
->nTime
;
664 if (nSmartTime
<= latestTolerated
)
666 latestEntry
= nSmartTime
;
667 if (nSmartTime
> latestNow
)
668 latestNow
= nSmartTime
;
674 int64_t blocktime
= mapBlockIndex
[wtxIn
.hashBlock
]->GetBlockTime();
675 wtx
.nTimeSmart
= std::max(latestEntry
, std::min(blocktime
, latestNow
));
678 LogPrintf("AddToWallet(): found %s in block %s not in index\n",
679 wtxIn
.GetHash().ToString(),
680 wtxIn
.hashBlock
.ToString());
685 bool fUpdated
= false;
689 if (!wtxIn
.hashUnset() && wtxIn
.hashBlock
!= wtx
.hashBlock
)
691 wtx
.hashBlock
= wtxIn
.hashBlock
;
694 // If no longer abandoned, update
695 if (wtxIn
.hashBlock
.IsNull() && wtx
.isAbandoned())
697 wtx
.hashBlock
= wtxIn
.hashBlock
;
700 if (wtxIn
.nIndex
!= -1 && (wtxIn
.nIndex
!= wtx
.nIndex
))
702 wtx
.nIndex
= wtxIn
.nIndex
;
705 if (wtxIn
.fFromMe
&& wtxIn
.fFromMe
!= wtx
.fFromMe
)
707 wtx
.fFromMe
= wtxIn
.fFromMe
;
713 LogPrintf("AddToWallet %s %s%s\n", wtxIn
.GetHash().ToString(), (fInsertedNew
? "new" : ""), (fUpdated
? "update" : ""));
716 if (fInsertedNew
|| fUpdated
)
717 if (!wtx
.WriteToDisk(pwalletdb
))
720 // Break debit/credit balance caches:
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
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
);
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
);
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
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
);
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()) {
801 while (!todo
.empty()) {
802 uint256 now
= *todo
.begin();
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());
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
);
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();
839 void CWallet::MarkConflicted(const uint256
& hashBlock
, const uint256
& hashTx
)
841 LOCK2(cs_main
, cs_wallet
);
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
;
860 while (!todo
.empty()) {
861 uint256 now
= *todo
.begin();
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.
871 wtx
.hashBlock
= hashBlock
;
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
);
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
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
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
]);
926 CAmount
CWallet::GetDebit(const CTxIn
&txin
, const isminefilter
& filter
) const
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
;
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
))
970 if (!mapAddressBook
.count(address
))
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
)
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
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");
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");
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");
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
1043 LOCK(pwallet
->cs_wallet
);
1049 map
<uint256
, int>::const_iterator mi
= pwallet
->mapRequestCount
.find(hashBlock
);
1050 if (mi
!= pwallet
->mapRequestCount
.end())
1051 nRequests
= (*mi
).second
;
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
;
1069 nRequests
= 1; // If it's in someone else's block it must have got out
1077 void CWalletTx::GetAmounts(list
<COutputEntry
>& listReceived
,
1078 list
<COutputEntry
>& listSent
, CAmount
& nFee
, string
& strSentAccount
, const isminefilter
& filter
) const
1081 listReceived
.clear();
1083 strSentAccount
= strFromAccount
;
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
;
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)
1103 // Don't report 'change' txouts
1104 if (pwallet
->IsChange(txout
))
1107 else if (!(fIsMine
& filter
))
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
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;
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
)
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
)
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);
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))));
1203 ReadBlockFromDisk(block
, pindex
, Params().GetConsensus());
1204 BOOST_FOREACH(CTransaction
& tx
, block
.vtx
)
1206 if (AddToWalletIfInvolvingMe(tx
, &block
, fUpdate
))
1209 pindex
= chainActive
.Next(pindex
);
1210 if (GetTime() >= nNow
+ 60) {
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
1220 void CWallet::ReacceptWalletTransactions()
1222 // If transactions aren't being broadcasted, don't let them into local mempool either
1223 if (!fBroadcastTransactions
)
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
);
1248 wtx
.AcceptToMemoryPool(false);
1252 bool CWalletTx::RelayWalletTransaction()
1254 assert(pwallet
->GetBroadcastTransactions());
1257 if (GetDepthInMainChain() == 0 && !isAbandoned()) {
1258 LogPrintf("Relaying wtx %s\n", GetHash().ToString());
1259 RelayTransaction((CTransaction
)*this);
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
);
1278 CAmount
CWalletTx::GetDebit(const isminefilter
& filter
) const
1284 if(filter
& ISMINE_SPENDABLE
)
1287 debit
+= nDebitCached
;
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
;
1301 nWatchDebitCached
= pwallet
->GetDebit(*this, ISMINE_WATCH_ONLY
);
1302 fWatchDebitCached
= true;
1303 debit
+= nWatchDebitCached
;
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)
1316 if (filter
& ISMINE_SPENDABLE
)
1318 // GetBalance can assume transactions in mapWallet won't change
1320 credit
+= nCreditCached
;
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
;
1334 nWatchCreditCached
= pwallet
->GetCredit(*this, ISMINE_WATCH_ONLY
);
1335 fWatchCreditCached
= true;
1336 credit
+= nWatchCreditCached
;
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
;
1356 CAmount
CWalletTx::GetAvailableCredit(bool fUseCache
) const
1361 // Must wait until coinbase is safely deep enough in the chain before valuing it
1362 if (IsCoinBase() && GetBlocksToMaturity() > 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;
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
;
1400 CAmount
CWalletTx::GetAvailableWatchOnlyCredit(const bool& fUseCache
) const
1405 // Must wait until coinbase is safely deep enough in the chain before valuing it
1406 if (IsCoinBase() && GetBlocksToMaturity() > 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;
1429 CAmount
CWalletTx::GetChange() const
1432 return nChangeCached
;
1433 nChangeCached
= pwallet
->GetChange(*this);
1434 fChangeCached
= true;
1435 return nChangeCached
;
1438 bool CWalletTx::InMempool() const
1441 if (mempool
.exists(GetHash())) {
1447 bool CWalletTx::IsTrusted() const
1449 // Quick answer in most cases
1450 if (!CheckFinalTx(*this))
1452 int nDepth
= GetDepthInMainChain();
1457 if (!bSpendZeroConfChange
|| !IsFromMe(ISMINE_ALL
)) // using wtx's cached debit
1460 // Don't trust unconfirmed transactions from us unless they are in the mempool.
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
);
1471 const CTxOut
& parentOut
= parent
->vout
[txin
.prevout
.n
];
1472 if (pwallet
->IsMine(parentOut
) != ISMINE_SPENDABLE
)
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
;
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
)
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());
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
)
1517 bool fFirst
= (nNextResend
== 0);
1518 nNextResend
= GetTime() + GetRand(30 * 60);
1522 // Only do it if there's been a new block since last time
1523 if (nBestBlockTime
< nLastResend
)
1525 nLastResend
= GetTime();
1527 // Rebroadcast unconfirmed txes older than 5 minutes before the last
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
1545 CAmount
CWallet::GetBalance() const
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();
1561 CAmount
CWallet::GetUnconfirmedBalance() const
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();
1576 CAmount
CWallet::GetImmatureBalance() const
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();
1590 CAmount
CWallet::GetWatchOnlyBalance() const
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();
1606 CAmount
CWallet::GetUnconfirmedWatchOnlyBalance() const
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();
1621 CAmount
CWallet::GetImmatureWatchOnlyBalance() const
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();
1635 void CWallet::AvailableCoins(vector
<COutput
>& vCoins
, bool fOnlyConfirmed
, const CCoinControl
*coinControl
, bool fIncludeZeroValue
) const
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
))
1649 if (fOnlyConfirmed
&& !pcoin
->IsTrusted())
1652 if (pcoin
->IsCoinBase() && pcoin
->GetBlocksToMaturity() > 0)
1655 int nDepth
= pcoin
->GetDepthInMainChain();
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);
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;
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
)
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();
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
)
1748 const CWalletTx
*pcoin
= output
.tx
;
1750 if (output
.nDepth
< (pcoin
->IsFromMe(ISMINE_ALL
) ? nConfMine
: nConfTheirs
))
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
;
1764 else if (n
< nTargetValue
+ MIN_CHANGE
)
1766 vValue
.push_back(coin
);
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
;
1785 if (nTotalLower
< nTargetValue
)
1787 if (coinLowestLarger
.second
.first
== NULL
)
1789 setCoinsRet
.insert(coinLowestLarger
.second
);
1790 nValueRet
+= coinLowestLarger
.first
;
1794 // Solve subset sum by stochastic approximation
1795 sort(vValue
.rbegin(), vValue
.rend(), CompareValueOnly());
1796 vector
<char> vfBest
;
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
;
1812 for (unsigned int i
= 0; i
< vValue
.size(); 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
++)
1822 LogPrint("selectcoins", "%s ", FormatMoney(vValue
[i
].first
));
1823 LogPrint("selectcoins", "total %s\n", FormatMoney(nBest
));
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
)
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
;
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
)
1863 nValueFromPresetInputs
+= pcoin
->vout
[outpoint
.n
].nValue
;
1864 setPresetCoins
.insert(make_pair(pcoin
, outpoint
.n
));
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
);
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
;
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);
1911 if (!CreateTransaction(vecSend
, wtx
, reservekey
, nFeeRet
, nChangePosRet
, strFailReason
, &coinControl
, 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
)
1921 BOOST_FOREACH(const CTxIn
& origTxIn
, tx
.vin
)
1923 if (txin
.prevout
.hash
== origTxIn
.prevout
.hash
&& txin
.prevout
.n
== origTxIn
.prevout
.n
)
1930 tx
.vin
.push_back(txin
);
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
)
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");
1948 nValue
+= recipient
.nAmount
;
1950 if (recipient
.fSubtractFeeFromAmount
)
1951 nSubtractFeeFromAmount
++;
1953 if (vecSend
.empty() || nValue
< 0)
1955 strFailReason
= _("Transaction amounts must be positive");
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
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
);
1999 // Start with no fee and loop until there is enough fee
2004 wtxNew
.fFromMe
= 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
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");
2035 strFailReason
= _("The transaction amount is too small to send after the fee has been deducted");
2038 strFailReason
= _("Transaction amount too small");
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");
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();
2063 dPriority
+= (double)nCredit
* age
;
2066 const CAmount nChange
= nValueIn
- nValueToSelect
;
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
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
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");
2121 // Never create dust outputs; if we would, just
2122 // add the dust to the fee.
2123 if (newTxOut
.IsDust(::minRelayTxFee
))
2126 reservekey
.ReturnKey();
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
);
2137 reservekey
.ReturnKey();
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));
2149 CTransaction
txNewConst(txNew
);
2150 BOOST_FOREACH(const PAIRTYPE(const CWalletTx
*,unsigned int)& coin
, setCoins
)
2153 const CScript
& scriptPubKey
= coin
.first
->vout
[coin
.second
].scriptPubKey
;
2154 CScript
& scriptSigRes
= txNew
.vin
[nIn
].scriptSig
;
2156 signSuccess
= ProduceSignature(TransactionSignatureCreator(this, &txNewConst
, nIn
, SIGHASH_ALL
), scriptPubKey
, scriptSigRes
);
2158 signSuccess
= ProduceSignature(DummySignatureCreator(this), scriptPubKey
, scriptSigRes
);
2162 strFailReason
= _("Signing transaction failed");
2168 unsigned int nBytes
= ::GetSerializeSize(txNew
, SER_NETWORK
, PROTOCOL_VERSION
);
2170 // Remove scriptSigs if we used dummy signatures for fee calculation
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
);
2180 if (nBytes
>= MAX_STANDARD_TX_SIZE
)
2182 strFailReason
= _("Transaction too large");
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
))
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");
2211 if (nFeeRet
>= nFeeNeeded
)
2212 break; // Done, enough fee included.
2214 // Include more fee and try again.
2215 nFeeRet
= nFeeNeeded
;
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
);
2258 // Track how many getdata requests our transaction gets
2259 mapRequestCount
[wtxNew
.GetHash()] = 0;
2261 if (fBroadcastTransactions
)
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");
2270 wtxNew
.RelayWalletTransaction();
2276 bool CWallet::AddAccountingEntry(const CAccountingEntry
& acentry
, CWalletDB
& pwalletdb
)
2278 if (!pwalletdb
.WriteAccountingEntry_Backend(acentry
))
2281 laccentries
.push_back(acentry
);
2282 CAccountingEntry
& entry
= laccentries
.back();
2283 wtxOrdered
.insert(make_pair(entry
.nOrderPos
, TxPair((CWalletTx
*)0, &entry
)));
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
;
2318 DBErrors
CWallet::LoadWallet(bool& fFirstRunRet
)
2322 fFirstRunRet
= false;
2323 DBErrors nLoadWalletRet
= CWalletDB(strWalletFile
,"cr+").LoadWallet(this);
2324 if (nLoadWalletRet
== DB_NEED_REWRITE
)
2326 if (CDB::Rewrite(strWalletFile
, "\x04pool"))
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);
2346 DBErrors
CWallet::ZapWalletTx(std::vector
<CWalletTx
>& vWtx
)
2350 DBErrors nZapWalletTxRet
= CWalletDB(strWalletFile
,"cr+").ZapWalletTx(this, vWtx
);
2351 if (nZapWalletTxRet
== DB_NEED_REWRITE
)
2353 if (CDB::Rewrite(strWalletFile
, "\x04pool"))
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
;
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
) );
2385 if (!strPurpose
.empty() && !CWalletDB(strWalletFile
).WritePurpose(CBitcoinAddress(address
).ToString(), strPurpose
))
2387 return CWalletDB(strWalletFile
).WriteName(CBitcoinAddress(address
).ToString(), strName
);
2390 bool CWallet::DelAddressBook(const CTxDestination
& address
)
2393 LOCK(cs_wallet
); // mapAddressBook
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
);
2411 CWalletDB(strWalletFile
).ErasePurpose(CBitcoinAddress(address
).ToString());
2412 return CWalletDB(strWalletFile
).EraseName(CBitcoinAddress(address
).ToString());
2415 bool CWallet::SetDefaultKey(const CPubKey
&vchPubKey
)
2419 if (!CWalletDB(strWalletFile
).WriteDefaultKey(vchPubKey
))
2422 vchDefaultKey
= vchPubKey
;
2427 * Mark old keypool keys as used,
2428 * and generate all new keys
2430 bool CWallet::NewKeyPool()
2434 CWalletDB
walletdb(strWalletFile
);
2435 BOOST_FOREACH(int64_t nIndex
, setKeyPool
)
2436 walletdb
.ErasePool(nIndex
);
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
);
2454 bool CWallet::TopUpKeyPool(unsigned int kpSize
)
2462 CWalletDB
walletdb(strWalletFile
);
2465 unsigned int nTargetSize
;
2467 nTargetSize
= kpSize
;
2469 nTargetSize
= max(GetArg("-keypool", DEFAULT_KEYPOOL_SIZE
), (int64_t) 0);
2471 while (setKeyPool
.size() < (nTargetSize
+ 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());
2485 void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex
, CKeyPool
& keypool
)
2488 keypool
.vchPubKey
= CPubKey();
2495 // Get the oldest key
2496 if(setKeyPool
.empty())
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
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
2528 setKeyPool
.insert(nIndex
);
2530 LogPrintf("keypool return %d\n", nIndex
);
2533 bool CWallet::GetKeyFromPool(CPubKey
& result
)
2539 ReserveKeyFromKeyPool(nIndex
, keypool
);
2542 if (IsLocked()) return false;
2543 result
= GenerateNewKey();
2547 result
= keypool
.vchPubKey
;
2552 int64_t CWallet::GetOldestKeyPoolTime()
2556 ReserveKeyFromKeyPool(nIndex
, keypool
);
2560 return keypool
.nTime
;
2563 std::map
<CTxDestination
, CAmount
> CWallet::GetAddressBalances()
2565 map
<CTxDestination
, CAmount
> balances
;
2569 BOOST_FOREACH(PAIRTYPE(uint256
, CWalletTx
) walletEntry
, mapWallet
)
2571 CWalletTx
*pcoin
= &walletEntry
.second
;
2573 if (!CheckFinalTx(*pcoin
) || !pcoin
->IsTrusted())
2576 if (pcoin
->IsCoinBase() && pcoin
->GetBlocksToMaturity() > 0)
2579 int nDepth
= pcoin
->GetDepthInMainChain();
2580 if (nDepth
< (pcoin
->IsFromMe(ISMINE_ALL
) ? 0 : 1))
2583 for (unsigned int i
= 0; i
< pcoin
->vout
.size(); i
++)
2585 CTxDestination addr
;
2586 if (!IsMine(pcoin
->vout
[i
]))
2588 if(!ExtractDestination(pcoin
->vout
[i
].scriptPubKey
, addr
))
2591 CAmount n
= IsSpent(walletEntry
.first
, i
) ? 0 : pcoin
->vout
[i
].nValue
;
2593 if (!balances
.count(addr
))
2595 balances
[addr
] += n
;
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 */
2622 if(!ExtractDestination(mapWallet
[txin
.prevout
.hash
].vout
[txin
.prevout
.n
].scriptPubKey
, address
))
2624 grouping
.insert(address
);
2628 // group change with input addresses
2631 BOOST_FOREACH(CTxOut txout
, pcoin
->vout
)
2632 if (IsChange(txout
))
2634 CTxDestination txoutAddr
;
2635 if(!ExtractDestination(txout
.scriptPubKey
, txoutAddr
))
2637 grouping
.insert(txoutAddr
);
2640 if (grouping
.size() > 0)
2642 groupings
.insert(grouping
);
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
))
2654 grouping
.insert(address
);
2655 groupings
.insert(grouping
);
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
);
2679 uniqueGroupings
.insert(merged
);
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
;
2696 std::set
<CTxDestination
> CWallet::GetAccountAddresses(const std::string
& strAccount
) const
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
);
2710 bool CReserveKey::GetReservedKey(CPubKey
& pubkey
)
2715 pwallet
->ReserveKeyFromKeyPool(nIndex
, keypool
);
2717 vchPubKey
= keypool
.vchPubKey
;
2722 assert(vchPubKey
.IsValid());
2727 void CReserveKey::KeepKey()
2730 pwallet
->KeepKey(nIndex
);
2732 vchPubKey
= CPubKey();
2735 void CReserveKey::ReturnKey()
2738 pwallet
->ReturnKey(nIndex
);
2740 vchPubKey
= CPubKey();
2743 void CWallet::GetAllReserveKeys(set
<CKeyID
>& setAddress
) const
2747 CWalletDB
walletdb(strWalletFile
);
2749 LOCK2(cs_main
, cs_wallet
);
2750 BOOST_FOREACH(const int64_t& id
, setKeyPool
)
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
)
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));
2778 if (!rKey
->GetReservedKey(pubkey
))
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> {
2825 const CKeyStore
&keystore
;
2826 std::vector
<CKeyID
> &vKeys
;
2829 CAffectedKeysVisitor(const CKeyStore
&keystoreIn
, std::vector
<CKeyID
> &vKeysIn
) : keystore(keystoreIn
), vKeys(vKeysIn
) {}
2831 void Process(const CScript
&script
) {
2833 std::vector
<CTxDestination
> vDest
;
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
) {
2848 if (keystore
.GetCScript(scriptId
, 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
;
2869 BOOST_FOREACH(const CKeyID
&keyid
, setKeys
) {
2870 if (mapKeyBirth
.count(keyid
) == 0)
2871 mapKeyFirstBlock
[keyid
] = pindexMax
;
2875 // if there are no such keys, we're done
2876 if (mapKeyFirstBlock
.empty())
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
;
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
))
2912 mapAddressBook
[dest
].destdata
.insert(std::make_pair(key
, value
));
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
))
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
));
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())
2949 CKeyPool::CKeyPool()
2954 CKeyPool::CKeyPool(const CPubKey
& vchPubKeyIn
)
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
);
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)
2978 if (nIndex
== (int)block
.vtx
.size())
2981 LogPrintf("ERROR: SetMerkleBranch(): couldn't find tx in block\n");
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())
2989 const CBlockIndex
* pindex
= (*mi
).second
;
2990 if (!pindex
|| !chainActive
.Contains(pindex
))
2993 return chainActive
.Height() - pindex
->nHeight
+ 1;
2996 int CMerkleTx::GetDepthInMainChain(const CBlockIndex
* &pindexRet
) const
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())
3007 CBlockIndex
* pindex
= (*mi
).second
;
3008 if (!pindex
|| !chainActive
.Contains(pindex
))
3012 return ((nIndex
== -1) ? (-1) : 1) * (chainActive
.Height() - pindex
->nHeight
+ 1);
3015 int CMerkleTx::GetBlocksToMaturity() const
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
);