1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 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 "script/sign.h"
17 #include "wallet/crypter.h"
18 #include "wallet/walletdb.h"
19 #include "wallet/rpcwallet.h"
31 #include <boost/shared_ptr.hpp>
33 extern CWallet
* pwalletMain
;
38 extern CFeeRate payTxFee
;
39 extern unsigned int nTxConfirmTarget
;
40 extern bool bSpendZeroConfChange
;
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 recommended increment for BIP 125 replacement txs
51 static const CAmount WALLET_INCREMENTAL_RELAY_FEE
= 5000;
52 //! target minimum change amount
53 static const CAmount MIN_CHANGE
= CENT
;
54 //! final minimum change amount after paying for fees
55 static const CAmount MIN_FINAL_CHANGE
= MIN_CHANGE
/2;
56 //! Default for -spendzeroconfchange
57 static const bool DEFAULT_SPEND_ZEROCONF_CHANGE
= true;
58 //! Default for -walletrejectlongchains
59 static const bool DEFAULT_WALLET_REJECT_LONG_CHAINS
= false;
60 //! -txconfirmtarget default
61 static const unsigned int DEFAULT_TX_CONFIRM_TARGET
= 6;
62 //! -walletrbf default
63 static const bool DEFAULT_WALLET_RBF
= false;
64 static const bool DEFAULT_WALLETBROADCAST
= true;
65 static const bool DEFAULT_DISABLE_WALLET
= false;
66 //! if set, all keys will be derived by using BIP32
67 static const bool DEFAULT_USE_HD_WALLET
= true;
69 extern const char * DEFAULT_WALLET_DAT
;
80 /** (client) version numbers for particular wallet features */
83 FEATURE_BASE
= 10500, // the earliest version new wallets supports (only useful for getinfo's clientversion output)
85 FEATURE_WALLETCRYPT
= 40000, // wallet encryption
86 FEATURE_COMPRPUBKEY
= 60000, // compressed public keys
88 FEATURE_HD
= 130000, // Hierarchical key derivation after BIP32 (HD Wallet)
90 FEATURE_HD_SPLIT
= 139900, // Wallet with HD chain split (change outputs will use m/0'/1'/k)
92 FEATURE_LATEST
= FEATURE_COMPRPUBKEY
// HD is optional, use FEATURE_COMPRPUBKEY as latest version
96 /** A key pool entry */
102 bool fInternal
; // for change outputs
105 CKeyPool(const CPubKey
& vchPubKeyIn
, bool internalIn
);
107 ADD_SERIALIZE_METHODS
;
109 template <typename Stream
, typename Operation
>
110 inline void SerializationOp(Stream
& s
, Operation ser_action
) {
111 int nVersion
= s
.GetVersion();
112 if (!(s
.GetType() & SER_GETHASH
))
115 READWRITE(vchPubKey
);
116 if (ser_action
.ForRead()) {
118 READWRITE(fInternal
);
120 catch (std::ios_base::failure
&) {
121 /* flag as external address if we can't read the internal boolean
122 (this will be the case for any wallet before the HD chain split version) */
127 READWRITE(fInternal
);
132 /** Address book data */
133 class CAddressBookData
144 typedef std::map
<std::string
, std::string
> StringMap
;
150 CScript scriptPubKey
;
152 bool fSubtractFeeFromAmount
;
155 typedef std::map
<std::string
, std::string
> mapValue_t
;
158 static inline void ReadOrderPos(int64_t& nOrderPos
, mapValue_t
& mapValue
)
160 if (!mapValue
.count("n"))
162 nOrderPos
= -1; // TODO: calculate elsewhere
165 nOrderPos
= atoi64(mapValue
["n"].c_str());
169 static inline void WriteOrderPos(const int64_t& nOrderPos
, mapValue_t
& mapValue
)
173 mapValue
["n"] = i64tostr(nOrderPos
);
178 CTxDestination destination
;
183 /** A transaction with a merkle branch linking it to the block chain. */
187 /** Constant used in hashBlock to indicate tx has been abandoned */
188 static const uint256 ABANDON_HASH
;
194 /* An nIndex == -1 means that hashBlock (in nonzero) refers to the earliest
195 * block in the chain we know this or any in-wallet dependency conflicts
196 * with. Older clients interpret nIndex == -1 as unconfirmed for backward
203 SetTx(MakeTransactionRef());
207 CMerkleTx(CTransactionRef arg
)
209 SetTx(std::move(arg
));
213 /** Helper conversion operator to allow passing CMerkleTx where CTransaction is expected.
214 * TODO: adapt callers and remove this operator. */
215 operator const CTransaction
&() const { return *tx
; }
219 hashBlock
= uint256();
223 void SetTx(CTransactionRef arg
)
228 ADD_SERIALIZE_METHODS
;
230 template <typename Stream
, typename Operation
>
231 inline void SerializationOp(Stream
& s
, Operation ser_action
) {
232 std::vector
<uint256
> vMerkleBranch
; // For compatibility with older versions.
234 READWRITE(hashBlock
);
235 READWRITE(vMerkleBranch
);
239 void SetMerkleBranch(const CBlockIndex
* pIndex
, int posInBlock
);
242 * Return depth of transaction in blockchain:
243 * <0 : conflicts with a transaction this deep in the blockchain
244 * 0 : in memory pool, waiting to be included in a block
245 * >=1 : this many blocks deep in the main chain
247 int GetDepthInMainChain(const CBlockIndex
* &pindexRet
) const;
248 int GetDepthInMainChain() const { const CBlockIndex
*pindexRet
; return GetDepthInMainChain(pindexRet
); }
249 bool IsInMainChain() const { const CBlockIndex
*pindexRet
; return GetDepthInMainChain(pindexRet
) > 0; }
250 int GetBlocksToMaturity() const;
251 /** Pass this transaction to the mempool. Fails if absolute fee exceeds absurd fee. */
252 bool AcceptToMemoryPool(const CAmount
& nAbsurdFee
, CValidationState
& state
);
253 bool hashUnset() const { return (hashBlock
.IsNull() || hashBlock
== ABANDON_HASH
); }
254 bool isAbandoned() const { return (hashBlock
== ABANDON_HASH
); }
255 void setAbandoned() { hashBlock
= ABANDON_HASH
; }
257 const uint256
& GetHash() const { return tx
->GetHash(); }
258 bool IsCoinBase() const { return tx
->IsCoinBase(); }
262 * A transaction with a bunch of additional info that only the owner cares about.
263 * It includes any unrecorded transactions needed to link it back to the block chain.
265 class CWalletTx
: public CMerkleTx
268 const CWallet
* pwallet
;
272 * Key/value map with information about the transaction.
274 * The following keys can be read and written through the map and are
275 * serialized in the wallet database:
277 * "comment", "to" - comment strings provided to sendtoaddress,
278 * sendfrom, sendmany wallet RPCs
279 * "replaces_txid" - txid (as HexStr) of transaction replaced by
280 * bumpfee on transaction created by bumpfee
281 * "replaced_by_txid" - txid (as HexStr) of transaction created by
282 * bumpfee on transaction replaced by bumpfee
283 * "from", "message" - obsolete fields that could be set in UI prior to
284 * 2011 (removed in commit 4d9b223)
286 * The following keys are serialized in the wallet database, but shouldn't
287 * be read or written through the map (they will be temporarily added and
288 * removed from the map during serialization):
290 * "fromaccount" - serialized strFromAccount value
291 * "n" - serialized nOrderPos value
292 * "timesmart" - serialized nTimeSmart value
293 * "spent" - serialized vfSpent value that existed prior to
294 * 2014 (removed in commit 93a18a3)
297 std::vector
<std::pair
<std::string
, std::string
> > vOrderForm
;
298 unsigned int fTimeReceivedIsTxTime
;
299 unsigned int nTimeReceived
; //!< time received by this node
301 * Stable timestamp that never changes, and reflects the order a transaction
302 * was added to the wallet. Timestamp is based on the block time for a
303 * transaction added as part of a block, or else the time when the
304 * transaction was received if it wasn't part of a block, with the timestamp
305 * adjusted in both cases so timestamp order matches the order transactions
306 * were added to the wallet. More details can be found in
307 * CWallet::ComputeTimeSmart().
309 unsigned int nTimeSmart
;
311 * From me flag is set to 1 for transactions that were created by the wallet
312 * on this bitcoin node, and set to 0 for transactions that were created
313 * externally and came in through the network or sendrawtransaction RPC.
316 std::string strFromAccount
;
317 int64_t nOrderPos
; //!< position in ordered transaction list
320 mutable bool fDebitCached
;
321 mutable bool fCreditCached
;
322 mutable bool fImmatureCreditCached
;
323 mutable bool fAvailableCreditCached
;
324 mutable bool fWatchDebitCached
;
325 mutable bool fWatchCreditCached
;
326 mutable bool fImmatureWatchCreditCached
;
327 mutable bool fAvailableWatchCreditCached
;
328 mutable bool fChangeCached
;
329 mutable CAmount nDebitCached
;
330 mutable CAmount nCreditCached
;
331 mutable CAmount nImmatureCreditCached
;
332 mutable CAmount nAvailableCreditCached
;
333 mutable CAmount nWatchDebitCached
;
334 mutable CAmount nWatchCreditCached
;
335 mutable CAmount nImmatureWatchCreditCached
;
336 mutable CAmount nAvailableWatchCreditCached
;
337 mutable CAmount nChangeCached
;
344 CWalletTx(const CWallet
* pwalletIn
, CTransactionRef arg
) : CMerkleTx(std::move(arg
))
349 void Init(const CWallet
* pwalletIn
)
354 fTimeReceivedIsTxTime
= false;
358 strFromAccount
.clear();
359 fDebitCached
= false;
360 fCreditCached
= false;
361 fImmatureCreditCached
= false;
362 fAvailableCreditCached
= false;
363 fWatchDebitCached
= false;
364 fWatchCreditCached
= false;
365 fImmatureWatchCreditCached
= false;
366 fAvailableWatchCreditCached
= false;
367 fChangeCached
= false;
370 nImmatureCreditCached
= 0;
371 nAvailableCreditCached
= 0;
372 nWatchDebitCached
= 0;
373 nWatchCreditCached
= 0;
374 nAvailableWatchCreditCached
= 0;
375 nImmatureWatchCreditCached
= 0;
380 ADD_SERIALIZE_METHODS
;
382 template <typename Stream
, typename Operation
>
383 inline void SerializationOp(Stream
& s
, Operation ser_action
) {
384 if (ser_action
.ForRead())
388 if (!ser_action
.ForRead())
390 mapValue
["fromaccount"] = strFromAccount
;
392 WriteOrderPos(nOrderPos
, mapValue
);
395 mapValue
["timesmart"] = strprintf("%u", nTimeSmart
);
398 READWRITE(*(CMerkleTx
*)this);
399 std::vector
<CMerkleTx
> vUnused
; //!< Used to be vtxPrev
402 READWRITE(vOrderForm
);
403 READWRITE(fTimeReceivedIsTxTime
);
404 READWRITE(nTimeReceived
);
408 if (ser_action
.ForRead())
410 strFromAccount
= mapValue
["fromaccount"];
412 ReadOrderPos(nOrderPos
, mapValue
);
414 nTimeSmart
= mapValue
.count("timesmart") ? (unsigned int)atoi64(mapValue
["timesmart"]) : 0;
417 mapValue
.erase("fromaccount");
418 mapValue
.erase("spent");
420 mapValue
.erase("timesmart");
423 //! make sure balances are recalculated
426 fCreditCached
= false;
427 fAvailableCreditCached
= false;
428 fImmatureCreditCached
= false;
429 fWatchDebitCached
= false;
430 fWatchCreditCached
= false;
431 fAvailableWatchCreditCached
= false;
432 fImmatureWatchCreditCached
= false;
433 fDebitCached
= false;
434 fChangeCached
= false;
437 void BindWallet(CWallet
*pwalletIn
)
443 //! filter decides which addresses will count towards the debit
444 CAmount
GetDebit(const isminefilter
& filter
) const;
445 CAmount
GetCredit(const isminefilter
& filter
) const;
446 CAmount
GetImmatureCredit(bool fUseCache
=true) const;
447 CAmount
GetAvailableCredit(bool fUseCache
=true) const;
448 CAmount
GetImmatureWatchOnlyCredit(const bool& fUseCache
=true) const;
449 CAmount
GetAvailableWatchOnlyCredit(const bool& fUseCache
=true) const;
450 CAmount
GetChange() const;
452 void GetAmounts(std::list
<COutputEntry
>& listReceived
,
453 std::list
<COutputEntry
>& listSent
, CAmount
& nFee
, std::string
& strSentAccount
, const isminefilter
& filter
) const;
455 void GetAccountAmounts(const std::string
& strAccount
, CAmount
& nReceived
,
456 CAmount
& nSent
, CAmount
& nFee
, const isminefilter
& filter
) const;
458 bool IsFromMe(const isminefilter
& filter
) const
460 return (GetDebit(filter
) > 0);
463 // True if only scriptSigs are different
464 bool IsEquivalentTo(const CWalletTx
& tx
) const;
466 bool InMempool() const;
467 bool IsTrusted() const;
469 int64_t GetTxTime() const;
470 int GetRequestCount() const;
472 bool RelayWalletTransaction(CConnman
* connman
);
474 std::set
<uint256
> GetConflicts() const;
487 /** Whether we have the private keys to spend this output */
490 /** Whether we know how to spend this output, ignoring the lack of keys */
494 * Whether this output is considered safe to spend. Unconfirmed transactions
495 * from outside keys and unconfirmed replacement transactions are considered
496 * unsafe and will not be used to fund new spending transactions.
500 COutput(const CWalletTx
*txIn
, int iIn
, int nDepthIn
, bool fSpendableIn
, bool fSolvableIn
, bool fSafeIn
)
502 tx
= txIn
; i
= iIn
; nDepth
= nDepthIn
; fSpendable
= fSpendableIn
; fSolvable
= fSolvableIn
; fSafe
= fSafeIn
;
505 std::string
ToString() const;
511 /** Private key that includes an expiration date in case it never gets used. */
516 int64_t nTimeCreated
;
517 int64_t nTimeExpires
;
518 std::string strComment
;
519 //! todo: add something to note what created it (user, getnewaddress, change)
520 //! maybe should have a map<string, string> property map
522 CWalletKey(int64_t nExpires
=0);
524 ADD_SERIALIZE_METHODS
;
526 template <typename Stream
, typename Operation
>
527 inline void SerializationOp(Stream
& s
, Operation ser_action
) {
528 int nVersion
= s
.GetVersion();
529 if (!(s
.GetType() & SER_GETHASH
))
531 READWRITE(vchPrivKey
);
532 READWRITE(nTimeCreated
);
533 READWRITE(nTimeExpires
);
534 READWRITE(LIMITED_STRING(strComment
, 65536));
539 * Internal transfers.
540 * Database key is acentry<account><counter>.
542 class CAccountingEntry
545 std::string strAccount
;
546 CAmount nCreditDebit
;
548 std::string strOtherAccount
;
549 std::string strComment
;
551 int64_t nOrderPos
; //!< position in ordered transaction list
564 strOtherAccount
.clear();
570 ADD_SERIALIZE_METHODS
;
572 template <typename Stream
, typename Operation
>
573 inline void SerializationOp(Stream
& s
, Operation ser_action
) {
574 int nVersion
= s
.GetVersion();
575 if (!(s
.GetType() & SER_GETHASH
))
577 //! Note: strAccount is serialized as part of the key, not here.
578 READWRITE(nCreditDebit
);
580 READWRITE(LIMITED_STRING(strOtherAccount
, 65536));
582 if (!ser_action
.ForRead())
584 WriteOrderPos(nOrderPos
, mapValue
);
586 if (!(mapValue
.empty() && _ssExtra
.empty()))
588 CDataStream
ss(s
.GetType(), s
.GetVersion());
589 ss
.insert(ss
.begin(), '\0');
591 ss
.insert(ss
.end(), _ssExtra
.begin(), _ssExtra
.end());
592 strComment
.append(ss
.str());
596 READWRITE(LIMITED_STRING(strComment
, 65536));
598 size_t nSepPos
= strComment
.find("\0", 0, 1);
599 if (ser_action
.ForRead())
602 if (std::string::npos
!= nSepPos
)
604 CDataStream
ss(std::vector
<char>(strComment
.begin() + nSepPos
+ 1, strComment
.end()), s
.GetType(), s
.GetVersion());
606 _ssExtra
= std::vector
<char>(ss
.begin(), ss
.end());
608 ReadOrderPos(nOrderPos
, mapValue
);
610 if (std::string::npos
!= nSepPos
)
611 strComment
.erase(nSepPos
);
617 std::vector
<char> _ssExtra
;
622 * A CWallet is an extension of a keystore, which also maintains a set of transactions and balances,
623 * and provides the ability to create new transactions.
625 class CWallet
: public CCryptoKeyStore
, public CValidationInterface
628 static std::atomic
<bool> fFlushScheduled
;
631 * Select a set of coins such that nValueRet >= nTargetValue and at least
632 * all coins from coinControl are selected; Never select unconfirmed coins
633 * if they are not ours
635 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;
637 CWalletDB
*pwalletdbEncryption
;
639 //! the current wallet version: clients below this version are not able to load the wallet
642 //! the maximum wallet format version: memory-only variable that specifies to what version this wallet may be upgraded
643 int nWalletMaxVersion
;
647 bool fBroadcastTransactions
;
650 * Used to keep track of spent outpoints, and
651 * detect and report conflicts (double-spends or
652 * mutated transactions where the mutant gets mined).
654 typedef std::multimap
<COutPoint
, uint256
> TxSpends
;
655 TxSpends mapTxSpends
;
656 void AddToSpends(const COutPoint
& outpoint
, const uint256
& wtxid
);
657 void AddToSpends(const uint256
& wtxid
);
659 /* Mark a transaction (and its in-wallet descendants) as conflicting with a particular block. */
660 void MarkConflicted(const uint256
& hashBlock
, const uint256
& hashTx
);
662 void SyncMetaData(std::pair
<TxSpends::iterator
, TxSpends::iterator
>);
664 /* the HD chain data model (external chain counters) */
667 /* HD derive new child key (on internal or external chain) */
668 void DeriveNewChildKey(CKeyMetadata
& metadata
, CKey
& secret
, bool internal
= false);
672 std::set
<int64_t> setKeyPool
;
674 int64_t nTimeFirstKey
;
677 * Private version of AddWatchOnly method which does not accept a
678 * timestamp, and which will reset the wallet's nTimeFirstKey value to 1 if
679 * the watch key did not previously have a timestamp associated with it.
680 * Because this is an inherited virtual method, it is accessible despite
681 * being marked private, but it is marked private anyway to encourage use
682 * of the other AddWatchOnly which accepts a timestamp and sets
683 * nTimeFirstKey more intelligently for more efficient rescans.
685 bool AddWatchOnly(const CScript
& dest
) override
;
690 * This lock protects all the fields added by CWallet
692 * fFileBacked (immutable after instantiation)
693 * strWalletFile (immutable after instantiation)
695 mutable CCriticalSection cs_wallet
;
697 const std::string strWalletFile
;
699 void LoadKeyPool(int nIndex
, const CKeyPool
&keypool
)
701 setKeyPool
.insert(nIndex
);
703 // If no metadata exists yet, create a default with the pool key's
704 // creation time. Note that this may be overwritten by actually
705 // stored metadata for that key later, which is fine.
706 CKeyID keyid
= keypool
.vchPubKey
.GetID();
707 if (mapKeyMetadata
.count(keyid
) == 0)
708 mapKeyMetadata
[keyid
] = CKeyMetadata(keypool
.nTime
);
711 // Map from Key ID (for regular keys) or Script ID (for watch-only keys) to
713 std::map
<CTxDestination
, CKeyMetadata
> mapKeyMetadata
;
715 typedef std::map
<unsigned int, CMasterKey
> MasterKeyMap
;
716 MasterKeyMap mapMasterKeys
;
717 unsigned int nMasterKeyMaxID
;
724 CWallet(const std::string
& strWalletFileIn
) : strWalletFile(strWalletFileIn
)
732 delete pwalletdbEncryption
;
733 pwalletdbEncryption
= NULL
;
738 nWalletVersion
= FEATURE_BASE
;
739 nWalletMaxVersion
= FEATURE_BASE
;
742 pwalletdbEncryption
= NULL
;
747 fBroadcastTransactions
= false;
751 std::map
<uint256
, CWalletTx
> mapWallet
;
752 std::list
<CAccountingEntry
> laccentries
;
754 typedef std::pair
<CWalletTx
*, CAccountingEntry
*> TxPair
;
755 typedef std::multimap
<int64_t, TxPair
> TxItems
;
758 int64_t nOrderPosNext
;
759 std::map
<uint256
, int> mapRequestCount
;
761 std::map
<CTxDestination
, CAddressBookData
> mapAddressBook
;
763 CPubKey vchDefaultKey
;
765 std::set
<COutPoint
> setLockedCoins
;
767 const CWalletTx
* GetWalletTx(const uint256
& hash
) const;
769 //! check whether we are allowed to upgrade (or already support) to the named feature
770 bool CanSupportFeature(enum WalletFeature wf
) { AssertLockHeld(cs_wallet
); return nWalletMaxVersion
>= wf
; }
773 * populate vCoins with vector of available COutputs.
775 void AvailableCoins(std::vector
<COutput
>& vCoins
, bool fOnlySafe
=true, const CCoinControl
*coinControl
= NULL
, bool fIncludeZeroValue
=false) const;
778 * Shuffle and select coins until nTargetValue is reached while avoiding
779 * small change; This method is stochastic for some inputs and upon
780 * completion the coin set and corresponding actual target value is
783 bool SelectCoinsMinConf(const CAmount
& nTargetValue
, int nConfMine
, int nConfTheirs
, uint64_t nMaxAncestors
, std::vector
<COutput
> vCoins
, std::set
<std::pair
<const CWalletTx
*,unsigned int> >& setCoinsRet
, CAmount
& nValueRet
) const;
785 bool IsSpent(const uint256
& hash
, unsigned int n
) const;
787 bool IsLockedCoin(uint256 hash
, unsigned int n
) const;
788 void LockCoin(const COutPoint
& output
);
789 void UnlockCoin(const COutPoint
& output
);
790 void UnlockAllCoins();
791 void ListLockedCoins(std::vector
<COutPoint
>& vOutpts
);
794 * keystore implementation
797 CPubKey
GenerateNewKey(bool internal
= false);
798 //! Adds a key to the store, and saves it to disk.
799 bool AddKeyPubKey(const CKey
& key
, const CPubKey
&pubkey
) override
;
800 //! Adds a key to the store, without saving it to disk (used by LoadWallet)
801 bool LoadKey(const CKey
& key
, const CPubKey
&pubkey
) { return CCryptoKeyStore::AddKeyPubKey(key
, pubkey
); }
802 //! Load metadata (used by LoadWallet)
803 bool LoadKeyMetadata(const CTxDestination
& pubKey
, const CKeyMetadata
&metadata
);
805 bool LoadMinVersion(int nVersion
) { AssertLockHeld(cs_wallet
); nWalletVersion
= nVersion
; nWalletMaxVersion
= std::max(nWalletMaxVersion
, nVersion
); return true; }
806 void UpdateTimeFirstKey(int64_t nCreateTime
);
808 //! Adds an encrypted key to the store, and saves it to disk.
809 bool AddCryptedKey(const CPubKey
&vchPubKey
, const std::vector
<unsigned char> &vchCryptedSecret
) override
;
810 //! Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
811 bool LoadCryptedKey(const CPubKey
&vchPubKey
, const std::vector
<unsigned char> &vchCryptedSecret
);
812 bool AddCScript(const CScript
& redeemScript
) override
;
813 bool LoadCScript(const CScript
& redeemScript
);
815 //! Adds a destination data tuple to the store, and saves it to disk
816 bool AddDestData(const CTxDestination
&dest
, const std::string
&key
, const std::string
&value
);
817 //! Erases a destination data tuple in the store and on disk
818 bool EraseDestData(const CTxDestination
&dest
, const std::string
&key
);
819 //! Adds a destination data tuple to the store, without saving it to disk
820 bool LoadDestData(const CTxDestination
&dest
, const std::string
&key
, const std::string
&value
);
821 //! Look up a destination data tuple in the store, return true if found false otherwise
822 bool GetDestData(const CTxDestination
&dest
, const std::string
&key
, std::string
*value
) const;
824 //! Adds a watch-only address to the store, and saves it to disk.
825 bool AddWatchOnly(const CScript
& dest
, int64_t nCreateTime
);
826 bool RemoveWatchOnly(const CScript
&dest
) override
;
827 //! Adds a watch-only address to the store, without saving it to disk (used by LoadWallet)
828 bool LoadWatchOnly(const CScript
&dest
);
830 //! Holds a timestamp at which point the wallet is scheduled (externally) to be relocked. Caller must arrange for actual relocking to occur via Lock().
833 bool Unlock(const SecureString
& strWalletPassphrase
);
834 bool ChangeWalletPassphrase(const SecureString
& strOldWalletPassphrase
, const SecureString
& strNewWalletPassphrase
);
835 bool EncryptWallet(const SecureString
& strWalletPassphrase
);
837 void GetKeyBirthTimes(std::map
<CTxDestination
, int64_t> &mapKeyBirth
) const;
838 unsigned int ComputeTimeSmart(const CWalletTx
& wtx
) const;
841 * Increment the next transaction order id
842 * @return next transaction order id
844 int64_t IncOrderPosNext(CWalletDB
*pwalletdb
= NULL
);
845 DBErrors
ReorderTransactions();
846 bool AccountMove(std::string strFrom
, std::string strTo
, CAmount nAmount
, std::string strComment
= "");
847 bool GetAccountPubkey(CPubKey
&pubKey
, std::string strAccount
, bool bForceNew
= false);
850 bool AddToWallet(const CWalletTx
& wtxIn
, bool fFlushOnClose
=true);
851 bool LoadToWallet(const CWalletTx
& wtxIn
);
852 void SyncTransaction(const CTransaction
& tx
, const CBlockIndex
*pindex
, int posInBlock
) override
;
853 bool AddToWalletIfInvolvingMe(const CTransaction
& tx
, const CBlockIndex
* pIndex
, int posInBlock
, bool fUpdate
);
854 CBlockIndex
* ScanForWalletTransactions(CBlockIndex
* pindexStart
, bool fUpdate
= false);
855 void ReacceptWalletTransactions();
856 void ResendWalletTransactions(int64_t nBestBlockTime
, CConnman
* connman
) override
;
857 std::vector
<uint256
> ResendWalletTransactionsBefore(int64_t nTime
, CConnman
* connman
);
858 CAmount
GetBalance() const;
859 CAmount
GetUnconfirmedBalance() const;
860 CAmount
GetImmatureBalance() const;
861 CAmount
GetWatchOnlyBalance() const;
862 CAmount
GetUnconfirmedWatchOnlyBalance() const;
863 CAmount
GetImmatureWatchOnlyBalance() const;
866 * Insert additional inputs into the transaction by
867 * calling CreateTransaction();
869 bool FundTransaction(CMutableTransaction
& tx
, CAmount
& nFeeRet
, bool overrideEstimatedFeeRate
, const CFeeRate
& specificFeeRate
, int& nChangePosInOut
, std::string
& strFailReason
, bool includeWatching
, bool lockUnspents
, const std::set
<int>& setSubtractFeeFromOutputs
, bool keepReserveKey
= true, const CTxDestination
& destChange
= CNoDestination());
872 * Create a new transaction paying the recipients with a set of coins
873 * selected by SelectCoins(); Also create the change output, when needed
874 * @note passing nChangePosInOut as -1 will result in setting a random position
876 bool CreateTransaction(const std::vector
<CRecipient
>& vecSend
, CWalletTx
& wtxNew
, CReserveKey
& reservekey
, CAmount
& nFeeRet
, int& nChangePosInOut
,
877 std::string
& strFailReason
, const CCoinControl
*coinControl
= NULL
, bool sign
= true);
878 bool CommitTransaction(CWalletTx
& wtxNew
, CReserveKey
& reservekey
, CConnman
* connman
, CValidationState
& state
);
880 void ListAccountCreditDebit(const std::string
& strAccount
, std::list
<CAccountingEntry
>& entries
);
881 bool AddAccountingEntry(const CAccountingEntry
&);
882 bool AddAccountingEntry(const CAccountingEntry
&, CWalletDB
*pwalletdb
);
883 template <typename ContainerType
>
884 bool DummySignTx(CMutableTransaction
&txNew
, const ContainerType
&coins
);
886 static CFeeRate minTxFee
;
887 static CFeeRate fallbackFee
;
889 * Estimate the minimum fee considering user set parameters
890 * and the required fee
892 static CAmount
GetMinimumFee(unsigned int nTxBytes
, unsigned int nConfirmTarget
, const CTxMemPool
& pool
);
894 * Estimate the minimum fee considering required fee and targetFee or if 0
895 * then fee estimation for nConfirmTarget
897 static CAmount
GetMinimumFee(unsigned int nTxBytes
, unsigned int nConfirmTarget
, const CTxMemPool
& pool
, CAmount targetFee
);
899 * Return the minimum required fee taking into account the
900 * floating relay fee and user set minimum transaction fee
902 static CAmount
GetRequiredFee(unsigned int nTxBytes
);
905 size_t KeypoolCountExternalKeys();
906 bool TopUpKeyPool(unsigned int kpSize
= 0);
907 void ReserveKeyFromKeyPool(int64_t& nIndex
, CKeyPool
& keypool
, bool internal
);
908 void KeepKey(int64_t nIndex
);
909 void ReturnKey(int64_t nIndex
);
910 bool GetKeyFromPool(CPubKey
&key
, bool internal
= false);
911 int64_t GetOldestKeyPoolTime();
912 void GetAllReserveKeys(std::set
<CKeyID
>& setAddress
) const;
914 std::set
< std::set
<CTxDestination
> > GetAddressGroupings();
915 std::map
<CTxDestination
, CAmount
> GetAddressBalances();
917 CAmount
GetAccountBalance(const std::string
& strAccount
, int nMinDepth
, const isminefilter
& filter
);
918 CAmount
GetAccountBalance(CWalletDB
& walletdb
, const std::string
& strAccount
, int nMinDepth
, const isminefilter
& filter
);
919 std::set
<CTxDestination
> GetAccountAddresses(const std::string
& strAccount
) const;
921 isminetype
IsMine(const CTxIn
& txin
) const;
923 * Returns amount of debit if the input matches the
924 * filter, otherwise returns 0
926 CAmount
GetDebit(const CTxIn
& txin
, const isminefilter
& filter
) const;
927 isminetype
IsMine(const CTxOut
& txout
) const;
928 CAmount
GetCredit(const CTxOut
& txout
, const isminefilter
& filter
) const;
929 bool IsChange(const CTxOut
& txout
) const;
930 CAmount
GetChange(const CTxOut
& txout
) const;
931 bool IsMine(const CTransaction
& tx
) const;
932 /** should probably be renamed to IsRelevantToMe */
933 bool IsFromMe(const CTransaction
& tx
) const;
934 CAmount
GetDebit(const CTransaction
& tx
, const isminefilter
& filter
) const;
935 /** Returns whether all of the inputs match the filter */
936 bool IsAllFromMe(const CTransaction
& tx
, const isminefilter
& filter
) const;
937 CAmount
GetCredit(const CTransaction
& tx
, const isminefilter
& filter
) const;
938 CAmount
GetChange(const CTransaction
& tx
) const;
939 void SetBestChain(const CBlockLocator
& loc
) override
;
941 DBErrors
LoadWallet(bool& fFirstRunRet
);
942 DBErrors
ZapWalletTx(std::vector
<CWalletTx
>& vWtx
);
943 DBErrors
ZapSelectTx(std::vector
<uint256
>& vHashIn
, std::vector
<uint256
>& vHashOut
);
945 bool SetAddressBook(const CTxDestination
& address
, const std::string
& strName
, const std::string
& purpose
);
947 bool DelAddressBook(const CTxDestination
& address
);
949 void UpdatedTransaction(const uint256
&hashTx
) override
;
951 void Inventory(const uint256
&hash
) override
955 std::map
<uint256
, int>::iterator mi
= mapRequestCount
.find(hash
);
956 if (mi
!= mapRequestCount
.end())
961 void GetScriptForMining(boost::shared_ptr
<CReserveScript
> &script
) override
;
962 void ResetRequestCount(const uint256
&hash
) override
965 mapRequestCount
[hash
] = 0;
968 unsigned int GetKeyPoolSize()
970 AssertLockHeld(cs_wallet
); // setKeyPool
971 return setKeyPool
.size();
974 bool SetDefaultKey(const CPubKey
&vchPubKey
);
976 //! signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
977 bool SetMinVersion(enum WalletFeature
, CWalletDB
* pwalletdbIn
= NULL
, bool fExplicit
= false);
979 //! change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
980 bool SetMaxVersion(int nVersion
);
982 //! get the current wallet format (the oldest client version guaranteed to understand this wallet)
983 int GetVersion() { LOCK(cs_wallet
); return nWalletVersion
; }
985 //! Get wallet transactions that conflict with given transaction (spend same outputs)
986 std::set
<uint256
> GetConflicts(const uint256
& txid
) const;
988 //! Check if a given transaction has any of its outputs spent by another transaction in the wallet
989 bool HasWalletSpend(const uint256
& txid
) const;
991 //! Flush wallet (bitdb flush)
992 void Flush(bool shutdown
=false);
994 //! Verify the wallet database and perform salvage if required
995 static bool Verify();
998 * Address book entry changed.
999 * @note called with lock cs_wallet held.
1001 boost::signals2::signal
<void (CWallet
*wallet
, const CTxDestination
1002 &address
, const std::string
&label
, bool isMine
,
1003 const std::string
&purpose
,
1004 ChangeType status
)> NotifyAddressBookChanged
;
1007 * Wallet transaction added, removed or updated.
1008 * @note called with lock cs_wallet held.
1010 boost::signals2::signal
<void (CWallet
*wallet
, const uint256
&hashTx
,
1011 ChangeType status
)> NotifyTransactionChanged
;
1013 /** Show progress e.g. for rescan */
1014 boost::signals2::signal
<void (const std::string
&title
, int nProgress
)> ShowProgress
;
1016 /** Watch-only address added */
1017 boost::signals2::signal
<void (bool fHaveWatchOnly
)> NotifyWatchonlyChanged
;
1019 /** Inquire whether this wallet broadcasts transactions. */
1020 bool GetBroadcastTransactions() const { return fBroadcastTransactions
; }
1021 /** Set whether this wallet broadcasts transactions. */
1022 void SetBroadcastTransactions(bool broadcast
) { fBroadcastTransactions
= broadcast
; }
1024 /* Mark a transaction (and it in-wallet descendants) as abandoned so its inputs may be respent. */
1025 bool AbandonTransaction(const uint256
& hashTx
);
1027 /** Mark a transaction as replaced by another transaction (e.g., BIP 125). */
1028 bool MarkReplaced(const uint256
& originalHash
, const uint256
& newHash
);
1030 /* Returns the wallets help message */
1031 static std::string
GetWalletHelpString(bool showDebug
);
1033 /* Initializes the wallet, returns a new CWallet instance or a null pointer in case of an error */
1034 static CWallet
* CreateWalletFromFile(const std::string walletFile
);
1035 static bool InitLoadWallet();
1038 * Wallet post-init setup
1039 * Gives the wallet a chance to register repetitive tasks and complete post-init tasks
1041 void postInitProcess(CScheduler
& scheduler
);
1043 /* Wallets parameter interaction */
1044 static bool ParameterInteraction();
1046 bool BackupWallet(const std::string
& strDest
);
1048 /* Set the HD chain model (chain child index counters) */
1049 bool SetHDChain(const CHDChain
& chain
, bool memonly
);
1050 const CHDChain
& GetHDChain() const { return hdChain
; }
1052 /* Returns true if HD is enabled */
1053 bool IsHDEnabled() const;
1055 /* Generates a new HD master key (will not be activated) */
1056 CPubKey
GenerateNewHDMasterKey();
1058 /* Set the current HD master key (will reset the chain child index counters)
1059 If possibleOldChain is provided, the parameters from the old chain (version)
1060 will be preserved. */
1061 bool SetHDMasterKey(const CPubKey
& key
, CHDChain
*possibleOldChain
= nullptr);
1064 /** A key allocated from the key pool. */
1065 class CReserveKey
: public CReserveScript
1072 CReserveKey(CWallet
* pwalletIn
)
1075 pwallet
= pwalletIn
;
1078 CReserveKey() = default;
1079 CReserveKey(const CReserveKey
&) = delete;
1080 CReserveKey
& operator=(const CReserveKey
&) = delete;
1088 bool GetReservedKey(CPubKey
&pubkey
, bool internal
= false);
1090 void KeepScript() { KeepKey(); }
1095 * Account information.
1096 * Stored in wallet with key "acc"+string account name.
1110 vchPubKey
= CPubKey();
1113 ADD_SERIALIZE_METHODS
;
1115 template <typename Stream
, typename Operation
>
1116 inline void SerializationOp(Stream
& s
, Operation ser_action
) {
1117 int nVersion
= s
.GetVersion();
1118 if (!(s
.GetType() & SER_GETHASH
))
1119 READWRITE(nVersion
);
1120 READWRITE(vchPubKey
);
1124 // Helper for producing a bunch of max-sized low-S signatures (eg 72 bytes)
1125 // ContainerType is meant to hold pair<CWalletTx *, int>, and be iterable
1126 // so that each entry corresponds to each vIn, in order.
1127 template <typename ContainerType
>
1128 bool CWallet::DummySignTx(CMutableTransaction
&txNew
, const ContainerType
&coins
)
1130 // Fill in dummy signatures for fee calculation.
1132 for (const auto& coin
: coins
)
1134 const CScript
& scriptPubKey
= coin
.first
->tx
->vout
[coin
.second
].scriptPubKey
;
1135 SignatureData sigdata
;
1137 if (!ProduceSignature(DummySignatureCreator(this), scriptPubKey
, sigdata
))
1141 UpdateTransaction(txNew
, nIn
, sigdata
);
1148 #endif // BITCOIN_WALLET_WALLET_H