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 #ifndef BITCOIN_WALLET_WALLET_H
7 #define BITCOIN_WALLET_WALLET_H
11 #include "tinyformat.h"
12 #include "ui_interface.h"
13 #include "utilstrencodings.h"
14 #include "validationinterface.h"
15 #include "script/ismine.h"
16 #include "wallet/crypter.h"
17 #include "wallet/walletdb.h"
18 #include "wallet/rpcwallet.h"
29 #include <boost/shared_ptr.hpp>
30 #include <boost/thread.hpp>
32 extern CWallet
* pwalletMain
;
37 extern CFeeRate payTxFee
;
38 extern unsigned int nTxConfirmTarget
;
39 extern bool bSpendZeroConfChange
;
40 extern bool fSendFreeTransactions
;
41 extern bool fWalletRbf
;
43 static const unsigned int DEFAULT_KEYPOOL_SIZE
= 100;
45 static const CAmount DEFAULT_TRANSACTION_FEE
= 0;
46 //! -fallbackfee default
47 static const CAmount DEFAULT_FALLBACK_FEE
= 20000;
49 static const CAmount DEFAULT_TRANSACTION_MINFEE
= 1000;
50 //! minimum change amount
51 static const CAmount MIN_CHANGE
= CENT
;
52 //! Default for -spendzeroconfchange
53 static const bool DEFAULT_SPEND_ZEROCONF_CHANGE
= true;
54 //! Default for -sendfreetransactions
55 static const bool DEFAULT_SEND_FREE_TRANSACTIONS
= false;
56 //! -txconfirmtarget default
57 static const unsigned int DEFAULT_TX_CONFIRM_TARGET
= 6;
58 //! -walletrbf default
59 static const bool DEFAULT_WALLET_RBF
= false;
60 //! Largest (in bytes) free transaction we're willing to create
61 static const unsigned int MAX_FREE_TRANSACTION_CREATE_SIZE
= 1000;
62 static const bool DEFAULT_WALLETBROADCAST
= true;
63 static const bool DEFAULT_DISABLE_WALLET
= false;
64 //! if set, all keys will be derived by using BIP32
65 static const bool DEFAULT_USE_HD_WALLET
= true;
67 extern const char * DEFAULT_WALLET_DAT
;
77 /** (client) version numbers for particular wallet features */
80 FEATURE_BASE
= 10500, // the earliest version new wallets supports (only useful for getinfo's clientversion output)
82 FEATURE_WALLETCRYPT
= 40000, // wallet encryption
83 FEATURE_COMPRPUBKEY
= 60000, // compressed public keys
85 FEATURE_HD
= 130000, // Hierarchical key derivation after BIP32 (HD Wallet)
86 FEATURE_LATEST
= FEATURE_COMPRPUBKEY
// HD is optional, use FEATURE_COMPRPUBKEY as latest version
90 /** A key pool entry */
98 CKeyPool(const CPubKey
& vchPubKeyIn
);
100 ADD_SERIALIZE_METHODS
;
102 template <typename Stream
, typename Operation
>
103 inline void SerializationOp(Stream
& s
, Operation ser_action
) {
104 int nVersion
= s
.GetVersion();
105 if (!(s
.GetType() & SER_GETHASH
))
108 READWRITE(vchPubKey
);
112 /** Address book data */
113 class CAddressBookData
124 typedef std::map
<std::string
, std::string
> StringMap
;
130 CScript scriptPubKey
;
132 bool fSubtractFeeFromAmount
;
135 typedef std::map
<std::string
, std::string
> mapValue_t
;
138 static inline void ReadOrderPos(int64_t& nOrderPos
, mapValue_t
& mapValue
)
140 if (!mapValue
.count("n"))
142 nOrderPos
= -1; // TODO: calculate elsewhere
145 nOrderPos
= atoi64(mapValue
["n"].c_str());
149 static inline void WriteOrderPos(const int64_t& nOrderPos
, mapValue_t
& mapValue
)
153 mapValue
["n"] = i64tostr(nOrderPos
);
158 CTxDestination destination
;
163 /** A transaction with a merkle branch linking it to the block chain. */
164 class CMerkleTx
: public CTransaction
167 /** Constant used in hashBlock to indicate tx has been abandoned */
168 static const uint256 ABANDON_HASH
;
173 /* An nIndex == -1 means that hashBlock (in nonzero) refers to the earliest
174 * block in the chain we know this or any in-wallet dependency conflicts
175 * with. Older clients interpret nIndex == -1 as unconfirmed for backward
185 CMerkleTx(const CTransaction
& txIn
) : CTransaction(txIn
)
192 hashBlock
= uint256();
196 ADD_SERIALIZE_METHODS
;
198 template <typename Stream
, typename Operation
>
199 inline void SerializationOp(Stream
& s
, Operation ser_action
) {
200 std::vector
<uint256
> vMerkleBranch
; // For compatibility with older versions.
201 READWRITE(*(CTransaction
*)this);
202 READWRITE(hashBlock
);
203 READWRITE(vMerkleBranch
);
207 int SetMerkleBranch(const CBlockIndex
* pIndex
, int posInBlock
);
210 * Return depth of transaction in blockchain:
211 * <0 : conflicts with a transaction this deep in the blockchain
212 * 0 : in memory pool, waiting to be included in a block
213 * >=1 : this many blocks deep in the main chain
215 int GetDepthInMainChain(const CBlockIndex
* &pindexRet
) const;
216 int GetDepthInMainChain() const { const CBlockIndex
*pindexRet
; return GetDepthInMainChain(pindexRet
); }
217 bool IsInMainChain() const { const CBlockIndex
*pindexRet
; return GetDepthInMainChain(pindexRet
) > 0; }
218 int GetBlocksToMaturity() const;
219 /** Pass this transaction to the mempool. Fails if absolute fee exceeds absurd fee. */
220 bool AcceptToMemoryPool(const CAmount
& nAbsurdFee
, CValidationState
& state
);
221 bool hashUnset() const { return (hashBlock
.IsNull() || hashBlock
== ABANDON_HASH
); }
222 bool isAbandoned() const { return (hashBlock
== ABANDON_HASH
); }
223 void setAbandoned() { hashBlock
= ABANDON_HASH
; }
227 * A transaction with a bunch of additional info that only the owner cares about.
228 * It includes any unrecorded transactions needed to link it back to the block chain.
230 class CWalletTx
: public CMerkleTx
233 const CWallet
* pwallet
;
237 std::vector
<std::pair
<std::string
, std::string
> > vOrderForm
;
238 unsigned int fTimeReceivedIsTxTime
;
239 unsigned int nTimeReceived
; //!< time received by this node
240 unsigned int nTimeSmart
;
242 std::string strFromAccount
;
243 int64_t nOrderPos
; //!< position in ordered transaction list
246 mutable bool fDebitCached
;
247 mutable bool fCreditCached
;
248 mutable bool fImmatureCreditCached
;
249 mutable bool fAvailableCreditCached
;
250 mutable bool fWatchDebitCached
;
251 mutable bool fWatchCreditCached
;
252 mutable bool fImmatureWatchCreditCached
;
253 mutable bool fAvailableWatchCreditCached
;
254 mutable bool fChangeCached
;
255 mutable CAmount nDebitCached
;
256 mutable CAmount nCreditCached
;
257 mutable CAmount nImmatureCreditCached
;
258 mutable CAmount nAvailableCreditCached
;
259 mutable CAmount nWatchDebitCached
;
260 mutable CAmount nWatchCreditCached
;
261 mutable CAmount nImmatureWatchCreditCached
;
262 mutable CAmount nAvailableWatchCreditCached
;
263 mutable CAmount nChangeCached
;
270 CWalletTx(const CWallet
* pwalletIn
)
275 CWalletTx(const CWallet
* pwalletIn
, const CMerkleTx
& txIn
) : CMerkleTx(txIn
)
280 CWalletTx(const CWallet
* pwalletIn
, const CTransaction
& txIn
) : CMerkleTx(txIn
)
285 void Init(const CWallet
* pwalletIn
)
290 fTimeReceivedIsTxTime
= false;
294 strFromAccount
.clear();
295 fDebitCached
= false;
296 fCreditCached
= false;
297 fImmatureCreditCached
= false;
298 fAvailableCreditCached
= false;
299 fWatchDebitCached
= false;
300 fWatchCreditCached
= false;
301 fImmatureWatchCreditCached
= false;
302 fAvailableWatchCreditCached
= false;
303 fChangeCached
= false;
306 nImmatureCreditCached
= 0;
307 nAvailableCreditCached
= 0;
308 nWatchDebitCached
= 0;
309 nWatchCreditCached
= 0;
310 nAvailableWatchCreditCached
= 0;
311 nImmatureWatchCreditCached
= 0;
316 ADD_SERIALIZE_METHODS
;
318 template <typename Stream
, typename Operation
>
319 inline void SerializationOp(Stream
& s
, Operation ser_action
) {
320 if (ser_action
.ForRead())
324 if (!ser_action
.ForRead())
326 mapValue
["fromaccount"] = strFromAccount
;
328 WriteOrderPos(nOrderPos
, mapValue
);
331 mapValue
["timesmart"] = strprintf("%u", nTimeSmart
);
334 READWRITE(*(CMerkleTx
*)this);
335 std::vector
<CMerkleTx
> vUnused
; //!< Used to be vtxPrev
338 READWRITE(vOrderForm
);
339 READWRITE(fTimeReceivedIsTxTime
);
340 READWRITE(nTimeReceived
);
344 if (ser_action
.ForRead())
346 strFromAccount
= mapValue
["fromaccount"];
348 ReadOrderPos(nOrderPos
, mapValue
);
350 nTimeSmart
= mapValue
.count("timesmart") ? (unsigned int)atoi64(mapValue
["timesmart"]) : 0;
353 mapValue
.erase("fromaccount");
354 mapValue
.erase("version");
355 mapValue
.erase("spent");
357 mapValue
.erase("timesmart");
360 //! make sure balances are recalculated
363 fCreditCached
= false;
364 fAvailableCreditCached
= false;
365 fWatchDebitCached
= false;
366 fWatchCreditCached
= false;
367 fAvailableWatchCreditCached
= false;
368 fImmatureWatchCreditCached
= false;
369 fDebitCached
= false;
370 fChangeCached
= false;
373 void BindWallet(CWallet
*pwalletIn
)
379 //! filter decides which addresses will count towards the debit
380 CAmount
GetDebit(const isminefilter
& filter
) const;
381 CAmount
GetCredit(const isminefilter
& filter
) const;
382 CAmount
GetImmatureCredit(bool fUseCache
=true) const;
383 CAmount
GetAvailableCredit(bool fUseCache
=true) const;
384 CAmount
GetImmatureWatchOnlyCredit(const bool& fUseCache
=true) const;
385 CAmount
GetAvailableWatchOnlyCredit(const bool& fUseCache
=true) const;
386 CAmount
GetChange() const;
388 void GetAmounts(std::list
<COutputEntry
>& listReceived
,
389 std::list
<COutputEntry
>& listSent
, CAmount
& nFee
, std::string
& strSentAccount
, const isminefilter
& filter
) const;
391 void GetAccountAmounts(const std::string
& strAccount
, CAmount
& nReceived
,
392 CAmount
& nSent
, CAmount
& nFee
, const isminefilter
& filter
) const;
394 bool IsFromMe(const isminefilter
& filter
) const
396 return (GetDebit(filter
) > 0);
399 // True if only scriptSigs are different
400 bool IsEquivalentTo(const CWalletTx
& tx
) const;
402 bool InMempool() const;
403 bool IsTrusted() const;
405 int64_t GetTxTime() const;
406 int GetRequestCount() const;
408 bool RelayWalletTransaction(CConnman
* connman
);
410 std::set
<uint256
> GetConflicts() const;
425 COutput(const CWalletTx
*txIn
, int iIn
, int nDepthIn
, bool fSpendableIn
, bool fSolvableIn
)
427 tx
= txIn
; i
= iIn
; nDepth
= nDepthIn
; fSpendable
= fSpendableIn
; fSolvable
= fSolvableIn
;
430 std::string
ToString() const;
436 /** Private key that includes an expiration date in case it never gets used. */
441 int64_t nTimeCreated
;
442 int64_t nTimeExpires
;
443 std::string strComment
;
444 //! todo: add something to note what created it (user, getnewaddress, change)
445 //! maybe should have a map<string, string> property map
447 CWalletKey(int64_t nExpires
=0);
449 ADD_SERIALIZE_METHODS
;
451 template <typename Stream
, typename Operation
>
452 inline void SerializationOp(Stream
& s
, Operation ser_action
) {
453 int nVersion
= s
.GetVersion();
454 if (!(s
.GetType() & SER_GETHASH
))
456 READWRITE(vchPrivKey
);
457 READWRITE(nTimeCreated
);
458 READWRITE(nTimeExpires
);
459 READWRITE(LIMITED_STRING(strComment
, 65536));
464 * Internal transfers.
465 * Database key is acentry<account><counter>.
467 class CAccountingEntry
470 std::string strAccount
;
471 CAmount nCreditDebit
;
473 std::string strOtherAccount
;
474 std::string strComment
;
476 int64_t nOrderPos
; //!< position in ordered transaction list
489 strOtherAccount
.clear();
495 ADD_SERIALIZE_METHODS
;
497 template <typename Stream
, typename Operation
>
498 inline void SerializationOp(Stream
& s
, Operation ser_action
) {
499 int nVersion
= s
.GetVersion();
500 if (!(s
.GetType() & SER_GETHASH
))
502 //! Note: strAccount is serialized as part of the key, not here.
503 READWRITE(nCreditDebit
);
505 READWRITE(LIMITED_STRING(strOtherAccount
, 65536));
507 if (!ser_action
.ForRead())
509 WriteOrderPos(nOrderPos
, mapValue
);
511 if (!(mapValue
.empty() && _ssExtra
.empty()))
513 CDataStream
ss(s
.GetType(), s
.GetVersion());
514 ss
.insert(ss
.begin(), '\0');
516 ss
.insert(ss
.end(), _ssExtra
.begin(), _ssExtra
.end());
517 strComment
.append(ss
.str());
521 READWRITE(LIMITED_STRING(strComment
, 65536));
523 size_t nSepPos
= strComment
.find("\0", 0, 1);
524 if (ser_action
.ForRead())
527 if (std::string::npos
!= nSepPos
)
529 CDataStream
ss(std::vector
<char>(strComment
.begin() + nSepPos
+ 1, strComment
.end()), s
.GetType(), s
.GetVersion());
531 _ssExtra
= std::vector
<char>(ss
.begin(), ss
.end());
533 ReadOrderPos(nOrderPos
, mapValue
);
535 if (std::string::npos
!= nSepPos
)
536 strComment
.erase(nSepPos
);
542 std::vector
<char> _ssExtra
;
547 * A CWallet is an extension of a keystore, which also maintains a set of transactions and balances,
548 * and provides the ability to create new transactions.
550 class CWallet
: public CCryptoKeyStore
, public CValidationInterface
554 * Select a set of coins such that nValueRet >= nTargetValue and at least
555 * all coins from coinControl are selected; Never select unconfirmed coins
556 * if they are not ours
558 bool SelectCoins(const std::vector
<COutput
>& vAvailableCoins
, const CAmount
& nTargetValue
, std::set
<std::pair
<const CWalletTx
*,unsigned int> >& setCoinsRet
, CAmount
& nValueRet
, const CCoinControl
*coinControl
= NULL
) const;
560 CWalletDB
*pwalletdbEncryption
;
562 //! the current wallet version: clients below this version are not able to load the wallet
565 //! the maximum wallet format version: memory-only variable that specifies to what version this wallet may be upgraded
566 int nWalletMaxVersion
;
570 bool fBroadcastTransactions
;
573 * Used to keep track of spent outpoints, and
574 * detect and report conflicts (double-spends or
575 * mutated transactions where the mutant gets mined).
577 typedef std::multimap
<COutPoint
, uint256
> TxSpends
;
578 TxSpends mapTxSpends
;
579 void AddToSpends(const COutPoint
& outpoint
, const uint256
& wtxid
);
580 void AddToSpends(const uint256
& wtxid
);
582 /* Mark a transaction (and its in-wallet descendants) as conflicting with a particular block. */
583 void MarkConflicted(const uint256
& hashBlock
, const uint256
& hashTx
);
585 void SyncMetaData(std::pair
<TxSpends::iterator
, TxSpends::iterator
>);
587 /* the HD chain data model (external chain counters) */
592 std::set
<int64_t> setKeyPool
;
596 * This lock protects all the fields added by CWallet
598 * fFileBacked (immutable after instantiation)
599 * strWalletFile (immutable after instantiation)
601 mutable CCriticalSection cs_wallet
;
603 std::string strWalletFile
;
605 void LoadKeyPool(int nIndex
, const CKeyPool
&keypool
)
607 setKeyPool
.insert(nIndex
);
609 // If no metadata exists yet, create a default with the pool key's
610 // creation time. Note that this may be overwritten by actually
611 // stored metadata for that key later, which is fine.
612 CKeyID keyid
= keypool
.vchPubKey
.GetID();
613 if (mapKeyMetadata
.count(keyid
) == 0)
614 mapKeyMetadata
[keyid
] = CKeyMetadata(keypool
.nTime
);
617 std::map
<CKeyID
, CKeyMetadata
> mapKeyMetadata
;
619 typedef std::map
<unsigned int, CMasterKey
> MasterKeyMap
;
620 MasterKeyMap mapMasterKeys
;
621 unsigned int nMasterKeyMaxID
;
628 CWallet(const std::string
& strWalletFileIn
)
632 strWalletFile
= strWalletFileIn
;
638 delete pwalletdbEncryption
;
639 pwalletdbEncryption
= NULL
;
644 nWalletVersion
= FEATURE_BASE
;
645 nWalletMaxVersion
= FEATURE_BASE
;
648 pwalletdbEncryption
= NULL
;
653 fBroadcastTransactions
= false;
656 std::map
<uint256
, CWalletTx
> mapWallet
;
657 std::list
<CAccountingEntry
> laccentries
;
659 typedef std::pair
<CWalletTx
*, CAccountingEntry
*> TxPair
;
660 typedef std::multimap
<int64_t, TxPair
> TxItems
;
663 int64_t nOrderPosNext
;
664 std::map
<uint256
, int> mapRequestCount
;
666 std::map
<CTxDestination
, CAddressBookData
> mapAddressBook
;
668 CPubKey vchDefaultKey
;
670 std::set
<COutPoint
> setLockedCoins
;
672 int64_t nTimeFirstKey
;
674 const CWalletTx
* GetWalletTx(const uint256
& hash
) const;
676 //! check whether we are allowed to upgrade (or already support) to the named feature
677 bool CanSupportFeature(enum WalletFeature wf
) { AssertLockHeld(cs_wallet
); return nWalletMaxVersion
>= wf
; }
680 * populate vCoins with vector of available COutputs.
682 void AvailableCoins(std::vector
<COutput
>& vCoins
, bool fOnlyConfirmed
=true, const CCoinControl
*coinControl
= NULL
, bool fIncludeZeroValue
=false) const;
685 * Shuffle and select coins until nTargetValue is reached while avoiding
686 * small change; This method is stochastic for some inputs and upon
687 * completion the coin set and corresponding actual target value is
690 bool SelectCoinsMinConf(const CAmount
& nTargetValue
, int nConfMine
, int nConfTheirs
, std::vector
<COutput
> vCoins
, std::set
<std::pair
<const CWalletTx
*,unsigned int> >& setCoinsRet
, CAmount
& nValueRet
) const;
692 bool IsSpent(const uint256
& hash
, unsigned int n
) const;
694 bool IsLockedCoin(uint256 hash
, unsigned int n
) const;
695 void LockCoin(const COutPoint
& output
);
696 void UnlockCoin(const COutPoint
& output
);
697 void UnlockAllCoins();
698 void ListLockedCoins(std::vector
<COutPoint
>& vOutpts
);
701 * keystore implementation
704 CPubKey
GenerateNewKey();
705 void DeriveNewChildKey(CKeyMetadata
& metadata
, CKey
& secret
);
706 //! Adds a key to the store, and saves it to disk.
707 bool AddKeyPubKey(const CKey
& key
, const CPubKey
&pubkey
);
708 //! Adds a key to the store, without saving it to disk (used by LoadWallet)
709 bool LoadKey(const CKey
& key
, const CPubKey
&pubkey
) { return CCryptoKeyStore::AddKeyPubKey(key
, pubkey
); }
710 //! Load metadata (used by LoadWallet)
711 bool LoadKeyMetadata(const CPubKey
&pubkey
, const CKeyMetadata
&metadata
);
713 bool LoadMinVersion(int nVersion
) { AssertLockHeld(cs_wallet
); nWalletVersion
= nVersion
; nWalletMaxVersion
= std::max(nWalletMaxVersion
, nVersion
); return true; }
715 //! Adds an encrypted key to the store, and saves it to disk.
716 bool AddCryptedKey(const CPubKey
&vchPubKey
, const std::vector
<unsigned char> &vchCryptedSecret
);
717 //! Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
718 bool LoadCryptedKey(const CPubKey
&vchPubKey
, const std::vector
<unsigned char> &vchCryptedSecret
);
719 bool AddCScript(const CScript
& redeemScript
);
720 bool LoadCScript(const CScript
& redeemScript
);
722 //! Adds a destination data tuple to the store, and saves it to disk
723 bool AddDestData(const CTxDestination
&dest
, const std::string
&key
, const std::string
&value
);
724 //! Erases a destination data tuple in the store and on disk
725 bool EraseDestData(const CTxDestination
&dest
, const std::string
&key
);
726 //! Adds a destination data tuple to the store, without saving it to disk
727 bool LoadDestData(const CTxDestination
&dest
, const std::string
&key
, const std::string
&value
);
728 //! Look up a destination data tuple in the store, return true if found false otherwise
729 bool GetDestData(const CTxDestination
&dest
, const std::string
&key
, std::string
*value
) const;
731 //! Adds a watch-only address to the store, and saves it to disk.
732 bool AddWatchOnly(const CScript
&dest
);
733 bool RemoveWatchOnly(const CScript
&dest
);
734 //! Adds a watch-only address to the store, without saving it to disk (used by LoadWallet)
735 bool LoadWatchOnly(const CScript
&dest
);
737 bool Unlock(const SecureString
& strWalletPassphrase
);
738 bool ChangeWalletPassphrase(const SecureString
& strOldWalletPassphrase
, const SecureString
& strNewWalletPassphrase
);
739 bool EncryptWallet(const SecureString
& strWalletPassphrase
);
741 void GetKeyBirthTimes(std::map
<CKeyID
, int64_t> &mapKeyBirth
) const;
744 * Increment the next transaction order id
745 * @return next transaction order id
747 int64_t IncOrderPosNext(CWalletDB
*pwalletdb
= NULL
);
748 DBErrors
ReorderTransactions();
749 bool AccountMove(std::string strFrom
, std::string strTo
, CAmount nAmount
, std::string strComment
= "");
750 bool GetAccountPubkey(CPubKey
&pubKey
, std::string strAccount
, bool bForceNew
= false);
753 bool AddToWallet(const CWalletTx
& wtxIn
, bool fFlushOnClose
=true);
754 bool LoadToWallet(const CWalletTx
& wtxIn
);
755 void SyncTransaction(const CTransaction
& tx
, const CBlockIndex
*pindex
, int posInBlock
);
756 bool AddToWalletIfInvolvingMe(const CTransaction
& tx
, const CBlockIndex
* pIndex
, int posInBlock
, bool fUpdate
);
757 int ScanForWalletTransactions(CBlockIndex
* pindexStart
, bool fUpdate
= false);
758 void ReacceptWalletTransactions();
759 void ResendWalletTransactions(int64_t nBestBlockTime
, CConnman
* connman
);
760 std::vector
<uint256
> ResendWalletTransactionsBefore(int64_t nTime
, CConnman
* connman
);
761 CAmount
GetBalance() const;
762 CAmount
GetUnconfirmedBalance() const;
763 CAmount
GetImmatureBalance() const;
764 CAmount
GetWatchOnlyBalance() const;
765 CAmount
GetUnconfirmedWatchOnlyBalance() const;
766 CAmount
GetImmatureWatchOnlyBalance() const;
769 * Insert additional inputs into the transaction by
770 * calling CreateTransaction();
772 bool FundTransaction(CMutableTransaction
& tx
, CAmount
& nFeeRet
, bool overrideEstimatedFeeRate
, const CFeeRate
& specificFeeRate
, int& nChangePosInOut
, std::string
& strFailReason
, bool includeWatching
, bool lockUnspents
, const CTxDestination
& destChange
= CNoDestination());
775 * Create a new transaction paying the recipients with a set of coins
776 * selected by SelectCoins(); Also create the change output, when needed
777 * @note passing nChangePosInOut as -1 will result in setting a random position
779 bool CreateTransaction(const std::vector
<CRecipient
>& vecSend
, CWalletTx
& wtxNew
, CReserveKey
& reservekey
, CAmount
& nFeeRet
, int& nChangePosInOut
,
780 std::string
& strFailReason
, const CCoinControl
*coinControl
= NULL
, bool sign
= true);
781 bool CommitTransaction(CWalletTx
& wtxNew
, CReserveKey
& reservekey
, CConnman
* connman
, CValidationState
& state
);
783 void ListAccountCreditDebit(const std::string
& strAccount
, std::list
<CAccountingEntry
>& entries
);
784 bool AddAccountingEntry(const CAccountingEntry
&);
785 bool AddAccountingEntry(const CAccountingEntry
&, CWalletDB
*pwalletdb
);
787 static CFeeRate minTxFee
;
788 static CFeeRate fallbackFee
;
790 * Estimate the minimum fee considering user set parameters
791 * and the required fee
793 static CAmount
GetMinimumFee(unsigned int nTxBytes
, unsigned int nConfirmTarget
, const CTxMemPool
& pool
);
795 * Return the minimum required fee taking into account the
796 * floating relay fee and user set minimum transaction fee
798 static CAmount
GetRequiredFee(unsigned int nTxBytes
);
801 bool TopUpKeyPool(unsigned int kpSize
= 0);
802 void ReserveKeyFromKeyPool(int64_t& nIndex
, CKeyPool
& keypool
);
803 void KeepKey(int64_t nIndex
);
804 void ReturnKey(int64_t nIndex
);
805 bool GetKeyFromPool(CPubKey
&key
);
806 int64_t GetOldestKeyPoolTime();
807 void GetAllReserveKeys(std::set
<CKeyID
>& setAddress
) const;
809 std::set
< std::set
<CTxDestination
> > GetAddressGroupings();
810 std::map
<CTxDestination
, CAmount
> GetAddressBalances();
812 CAmount
GetAccountBalance(const std::string
& strAccount
, int nMinDepth
, const isminefilter
& filter
);
813 CAmount
GetAccountBalance(CWalletDB
& walletdb
, const std::string
& strAccount
, int nMinDepth
, const isminefilter
& filter
);
814 std::set
<CTxDestination
> GetAccountAddresses(const std::string
& strAccount
) const;
816 isminetype
IsMine(const CTxIn
& txin
) const;
817 CAmount
GetDebit(const CTxIn
& txin
, const isminefilter
& filter
) const;
818 isminetype
IsMine(const CTxOut
& txout
) const;
819 CAmount
GetCredit(const CTxOut
& txout
, const isminefilter
& filter
) const;
820 bool IsChange(const CTxOut
& txout
) const;
821 CAmount
GetChange(const CTxOut
& txout
) const;
822 bool IsMine(const CTransaction
& tx
) const;
823 /** should probably be renamed to IsRelevantToMe */
824 bool IsFromMe(const CTransaction
& tx
) const;
825 CAmount
GetDebit(const CTransaction
& tx
, const isminefilter
& filter
) const;
826 CAmount
GetCredit(const CTransaction
& tx
, const isminefilter
& filter
) const;
827 CAmount
GetChange(const CTransaction
& tx
) const;
828 void SetBestChain(const CBlockLocator
& loc
);
830 DBErrors
LoadWallet(bool& fFirstRunRet
);
831 DBErrors
ZapWalletTx(std::vector
<CWalletTx
>& vWtx
);
832 DBErrors
ZapSelectTx(std::vector
<uint256
>& vHashIn
, std::vector
<uint256
>& vHashOut
);
834 bool SetAddressBook(const CTxDestination
& address
, const std::string
& strName
, const std::string
& purpose
);
836 bool DelAddressBook(const CTxDestination
& address
);
838 void UpdatedTransaction(const uint256
&hashTx
);
840 void Inventory(const uint256
&hash
)
844 std::map
<uint256
, int>::iterator mi
= mapRequestCount
.find(hash
);
845 if (mi
!= mapRequestCount
.end())
850 void GetScriptForMining(boost::shared_ptr
<CReserveScript
> &script
);
851 void ResetRequestCount(const uint256
&hash
)
854 mapRequestCount
[hash
] = 0;
857 unsigned int GetKeyPoolSize()
859 AssertLockHeld(cs_wallet
); // setKeyPool
860 return setKeyPool
.size();
863 bool SetDefaultKey(const CPubKey
&vchPubKey
);
865 //! signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
866 bool SetMinVersion(enum WalletFeature
, CWalletDB
* pwalletdbIn
= NULL
, bool fExplicit
= false);
868 //! change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
869 bool SetMaxVersion(int nVersion
);
871 //! get the current wallet format (the oldest client version guaranteed to understand this wallet)
872 int GetVersion() { LOCK(cs_wallet
); return nWalletVersion
; }
874 //! Get wallet transactions that conflict with given transaction (spend same outputs)
875 std::set
<uint256
> GetConflicts(const uint256
& txid
) const;
877 //! Flush wallet (bitdb flush)
878 void Flush(bool shutdown
=false);
880 //! Verify the wallet database and perform salvage if required
881 static bool Verify();
884 * Address book entry changed.
885 * @note called with lock cs_wallet held.
887 boost::signals2::signal
<void (CWallet
*wallet
, const CTxDestination
888 &address
, const std::string
&label
, bool isMine
,
889 const std::string
&purpose
,
890 ChangeType status
)> NotifyAddressBookChanged
;
893 * Wallet transaction added, removed or updated.
894 * @note called with lock cs_wallet held.
896 boost::signals2::signal
<void (CWallet
*wallet
, const uint256
&hashTx
,
897 ChangeType status
)> NotifyTransactionChanged
;
899 /** Show progress e.g. for rescan */
900 boost::signals2::signal
<void (const std::string
&title
, int nProgress
)> ShowProgress
;
902 /** Watch-only address added */
903 boost::signals2::signal
<void (bool fHaveWatchOnly
)> NotifyWatchonlyChanged
;
905 /** Inquire whether this wallet broadcasts transactions. */
906 bool GetBroadcastTransactions() const { return fBroadcastTransactions
; }
907 /** Set whether this wallet broadcasts transactions. */
908 void SetBroadcastTransactions(bool broadcast
) { fBroadcastTransactions
= broadcast
; }
910 /* Mark a transaction (and it in-wallet descendants) as abandoned so its inputs may be respent. */
911 bool AbandonTransaction(const uint256
& hashTx
);
913 /* Returns the wallets help message */
914 static std::string
GetWalletHelpString(bool showDebug
);
916 /* Initializes the wallet, returns a new CWallet instance or a null pointer in case of an error */
917 static bool InitLoadWallet();
920 * Wallet post-init setup
921 * Gives the wallet a chance to register repetitive tasks and complete post-init tasks
923 void postInitProcess(boost::thread_group
& threadGroup
);
925 /* Wallets parameter interaction */
926 static bool ParameterInteraction();
928 bool BackupWallet(const std::string
& strDest
);
930 /* Set the HD chain model (chain child index counters) */
931 bool SetHDChain(const CHDChain
& chain
, bool memonly
);
932 const CHDChain
& GetHDChain() { return hdChain
; }
934 /* Returns true if HD is enabled */
937 /* Generates a new HD master key (will not be activated) */
938 CPubKey
GenerateNewHDMasterKey();
940 /* Set the current HD master key (will reset the chain child index counters) */
941 bool SetHDMasterKey(const CPubKey
& key
);
944 /** A key allocated from the key pool. */
945 class CReserveKey
: public CReserveScript
952 CReserveKey(CWallet
* pwalletIn
)
964 bool GetReservedKey(CPubKey
&pubkey
);
966 void KeepScript() { KeepKey(); }
971 * Account information.
972 * Stored in wallet with key "acc"+string account name.
986 vchPubKey
= CPubKey();
989 ADD_SERIALIZE_METHODS
;
991 template <typename Stream
, typename Operation
>
992 inline void SerializationOp(Stream
& s
, Operation ser_action
) {
993 int nVersion
= s
.GetVersion();
994 if (!(s
.GetType() & SER_GETHASH
))
996 READWRITE(vchPubKey
);
1000 #endif // BITCOIN_WALLET_WALLET_H