diff options
author | Russell Yanofsky <russ@yanofsky.org> | 2018-04-07 03:42:02 -0400 |
---|---|---|
committer | Russell Yanofsky <russ@yanofsky.org> | 2018-04-07 03:42:02 -0400 |
commit | 17780d6f35a3951f649c3b7766b9283d9c18e39f (patch) | |
tree | c858c2d92b028d96118983415f40da5b3a0c48e6 /src/interfaces | |
parent | 5f0c6a7b0e47e03f848dc992d37fe209dd9c6975 (diff) |
scripted-diff: Avoid `interface` keyword to fix windows gitian build
Rename `interface` to `interfaces`
Build failure reported by Chun Kuan Lee <ken2812221@gmail.com>
https://github.com/bitcoin/bitcoin/pull/10244#issuecomment-379434756
-BEGIN VERIFY SCRIPT-
git mv src/interface src/interfaces
ren() { git grep -l "$1" | xargs sed -i "s,$1,$2,g"; }
ren interface/ interfaces/
ren interface:: interfaces::
ren BITCOIN_INTERFACE_ BITCOIN_INTERFACES_
ren "namespace interface" "namespace interfaces"
-END VERIFY SCRIPT-
Diffstat (limited to 'src/interfaces')
-rw-r--r-- | src/interfaces/README.md | 17 | ||||
-rw-r--r-- | src/interfaces/handler.cpp | 33 | ||||
-rw-r--r-- | src/interfaces/handler.h | 35 | ||||
-rw-r--r-- | src/interfaces/node.cpp | 308 | ||||
-rw-r--r-- | src/interfaces/node.h | 259 | ||||
-rw-r--r-- | src/interfaces/wallet.cpp | 441 | ||||
-rw-r--r-- | src/interfaces/wallet.h | 352 |
7 files changed, 1445 insertions, 0 deletions
diff --git a/src/interfaces/README.md b/src/interfaces/README.md new file mode 100644 index 0000000000..e93b91d23c --- /dev/null +++ b/src/interfaces/README.md @@ -0,0 +1,17 @@ +# Internal c++ interfaces + +The following interfaces are defined here: + +* [`Chain`](chain.h) — used by wallet to access blockchain and mempool state. Added in [#10973](https://github.com/bitcoin/bitcoin/pull/10973). + +* [`Chain::Client`](chain.h) — used by node to start & stop `Chain` clients. Added in [#10973](https://github.com/bitcoin/bitcoin/pull/10973). + +* [`Node`](node.h) — used by GUI to start & stop bitcoin node. Added in [#10244](https://github.com/bitcoin/bitcoin/pull/10244). + +* [`Wallet`](wallet.h) — used by GUI to access wallets. Added in [#10244](https://github.com/bitcoin/bitcoin/pull/10244). + +* [`Handler`](handler.h) — returned by `handleEvent` methods on interfaces above and used to manage lifetimes of event handlers. + +* [`Init`](init.h) — used by multiprocess code to access interfaces above on startup. Added in [#10102](https://github.com/bitcoin/bitcoin/pull/10102). + +The interfaces above define boundaries between major components of bitcoin code (node, wallet, and gui), making it possible for them to run in different processes, and be tested, developed, and understood independently. These interfaces are not currently designed to be stable or to be used externally. diff --git a/src/interfaces/handler.cpp b/src/interfaces/handler.cpp new file mode 100644 index 0000000000..1443fe9f18 --- /dev/null +++ b/src/interfaces/handler.cpp @@ -0,0 +1,33 @@ +// Copyright (c) 2018 The Bitcoin Core developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include <interfaces/handler.h> + +#include <util.h> + +#include <boost/signals2/connection.hpp> +#include <memory> +#include <utility> + +namespace interfaces { +namespace { + +class HandlerImpl : public Handler +{ +public: + HandlerImpl(boost::signals2::connection connection) : m_connection(std::move(connection)) {} + + void disconnect() override { m_connection.disconnect(); } + + boost::signals2::scoped_connection m_connection; +}; + +} // namespace + +std::unique_ptr<Handler> MakeHandler(boost::signals2::connection connection) +{ + return MakeUnique<HandlerImpl>(std::move(connection)); +} + +} // namespace interfaces diff --git a/src/interfaces/handler.h b/src/interfaces/handler.h new file mode 100644 index 0000000000..c4c674cac5 --- /dev/null +++ b/src/interfaces/handler.h @@ -0,0 +1,35 @@ +// Copyright (c) 2018 The Bitcoin Core developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#ifndef BITCOIN_INTERFACES_HANDLER_H +#define BITCOIN_INTERFACES_HANDLER_H + +#include <memory> + +namespace boost { +namespace signals2 { +class connection; +} // namespace signals2 +} // namespace boost + +namespace interfaces { + +//! Generic interface for managing an event handler or callback function +//! registered with another interface. Has a single disconnect method to cancel +//! the registration and prevent any future notifications. +class Handler +{ +public: + virtual ~Handler() {} + + //! Disconnect the handler. + virtual void disconnect() = 0; +}; + +//! Return handler wrapping a boost signal connection. +std::unique_ptr<Handler> MakeHandler(boost::signals2::connection connection); + +} // namespace interfaces + +#endif // BITCOIN_INTERFACES_HANDLER_H diff --git a/src/interfaces/node.cpp b/src/interfaces/node.cpp new file mode 100644 index 0000000000..919748f942 --- /dev/null +++ b/src/interfaces/node.cpp @@ -0,0 +1,308 @@ +// Copyright (c) 2018 The Bitcoin Core developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include <interfaces/node.h> + +#include <addrdb.h> +#include <amount.h> +#include <chain.h> +#include <chainparams.h> +#include <init.h> +#include <interfaces/handler.h> +#include <interfaces/wallet.h> +#include <net.h> +#include <net_processing.h> +#include <netaddress.h> +#include <netbase.h> +#include <policy/feerate.h> +#include <policy/fees.h> +#include <policy/policy.h> +#include <primitives/block.h> +#include <rpc/server.h> +#include <scheduler.h> +#include <sync.h> +#include <txmempool.h> +#include <ui_interface.h> +#include <util.h> +#include <validation.h> +#include <warnings.h> + +#if defined(HAVE_CONFIG_H) +#include <config/bitcoin-config.h> +#endif +#ifdef ENABLE_WALLET +#include <wallet/fees.h> +#include <wallet/wallet.h> +#define CHECK_WALLET(x) x +#else +#define CHECK_WALLET(x) throw std::logic_error("Wallet function called in non-wallet build.") +#endif + +#include <atomic> +#include <boost/thread/thread.hpp> +#include <univalue.h> + +namespace interfaces { +namespace { + +class NodeImpl : public Node +{ + void parseParameters(int argc, const char* const argv[]) override + { + gArgs.ParseParameters(argc, argv); + } + void readConfigFile(const std::string& conf_path) override { gArgs.ReadConfigFile(conf_path); } + bool softSetArg(const std::string& arg, const std::string& value) override { return gArgs.SoftSetArg(arg, value); } + bool softSetBoolArg(const std::string& arg, bool value) override { return gArgs.SoftSetBoolArg(arg, value); } + void selectParams(const std::string& network) override { SelectParams(network); } + std::string getNetwork() override { return Params().NetworkIDString(); } + void initLogging() override { InitLogging(); } + void initParameterInteraction() override { InitParameterInteraction(); } + std::string getWarnings(const std::string& type) override { return GetWarnings(type); } + uint32_t getLogCategories() override { return ::logCategories; } + bool baseInitialize() override + { + return AppInitBasicSetup() && AppInitParameterInteraction() && AppInitSanityChecks() && + AppInitLockDataDirectory(); + } + bool appInitMain() override { return AppInitMain(); } + void appShutdown() override + { + Interrupt(); + Shutdown(); + } + void startShutdown() override { StartShutdown(); } + bool shutdownRequested() override { return ShutdownRequested(); } + void mapPort(bool use_upnp) override + { + if (use_upnp) { + StartMapPort(); + } else { + InterruptMapPort(); + StopMapPort(); + } + } + std::string helpMessage(HelpMessageMode mode) override { return HelpMessage(mode); } + bool getProxy(Network net, proxyType& proxy_info) override { return GetProxy(net, proxy_info); } + size_t getNodeCount(CConnman::NumConnections flags) override + { + return g_connman ? g_connman->GetNodeCount(flags) : 0; + } + bool getNodesStats(NodesStats& stats) override + { + stats.clear(); + + if (g_connman) { + std::vector<CNodeStats> stats_temp; + g_connman->GetNodeStats(stats_temp); + + stats.reserve(stats_temp.size()); + for (auto& node_stats_temp : stats_temp) { + stats.emplace_back(std::move(node_stats_temp), false, CNodeStateStats()); + } + + // Try to retrieve the CNodeStateStats for each node. + TRY_LOCK(::cs_main, lockMain); + if (lockMain) { + for (auto& node_stats : stats) { + std::get<1>(node_stats) = + GetNodeStateStats(std::get<0>(node_stats).nodeid, std::get<2>(node_stats)); + } + } + return true; + } + return false; + } + bool getBanned(banmap_t& banmap) override + { + if (g_connman) { + g_connman->GetBanned(banmap); + return true; + } + return false; + } + bool ban(const CNetAddr& net_addr, BanReason reason, int64_t ban_time_offset) override + { + if (g_connman) { + g_connman->Ban(net_addr, reason, ban_time_offset); + return true; + } + return false; + } + bool unban(const CSubNet& ip) override + { + if (g_connman) { + g_connman->Unban(ip); + return true; + } + return false; + } + bool disconnect(NodeId id) override + { + if (g_connman) { + return g_connman->DisconnectNode(id); + } + return false; + } + int64_t getTotalBytesRecv() override { return g_connman ? g_connman->GetTotalBytesRecv() : 0; } + int64_t getTotalBytesSent() override { return g_connman ? g_connman->GetTotalBytesSent() : 0; } + size_t getMempoolSize() override { return ::mempool.size(); } + size_t getMempoolDynamicUsage() override { return ::mempool.DynamicMemoryUsage(); } + bool getHeaderTip(int& height, int64_t& block_time) override + { + LOCK(::cs_main); + if (::pindexBestHeader) { + height = ::pindexBestHeader->nHeight; + block_time = ::pindexBestHeader->GetBlockTime(); + return true; + } + return false; + } + int getNumBlocks() override + { + LOCK(::cs_main); + return ::chainActive.Height(); + } + int64_t getLastBlockTime() override + { + LOCK(::cs_main); + if (::chainActive.Tip()) { + return ::chainActive.Tip()->GetBlockTime(); + } + return Params().GenesisBlock().GetBlockTime(); // Genesis block's time of current network + } + double getVerificationProgress() override + { + const CBlockIndex* tip; + { + LOCK(::cs_main); + tip = ::chainActive.Tip(); + } + return GuessVerificationProgress(Params().TxData(), tip); + } + bool isInitialBlockDownload() override { return IsInitialBlockDownload(); } + bool getReindex() override { return ::fReindex; } + bool getImporting() override { return ::fImporting; } + void setNetworkActive(bool active) override + { + if (g_connman) { + g_connman->SetNetworkActive(active); + } + } + bool getNetworkActive() override { return g_connman && g_connman->GetNetworkActive(); } + unsigned int getTxConfirmTarget() override { CHECK_WALLET(return ::nTxConfirmTarget); } + CAmount getRequiredFee(unsigned int tx_bytes) override { CHECK_WALLET(return GetRequiredFee(tx_bytes)); } + CAmount getMinimumFee(unsigned int tx_bytes, + const CCoinControl& coin_control, + int* returned_target, + FeeReason* reason) override + { + FeeCalculation fee_calc; + CAmount result; + CHECK_WALLET(result = GetMinimumFee(tx_bytes, coin_control, ::mempool, ::feeEstimator, &fee_calc)); + if (returned_target) *returned_target = fee_calc.returnedTarget; + if (reason) *reason = fee_calc.reason; + return result; + } + CAmount getMaxTxFee() override { return ::maxTxFee; } + CFeeRate estimateSmartFee(int num_blocks, bool conservative, int* returned_target = nullptr) override + { + FeeCalculation fee_calc; + CFeeRate result = ::feeEstimator.estimateSmartFee(num_blocks, &fee_calc, conservative); + if (returned_target) { + *returned_target = fee_calc.returnedTarget; + } + return result; + } + CFeeRate getDustRelayFee() override { return ::dustRelayFee; } + CFeeRate getFallbackFee() override { CHECK_WALLET(return CWallet::fallbackFee); } + CFeeRate getPayTxFee() override { CHECK_WALLET(return ::payTxFee); } + void setPayTxFee(CFeeRate rate) override { CHECK_WALLET(::payTxFee = rate); } + UniValue executeRpc(const std::string& command, const UniValue& params, const std::string& uri) override + { + JSONRPCRequest req; + req.params = params; + req.strMethod = command; + req.URI = uri; + return ::tableRPC.execute(req); + } + std::vector<std::string> listRpcCommands() override { return ::tableRPC.listCommands(); } + void rpcSetTimerInterfaceIfUnset(RPCTimerInterface* iface) override { RPCSetTimerInterfaceIfUnset(iface); } + void rpcUnsetTimerInterface(RPCTimerInterface* iface) override { RPCUnsetTimerInterface(iface); } + bool getUnspentOutput(const COutPoint& output, Coin& coin) override + { + LOCK(::cs_main); + return ::pcoinsTip->GetCoin(output, coin); + } + std::vector<std::unique_ptr<Wallet>> getWallets() override + { +#ifdef ENABLE_WALLET + std::vector<std::unique_ptr<Wallet>> wallets; + for (CWalletRef wallet : ::vpwallets) { + wallets.emplace_back(MakeWallet(*wallet)); + } + return wallets; +#else + throw std::logic_error("Node::getWallets() called in non-wallet build."); +#endif + } + std::unique_ptr<Handler> handleInitMessage(InitMessageFn fn) override + { + return MakeHandler(::uiInterface.InitMessage.connect(fn)); + } + std::unique_ptr<Handler> handleMessageBox(MessageBoxFn fn) override + { + return MakeHandler(::uiInterface.ThreadSafeMessageBox.connect(fn)); + } + std::unique_ptr<Handler> handleQuestion(QuestionFn fn) override + { + return MakeHandler(::uiInterface.ThreadSafeQuestion.connect(fn)); + } + std::unique_ptr<Handler> handleShowProgress(ShowProgressFn fn) override + { + return MakeHandler(::uiInterface.ShowProgress.connect(fn)); + } + std::unique_ptr<Handler> handleLoadWallet(LoadWalletFn fn) override + { + CHECK_WALLET( + return MakeHandler(::uiInterface.LoadWallet.connect([fn](CWallet* wallet) { fn(MakeWallet(*wallet)); }))); + } + std::unique_ptr<Handler> handleNotifyNumConnectionsChanged(NotifyNumConnectionsChangedFn fn) override + { + return MakeHandler(::uiInterface.NotifyNumConnectionsChanged.connect(fn)); + } + std::unique_ptr<Handler> handleNotifyNetworkActiveChanged(NotifyNetworkActiveChangedFn fn) override + { + return MakeHandler(::uiInterface.NotifyNetworkActiveChanged.connect(fn)); + } + std::unique_ptr<Handler> handleNotifyAlertChanged(NotifyAlertChangedFn fn) override + { + return MakeHandler(::uiInterface.NotifyAlertChanged.connect(fn)); + } + std::unique_ptr<Handler> handleBannedListChanged(BannedListChangedFn fn) override + { + return MakeHandler(::uiInterface.BannedListChanged.connect(fn)); + } + std::unique_ptr<Handler> handleNotifyBlockTip(NotifyBlockTipFn fn) override + { + return MakeHandler(::uiInterface.NotifyBlockTip.connect([fn](bool initial_download, const CBlockIndex* block) { + fn(initial_download, block->nHeight, block->GetBlockTime(), + GuessVerificationProgress(Params().TxData(), block)); + })); + } + std::unique_ptr<Handler> handleNotifyHeaderTip(NotifyHeaderTipFn fn) override + { + return MakeHandler( + ::uiInterface.NotifyHeaderTip.connect([fn](bool initial_download, const CBlockIndex* block) { + fn(initial_download, block->nHeight, block->GetBlockTime(), + GuessVerificationProgress(Params().TxData(), block)); + })); + } +}; + +} // namespace + +std::unique_ptr<Node> MakeNode() { return MakeUnique<NodeImpl>(); } + +} // namespace interfaces diff --git a/src/interfaces/node.h b/src/interfaces/node.h new file mode 100644 index 0000000000..f375af2f19 --- /dev/null +++ b/src/interfaces/node.h @@ -0,0 +1,259 @@ +// Copyright (c) 2018 The Bitcoin Core developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#ifndef BITCOIN_INTERFACES_NODE_H +#define BITCOIN_INTERFACES_NODE_H + +#include <addrdb.h> // For banmap_t +#include <amount.h> // For CAmount +#include <init.h> // For HelpMessageMode +#include <net.h> // For CConnman::NumConnections +#include <netaddress.h> // For Network + +#include <functional> +#include <memory> +#include <stddef.h> +#include <stdint.h> +#include <string> +#include <tuple> +#include <vector> + +class CCoinControl; +class CFeeRate; +class CNodeStats; +class Coin; +class RPCTimerInterface; +class UniValue; +class proxyType; +enum class FeeReason; +struct CNodeStateStats; + +namespace interfaces { + +class Handler; +class Wallet; + +//! Top-level interface for a bitcoin node (bitcoind process). +class Node +{ +public: + virtual ~Node() {} + + //! Set command line arguments. + virtual void parseParameters(int argc, const char* const argv[]) = 0; + + //! Set a command line argument if it doesn't already have a value + virtual bool softSetArg(const std::string& arg, const std::string& value) = 0; + + //! Set a command line boolean argument if it doesn't already have a value + virtual bool softSetBoolArg(const std::string& arg, bool value) = 0; + + //! Load settings from configuration file. + virtual void readConfigFile(const std::string& conf_path) = 0; + + //! Choose network parameters. + virtual void selectParams(const std::string& network) = 0; + + //! Get network name. + virtual std::string getNetwork() = 0; + + //! Init logging. + virtual void initLogging() = 0; + + //! Init parameter interaction. + virtual void initParameterInteraction() = 0; + + //! Get warnings. + virtual std::string getWarnings(const std::string& type) = 0; + + // Get log flags. + virtual uint32_t getLogCategories() = 0; + + //! Initialize app dependencies. + virtual bool baseInitialize() = 0; + + //! Start node. + virtual bool appInitMain() = 0; + + //! Stop node. + virtual void appShutdown() = 0; + + //! Start shutdown. + virtual void startShutdown() = 0; + + //! Return whether shutdown was requested. + virtual bool shutdownRequested() = 0; + + //! Get help message string. + virtual std::string helpMessage(HelpMessageMode mode) = 0; + + //! Map port. + virtual void mapPort(bool use_upnp) = 0; + + //! Get proxy. + virtual bool getProxy(Network net, proxyType& proxy_info) = 0; + + //! Get number of connections. + virtual size_t getNodeCount(CConnman::NumConnections flags) = 0; + + //! Get stats for connected nodes. + using NodesStats = std::vector<std::tuple<CNodeStats, bool, CNodeStateStats>>; + virtual bool getNodesStats(NodesStats& stats) = 0; + + //! Get ban map entries. + virtual bool getBanned(banmap_t& banmap) = 0; + + //! Ban node. + virtual bool ban(const CNetAddr& net_addr, BanReason reason, int64_t ban_time_offset) = 0; + + //! Unban node. + virtual bool unban(const CSubNet& ip) = 0; + + //! Disconnect node. + virtual bool disconnect(NodeId id) = 0; + + //! Get total bytes recv. + virtual int64_t getTotalBytesRecv() = 0; + + //! Get total bytes sent. + virtual int64_t getTotalBytesSent() = 0; + + //! Get mempool size. + virtual size_t getMempoolSize() = 0; + + //! Get mempool dynamic usage. + virtual size_t getMempoolDynamicUsage() = 0; + + //! Get header tip height and time. + virtual bool getHeaderTip(int& height, int64_t& block_time) = 0; + + //! Get num blocks. + virtual int getNumBlocks() = 0; + + //! Get last block time. + virtual int64_t getLastBlockTime() = 0; + + //! Get verification progress. + virtual double getVerificationProgress() = 0; + + //! Is initial block download. + virtual bool isInitialBlockDownload() = 0; + + //! Get reindex. + virtual bool getReindex() = 0; + + //! Get importing. + virtual bool getImporting() = 0; + + //! Set network active. + virtual void setNetworkActive(bool active) = 0; + + //! Get network active. + virtual bool getNetworkActive() = 0; + + //! Get tx confirm target. + virtual unsigned int getTxConfirmTarget() = 0; + + //! Get required fee. + virtual CAmount getRequiredFee(unsigned int tx_bytes) = 0; + + //! Get minimum fee. + virtual CAmount getMinimumFee(unsigned int tx_bytes, + const CCoinControl& coin_control, + int* returned_target, + FeeReason* reason) = 0; + + //! Get max tx fee. + virtual CAmount getMaxTxFee() = 0; + + //! Estimate smart fee. + virtual CFeeRate estimateSmartFee(int num_blocks, bool conservative, int* returned_target = nullptr) = 0; + + //! Get dust relay fee. + virtual CFeeRate getDustRelayFee() = 0; + + //! Get fallback fee. + virtual CFeeRate getFallbackFee() = 0; + + //! Get pay tx fee. + virtual CFeeRate getPayTxFee() = 0; + + //! Set pay tx fee. + virtual void setPayTxFee(CFeeRate rate) = 0; + + //! Execute rpc command. + virtual UniValue executeRpc(const std::string& command, const UniValue& params, const std::string& uri) = 0; + + //! List rpc commands. + virtual std::vector<std::string> listRpcCommands() = 0; + + //! Set RPC timer interface if unset. + virtual void rpcSetTimerInterfaceIfUnset(RPCTimerInterface* iface) = 0; + + //! Unset RPC timer interface. + virtual void rpcUnsetTimerInterface(RPCTimerInterface* iface) = 0; + + //! Get unspent outputs associated with a transaction. + virtual bool getUnspentOutput(const COutPoint& output, Coin& coin) = 0; + + //! Return interfaces for accessing wallets (if any). + virtual std::vector<std::unique_ptr<Wallet>> getWallets() = 0; + + //! Register handler for init messages. + using InitMessageFn = std::function<void(const std::string& message)>; + virtual std::unique_ptr<Handler> handleInitMessage(InitMessageFn fn) = 0; + + //! Register handler for message box messages. + using MessageBoxFn = + std::function<bool(const std::string& message, const std::string& caption, unsigned int style)>; + virtual std::unique_ptr<Handler> handleMessageBox(MessageBoxFn fn) = 0; + + //! Register handler for question messages. + using QuestionFn = std::function<bool(const std::string& message, + const std::string& non_interactive_message, + const std::string& caption, + unsigned int style)>; + virtual std::unique_ptr<Handler> handleQuestion(QuestionFn fn) = 0; + + //! Register handler for progress messages. + using ShowProgressFn = std::function<void(const std::string& title, int progress, bool resume_possible)>; + virtual std::unique_ptr<Handler> handleShowProgress(ShowProgressFn fn) = 0; + + //! Register handler for load wallet messages. + using LoadWalletFn = std::function<void(std::unique_ptr<Wallet> wallet)>; + virtual std::unique_ptr<Handler> handleLoadWallet(LoadWalletFn fn) = 0; + + //! Register handler for number of connections changed messages. + using NotifyNumConnectionsChangedFn = std::function<void(int new_num_connections)>; + virtual std::unique_ptr<Handler> handleNotifyNumConnectionsChanged(NotifyNumConnectionsChangedFn fn) = 0; + + //! Register handler for network active messages. + using NotifyNetworkActiveChangedFn = std::function<void(bool network_active)>; + virtual std::unique_ptr<Handler> handleNotifyNetworkActiveChanged(NotifyNetworkActiveChangedFn fn) = 0; + + //! Register handler for notify alert messages. + using NotifyAlertChangedFn = std::function<void()>; + virtual std::unique_ptr<Handler> handleNotifyAlertChanged(NotifyAlertChangedFn fn) = 0; + + //! Register handler for ban list messages. + using BannedListChangedFn = std::function<void()>; + virtual std::unique_ptr<Handler> handleBannedListChanged(BannedListChangedFn fn) = 0; + + //! Register handler for block tip messages. + using NotifyBlockTipFn = + std::function<void(bool initial_download, int height, int64_t block_time, double verification_progress)>; + virtual std::unique_ptr<Handler> handleNotifyBlockTip(NotifyBlockTipFn fn) = 0; + + //! Register handler for header tip messages. + using NotifyHeaderTipFn = + std::function<void(bool initial_download, int height, int64_t block_time, double verification_progress)>; + virtual std::unique_ptr<Handler> handleNotifyHeaderTip(NotifyHeaderTipFn fn) = 0; +}; + +//! Return implementation of Node interface. +std::unique_ptr<Node> MakeNode(); + +} // namespace interfaces + +#endif // BITCOIN_INTERFACES_NODE_H diff --git a/src/interfaces/wallet.cpp b/src/interfaces/wallet.cpp new file mode 100644 index 0000000000..0244fe70f5 --- /dev/null +++ b/src/interfaces/wallet.cpp @@ -0,0 +1,441 @@ +// Copyright (c) 2018 The Bitcoin Core developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include <interfaces/wallet.h> + +#include <amount.h> +#include <chain.h> +#include <consensus/validation.h> +#include <interfaces/handler.h> +#include <net.h> +#include <policy/policy.h> +#include <primitives/transaction.h> +#include <script/ismine.h> +#include <script/standard.h> +#include <support/allocators/secure.h> +#include <sync.h> +#include <timedata.h> +#include <ui_interface.h> +#include <uint256.h> +#include <validation.h> +#include <wallet/feebumper.h> +#include <wallet/wallet.h> + +#include <memory> + +namespace interfaces { +namespace { + +class PendingWalletTxImpl : public PendingWalletTx +{ +public: + PendingWalletTxImpl(CWallet& wallet) : m_wallet(wallet), m_key(&wallet) {} + + const CTransaction& get() override { return *m_tx; } + + int64_t getVirtualSize() override { return GetVirtualTransactionSize(*m_tx); } + + bool commit(WalletValueMap value_map, + WalletOrderForm order_form, + std::string from_account, + std::string& reject_reason) override + { + LOCK2(cs_main, m_wallet.cs_wallet); + CValidationState state; + if (!m_wallet.CommitTransaction(m_tx, std::move(value_map), std::move(order_form), std::move(from_account), m_key, g_connman.get(), state)) { + reject_reason = state.GetRejectReason(); + return false; + } + return true; + } + + CTransactionRef m_tx; + CWallet& m_wallet; + CReserveKey m_key; +}; + +//! Construct wallet tx struct. +WalletTx MakeWalletTx(CWallet& wallet, const CWalletTx& wtx) +{ + WalletTx result; + result.tx = wtx.tx; + result.txin_is_mine.reserve(wtx.tx->vin.size()); + for (const auto& txin : wtx.tx->vin) { + result.txin_is_mine.emplace_back(wallet.IsMine(txin)); + } + result.txout_is_mine.reserve(wtx.tx->vout.size()); + result.txout_address.reserve(wtx.tx->vout.size()); + result.txout_address_is_mine.reserve(wtx.tx->vout.size()); + for (const auto& txout : wtx.tx->vout) { + result.txout_is_mine.emplace_back(wallet.IsMine(txout)); + result.txout_address.emplace_back(); + result.txout_address_is_mine.emplace_back(ExtractDestination(txout.scriptPubKey, result.txout_address.back()) ? + IsMine(wallet, result.txout_address.back()) : + ISMINE_NO); + } + result.credit = wtx.GetCredit(ISMINE_ALL); + result.debit = wtx.GetDebit(ISMINE_ALL); + result.change = wtx.GetChange(); + result.time = wtx.GetTxTime(); + result.value_map = wtx.mapValue; + result.is_coinbase = wtx.IsCoinBase(); + return result; +} + +//! Construct wallet tx status struct. +WalletTxStatus MakeWalletTxStatus(const CWalletTx& wtx) +{ + WalletTxStatus result; + auto mi = ::mapBlockIndex.find(wtx.hashBlock); + CBlockIndex* block = mi != ::mapBlockIndex.end() ? mi->second : nullptr; + result.block_height = (block ? block->nHeight : std::numeric_limits<int>::max()), + result.blocks_to_maturity = wtx.GetBlocksToMaturity(); + result.depth_in_main_chain = wtx.GetDepthInMainChain(); + result.request_count = wtx.GetRequestCount(); + result.time_received = wtx.nTimeReceived; + result.lock_time = wtx.tx->nLockTime; + result.is_final = CheckFinalTx(*wtx.tx); + result.is_trusted = wtx.IsTrusted(); + result.is_abandoned = wtx.isAbandoned(); + result.is_coinbase = wtx.IsCoinBase(); + result.is_in_main_chain = wtx.IsInMainChain(); + return result; +} + +//! Construct wallet TxOut struct. +WalletTxOut MakeWalletTxOut(CWallet& wallet, const CWalletTx& wtx, int n, int depth) +{ + WalletTxOut result; + result.txout = wtx.tx->vout[n]; + result.time = wtx.GetTxTime(); + result.depth_in_main_chain = depth; + result.is_spent = wallet.IsSpent(wtx.GetHash(), n); + return result; +} + +class WalletImpl : public Wallet +{ +public: + WalletImpl(CWallet& wallet) : m_wallet(wallet) {} + + bool encryptWallet(const SecureString& wallet_passphrase) override + { + return m_wallet.EncryptWallet(wallet_passphrase); + } + bool isCrypted() override { return m_wallet.IsCrypted(); } + bool lock() override { return m_wallet.Lock(); } + bool unlock(const SecureString& wallet_passphrase) override { return m_wallet.Unlock(wallet_passphrase); } + bool isLocked() override { return m_wallet.IsLocked(); } + bool changeWalletPassphrase(const SecureString& old_wallet_passphrase, + const SecureString& new_wallet_passphrase) override + { + return m_wallet.ChangeWalletPassphrase(old_wallet_passphrase, new_wallet_passphrase); + } + bool backupWallet(const std::string& filename) override { return m_wallet.BackupWallet(filename); } + std::string getWalletName() override { return m_wallet.GetName(); } + bool getKeyFromPool(bool internal, CPubKey& pub_key) override + { + return m_wallet.GetKeyFromPool(pub_key, internal); + } + bool getPubKey(const CKeyID& address, CPubKey& pub_key) override { return m_wallet.GetPubKey(address, pub_key); } + bool getPrivKey(const CKeyID& address, CKey& key) override { return m_wallet.GetKey(address, key); } + bool isSpendable(const CTxDestination& dest) override { return IsMine(m_wallet, dest) & ISMINE_SPENDABLE; } + bool haveWatchOnly() override { return m_wallet.HaveWatchOnly(); }; + bool setAddressBook(const CTxDestination& dest, const std::string& name, const std::string& purpose) override + { + return m_wallet.SetAddressBook(dest, name, purpose); + } + bool delAddressBook(const CTxDestination& dest) override + { + return m_wallet.DelAddressBook(dest); + } + bool getAddress(const CTxDestination& dest, std::string* name, isminetype* is_mine) override + { + LOCK(m_wallet.cs_wallet); + auto it = m_wallet.mapAddressBook.find(dest); + if (it == m_wallet.mapAddressBook.end()) { + return false; + } + if (name) { + *name = it->second.name; + } + if (is_mine) { + *is_mine = IsMine(m_wallet, dest); + } + return true; + } + std::vector<WalletAddress> getAddresses() override + { + LOCK(m_wallet.cs_wallet); + std::vector<WalletAddress> result; + for (const auto& item : m_wallet.mapAddressBook) { + result.emplace_back(item.first, IsMine(m_wallet, item.first), item.second.name, item.second.purpose); + } + return result; + } + void learnRelatedScripts(const CPubKey& key, OutputType type) override { m_wallet.LearnRelatedScripts(key, type); } + bool addDestData(const CTxDestination& dest, const std::string& key, const std::string& value) override + { + LOCK(m_wallet.cs_wallet); + return m_wallet.AddDestData(dest, key, value); + } + bool eraseDestData(const CTxDestination& dest, const std::string& key) override + { + LOCK(m_wallet.cs_wallet); + return m_wallet.EraseDestData(dest, key); + } + std::vector<std::string> getDestValues(const std::string& prefix) override + { + return m_wallet.GetDestValues(prefix); + } + void lockCoin(const COutPoint& output) override + { + LOCK2(cs_main, m_wallet.cs_wallet); + return m_wallet.LockCoin(output); + } + void unlockCoin(const COutPoint& output) override + { + LOCK2(cs_main, m_wallet.cs_wallet); + return m_wallet.UnlockCoin(output); + } + bool isLockedCoin(const COutPoint& output) override + { + LOCK2(cs_main, m_wallet.cs_wallet); + return m_wallet.IsLockedCoin(output.hash, output.n); + } + void listLockedCoins(std::vector<COutPoint>& outputs) override + { + LOCK2(cs_main, m_wallet.cs_wallet); + return m_wallet.ListLockedCoins(outputs); + } + std::unique_ptr<PendingWalletTx> createTransaction(const std::vector<CRecipient>& recipients, + const CCoinControl& coin_control, + bool sign, + int& change_pos, + CAmount& fee, + std::string& fail_reason) override + { + LOCK2(cs_main, m_wallet.cs_wallet); + auto pending = MakeUnique<PendingWalletTxImpl>(m_wallet); + if (!m_wallet.CreateTransaction(recipients, pending->m_tx, pending->m_key, fee, change_pos, + fail_reason, coin_control, sign)) { + return {}; + } + return std::move(pending); + } + bool transactionCanBeAbandoned(const uint256& txid) override { return m_wallet.TransactionCanBeAbandoned(txid); } + bool abandonTransaction(const uint256& txid) override + { + LOCK2(cs_main, m_wallet.cs_wallet); + return m_wallet.AbandonTransaction(txid); + } + bool transactionCanBeBumped(const uint256& txid) override + { + return feebumper::TransactionCanBeBumped(&m_wallet, txid); + } + bool createBumpTransaction(const uint256& txid, + const CCoinControl& coin_control, + CAmount total_fee, + std::vector<std::string>& errors, + CAmount& old_fee, + CAmount& new_fee, + CMutableTransaction& mtx) override + { + return feebumper::CreateTransaction(&m_wallet, txid, coin_control, total_fee, errors, old_fee, new_fee, mtx) == + feebumper::Result::OK; + } + bool signBumpTransaction(CMutableTransaction& mtx) override { return feebumper::SignTransaction(&m_wallet, mtx); } + bool commitBumpTransaction(const uint256& txid, + CMutableTransaction&& mtx, + std::vector<std::string>& errors, + uint256& bumped_txid) override + { + return feebumper::CommitTransaction(&m_wallet, txid, std::move(mtx), errors, bumped_txid) == + feebumper::Result::OK; + } + CTransactionRef getTx(const uint256& txid) override + { + LOCK2(::cs_main, m_wallet.cs_wallet); + auto mi = m_wallet.mapWallet.find(txid); + if (mi != m_wallet.mapWallet.end()) { + return mi->second.tx; + } + return {}; + } + WalletTx getWalletTx(const uint256& txid) override + { + LOCK2(::cs_main, m_wallet.cs_wallet); + auto mi = m_wallet.mapWallet.find(txid); + if (mi != m_wallet.mapWallet.end()) { + return MakeWalletTx(m_wallet, mi->second); + } + return {}; + } + std::vector<WalletTx> getWalletTxs() override + { + LOCK2(::cs_main, m_wallet.cs_wallet); + std::vector<WalletTx> result; + result.reserve(m_wallet.mapWallet.size()); + for (const auto& entry : m_wallet.mapWallet) { + result.emplace_back(MakeWalletTx(m_wallet, entry.second)); + } + return result; + } + bool tryGetTxStatus(const uint256& txid, + interfaces::WalletTxStatus& tx_status, + int& num_blocks, + int64_t& adjusted_time) override + { + TRY_LOCK(::cs_main, locked_chain); + if (!locked_chain) { + return false; + } + TRY_LOCK(m_wallet.cs_wallet, locked_wallet); + if (!locked_wallet) { + return false; + } + auto mi = m_wallet.mapWallet.find(txid); + if (mi == m_wallet.mapWallet.end()) { + return false; + } + num_blocks = ::chainActive.Height(); + adjusted_time = GetAdjustedTime(); + tx_status = MakeWalletTxStatus(mi->second); + return true; + } + WalletTx getWalletTxDetails(const uint256& txid, + WalletTxStatus& tx_status, + WalletOrderForm& order_form, + bool& in_mempool, + int& num_blocks, + int64_t& adjusted_time) override + { + LOCK2(::cs_main, m_wallet.cs_wallet); + auto mi = m_wallet.mapWallet.find(txid); + if (mi != m_wallet.mapWallet.end()) { + num_blocks = ::chainActive.Height(); + adjusted_time = GetAdjustedTime(); + in_mempool = mi->second.InMempool(); + order_form = mi->second.vOrderForm; + tx_status = MakeWalletTxStatus(mi->second); + return MakeWalletTx(m_wallet, mi->second); + } + return {}; + } + WalletBalances getBalances() override + { + WalletBalances result; + result.balance = m_wallet.GetBalance(); + result.unconfirmed_balance = m_wallet.GetUnconfirmedBalance(); + result.immature_balance = m_wallet.GetImmatureBalance(); + result.have_watch_only = m_wallet.HaveWatchOnly(); + if (result.have_watch_only) { + result.watch_only_balance = m_wallet.GetWatchOnlyBalance(); + result.unconfirmed_watch_only_balance = m_wallet.GetUnconfirmedWatchOnlyBalance(); + result.immature_watch_only_balance = m_wallet.GetImmatureWatchOnlyBalance(); + } + return result; + } + bool tryGetBalances(WalletBalances& balances, int& num_blocks) override + { + TRY_LOCK(cs_main, locked_chain); + if (!locked_chain) return false; + TRY_LOCK(m_wallet.cs_wallet, locked_wallet); + if (!locked_wallet) { + return false; + } + balances = getBalances(); + num_blocks = ::chainActive.Height(); + return true; + } + CAmount getBalance() override { return m_wallet.GetBalance(); } + CAmount getAvailableBalance(const CCoinControl& coin_control) override + { + return m_wallet.GetAvailableBalance(&coin_control); + } + isminetype txinIsMine(const CTxIn& txin) override + { + LOCK2(::cs_main, m_wallet.cs_wallet); + return m_wallet.IsMine(txin); + } + isminetype txoutIsMine(const CTxOut& txout) override + { + LOCK2(::cs_main, m_wallet.cs_wallet); + return m_wallet.IsMine(txout); + } + CAmount getDebit(const CTxIn& txin, isminefilter filter) override + { + LOCK2(::cs_main, m_wallet.cs_wallet); + return m_wallet.GetDebit(txin, filter); + } + CAmount getCredit(const CTxOut& txout, isminefilter filter) override + { + LOCK2(::cs_main, m_wallet.cs_wallet); + return m_wallet.GetCredit(txout, filter); + } + CoinsList listCoins() override + { + LOCK2(::cs_main, m_wallet.cs_wallet); + CoinsList result; + for (const auto& entry : m_wallet.ListCoins()) { + auto& group = result[entry.first]; + for (const auto& coin : entry.second) { + group.emplace_back( + COutPoint(coin.tx->GetHash(), coin.i), MakeWalletTxOut(m_wallet, *coin.tx, coin.i, coin.nDepth)); + } + } + return result; + } + std::vector<WalletTxOut> getCoins(const std::vector<COutPoint>& outputs) override + { + LOCK2(::cs_main, m_wallet.cs_wallet); + std::vector<WalletTxOut> result; + result.reserve(outputs.size()); + for (const auto& output : outputs) { + result.emplace_back(); + auto it = m_wallet.mapWallet.find(output.hash); + if (it != m_wallet.mapWallet.end()) { + int depth = it->second.GetDepthInMainChain(); + if (depth >= 0) { + result.back() = MakeWalletTxOut(m_wallet, it->second, output.n, depth); + } + } + } + return result; + } + bool hdEnabled() override { return m_wallet.IsHDEnabled(); } + OutputType getDefaultAddressType() override { return m_wallet.m_default_address_type; } + OutputType getDefaultChangeType() override { return m_wallet.m_default_change_type; } + std::unique_ptr<Handler> handleShowProgress(ShowProgressFn fn) override + { + return MakeHandler(m_wallet.ShowProgress.connect(fn)); + } + std::unique_ptr<Handler> handleStatusChanged(StatusChangedFn fn) override + { + return MakeHandler(m_wallet.NotifyStatusChanged.connect([fn](CCryptoKeyStore*) { fn(); })); + } + std::unique_ptr<Handler> handleAddressBookChanged(AddressBookChangedFn fn) override + { + return MakeHandler(m_wallet.NotifyAddressBookChanged.connect( + [fn](CWallet*, const CTxDestination& address, const std::string& label, bool is_mine, + const std::string& purpose, ChangeType status) { fn(address, label, is_mine, purpose, status); })); + } + std::unique_ptr<Handler> handleTransactionChanged(TransactionChangedFn fn) override + { + return MakeHandler(m_wallet.NotifyTransactionChanged.connect( + [fn, this](CWallet*, const uint256& txid, ChangeType status) { fn(txid, status); })); + } + std::unique_ptr<Handler> handleWatchOnlyChanged(WatchOnlyChangedFn fn) override + { + return MakeHandler(m_wallet.NotifyWatchonlyChanged.connect(fn)); + } + + CWallet& m_wallet; +}; + +} // namespace + +std::unique_ptr<Wallet> MakeWallet(CWallet& wallet) { return MakeUnique<WalletImpl>(wallet); } + +} // namespace interfaces diff --git a/src/interfaces/wallet.h b/src/interfaces/wallet.h new file mode 100644 index 0000000000..3e27242c2c --- /dev/null +++ b/src/interfaces/wallet.h @@ -0,0 +1,352 @@ +// Copyright (c) 2018 The Bitcoin Core developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#ifndef BITCOIN_INTERFACES_WALLET_H +#define BITCOIN_INTERFACES_WALLET_H + +#include <amount.h> // For CAmount +#include <pubkey.h> // For CTxDestination (CKeyID and CScriptID) +#include <script/ismine.h> // For isminefilter, isminetype +#include <script/standard.h> // For CTxDestination +#include <support/allocators/secure.h> // For SecureString +#include <ui_interface.h> // For ChangeType + +#include <functional> +#include <map> +#include <memory> +#include <stdint.h> +#include <string> +#include <tuple> +#include <utility> +#include <vector> + +class CCoinControl; +class CKey; +class CWallet; +enum class OutputType; +struct CRecipient; + +namespace interfaces { + +class Handler; +class PendingWalletTx; +struct WalletAddress; +struct WalletBalances; +struct WalletTx; +struct WalletTxOut; +struct WalletTxStatus; + +using WalletOrderForm = std::vector<std::pair<std::string, std::string>>; +using WalletValueMap = std::map<std::string, std::string>; + +//! Interface for accessing a wallet. +class Wallet +{ +public: + virtual ~Wallet() {} + + //! Encrypt wallet. + virtual bool encryptWallet(const SecureString& wallet_passphrase) = 0; + + //! Return whether wallet is encrypted. + virtual bool isCrypted() = 0; + + //! Lock wallet. + virtual bool lock() = 0; + + //! Unlock wallet. + virtual bool unlock(const SecureString& wallet_passphrase) = 0; + + //! Return whether wallet is locked. + virtual bool isLocked() = 0; + + //! Change wallet passphrase. + virtual bool changeWalletPassphrase(const SecureString& old_wallet_passphrase, + const SecureString& new_wallet_passphrase) = 0; + + //! Back up wallet. + virtual bool backupWallet(const std::string& filename) = 0; + + //! Get wallet name. + virtual std::string getWalletName() = 0; + + // Get key from pool. + virtual bool getKeyFromPool(bool internal, CPubKey& pub_key) = 0; + + //! Get public key. + virtual bool getPubKey(const CKeyID& address, CPubKey& pub_key) = 0; + + //! Get private key. + virtual bool getPrivKey(const CKeyID& address, CKey& key) = 0; + + //! Return whether wallet has private key. + virtual bool isSpendable(const CTxDestination& dest) = 0; + + //! Return whether wallet has watch only keys. + virtual bool haveWatchOnly() = 0; + + //! Add or update address. + virtual bool setAddressBook(const CTxDestination& dest, const std::string& name, const std::string& purpose) = 0; + + // Remove address. + virtual bool delAddressBook(const CTxDestination& dest) = 0; + + //! Look up address in wallet, return whether exists. + virtual bool getAddress(const CTxDestination& dest, + std::string* name = nullptr, + isminetype* is_mine = nullptr) = 0; + + //! Get wallet address list. + virtual std::vector<WalletAddress> getAddresses() = 0; + + //! Add scripts to key store so old so software versions opening the wallet + //! database can detect payments to newer address types. + virtual void learnRelatedScripts(const CPubKey& key, OutputType type) = 0; + + //! Add dest data. + virtual bool addDestData(const CTxDestination& dest, const std::string& key, const std::string& value) = 0; + + //! Erase dest data. + virtual bool eraseDestData(const CTxDestination& dest, const std::string& key) = 0; + + //! Get dest values with prefix. + virtual std::vector<std::string> getDestValues(const std::string& prefix) = 0; + + //! Lock coin. + virtual void lockCoin(const COutPoint& output) = 0; + + //! Unlock coin. + virtual void unlockCoin(const COutPoint& output) = 0; + + //! Return whether coin is locked. + virtual bool isLockedCoin(const COutPoint& output) = 0; + + //! List locked coins. + virtual void listLockedCoins(std::vector<COutPoint>& outputs) = 0; + + //! Create transaction. + virtual std::unique_ptr<PendingWalletTx> createTransaction(const std::vector<CRecipient>& recipients, + const CCoinControl& coin_control, + bool sign, + int& change_pos, + CAmount& fee, + std::string& fail_reason) = 0; + + //! Return whether transaction can be abandoned. + virtual bool transactionCanBeAbandoned(const uint256& txid) = 0; + + //! Abandon transaction. + virtual bool abandonTransaction(const uint256& txid) = 0; + + //! Return whether transaction can be bumped. + virtual bool transactionCanBeBumped(const uint256& txid) = 0; + + //! Create bump transaction. + virtual bool createBumpTransaction(const uint256& txid, + const CCoinControl& coin_control, + CAmount total_fee, + std::vector<std::string>& errors, + CAmount& old_fee, + CAmount& new_fee, + CMutableTransaction& mtx) = 0; + + //! Sign bump transaction. + virtual bool signBumpTransaction(CMutableTransaction& mtx) = 0; + + //! Commit bump transaction. + virtual bool commitBumpTransaction(const uint256& txid, + CMutableTransaction&& mtx, + std::vector<std::string>& errors, + uint256& bumped_txid) = 0; + + //! Get a transaction. + virtual CTransactionRef getTx(const uint256& txid) = 0; + + //! Get transaction information. + virtual WalletTx getWalletTx(const uint256& txid) = 0; + + //! Get list of all wallet transactions. + virtual std::vector<WalletTx> getWalletTxs() = 0; + + //! Try to get updated status for a particular transaction, if possible without blocking. + virtual bool tryGetTxStatus(const uint256& txid, + WalletTxStatus& tx_status, + int& num_blocks, + int64_t& adjusted_time) = 0; + + //! Get transaction details. + virtual WalletTx getWalletTxDetails(const uint256& txid, + WalletTxStatus& tx_status, + WalletOrderForm& order_form, + bool& in_mempool, + int& num_blocks, + int64_t& adjusted_time) = 0; + + //! Get balances. + virtual WalletBalances getBalances() = 0; + + //! Get balances if possible without blocking. + virtual bool tryGetBalances(WalletBalances& balances, int& num_blocks) = 0; + + //! Get balance. + virtual CAmount getBalance() = 0; + + //! Get available balance. + virtual CAmount getAvailableBalance(const CCoinControl& coin_control) = 0; + + //! Return whether transaction input belongs to wallet. + virtual isminetype txinIsMine(const CTxIn& txin) = 0; + + //! Return whether transaction output belongs to wallet. + virtual isminetype txoutIsMine(const CTxOut& txout) = 0; + + //! Return debit amount if transaction input belongs to wallet. + virtual CAmount getDebit(const CTxIn& txin, isminefilter filter) = 0; + + //! Return credit amount if transaction input belongs to wallet. + virtual CAmount getCredit(const CTxOut& txout, isminefilter filter) = 0; + + //! Return AvailableCoins + LockedCoins grouped by wallet address. + //! (put change in one group with wallet address) + using CoinsList = std::map<CTxDestination, std::vector<std::tuple<COutPoint, WalletTxOut>>>; + virtual CoinsList listCoins() = 0; + + //! Return wallet transaction output information. + virtual std::vector<WalletTxOut> getCoins(const std::vector<COutPoint>& outputs) = 0; + + // Return whether HD enabled. + virtual bool hdEnabled() = 0; + + // Get default address type. + virtual OutputType getDefaultAddressType() = 0; + + // Get default change type. + virtual OutputType getDefaultChangeType() = 0; + + //! Register handler for show progress messages. + using ShowProgressFn = std::function<void(const std::string& title, int progress)>; + virtual std::unique_ptr<Handler> handleShowProgress(ShowProgressFn fn) = 0; + + //! Register handler for status changed messages. + using StatusChangedFn = std::function<void()>; + virtual std::unique_ptr<Handler> handleStatusChanged(StatusChangedFn fn) = 0; + + //! Register handler for address book changed messages. + using AddressBookChangedFn = std::function<void(const CTxDestination& address, + const std::string& label, + bool is_mine, + const std::string& purpose, + ChangeType status)>; + virtual std::unique_ptr<Handler> handleAddressBookChanged(AddressBookChangedFn fn) = 0; + + //! Register handler for transaction changed messages. + using TransactionChangedFn = std::function<void(const uint256& txid, ChangeType status)>; + virtual std::unique_ptr<Handler> handleTransactionChanged(TransactionChangedFn fn) = 0; + + //! Register handler for watchonly changed messages. + using WatchOnlyChangedFn = std::function<void(bool have_watch_only)>; + virtual std::unique_ptr<Handler> handleWatchOnlyChanged(WatchOnlyChangedFn fn) = 0; +}; + +//! Tracking object returned by CreateTransaction and passed to CommitTransaction. +class PendingWalletTx +{ +public: + virtual ~PendingWalletTx() {} + + //! Get transaction data. + virtual const CTransaction& get() = 0; + + //! Get virtual transaction size. + virtual int64_t getVirtualSize() = 0; + + //! Send pending transaction and commit to wallet. + virtual bool commit(WalletValueMap value_map, + WalletOrderForm order_form, + std::string from_account, + std::string& reject_reason) = 0; +}; + +//! Information about one wallet address. +struct WalletAddress +{ + CTxDestination dest; + isminetype is_mine; + std::string name; + std::string purpose; + + WalletAddress(CTxDestination dest, isminetype is_mine, std::string name, std::string purpose) + : dest(std::move(dest)), is_mine(is_mine), name(std::move(name)), purpose(std::move(purpose)) + { + } +}; + +//! Collection of wallet balances. +struct WalletBalances +{ + CAmount balance = 0; + CAmount unconfirmed_balance = 0; + CAmount immature_balance = 0; + bool have_watch_only = false; + CAmount watch_only_balance = 0; + CAmount unconfirmed_watch_only_balance = 0; + CAmount immature_watch_only_balance = 0; + + bool balanceChanged(const WalletBalances& prev) const + { + return balance != prev.balance || unconfirmed_balance != prev.unconfirmed_balance || + immature_balance != prev.immature_balance || watch_only_balance != prev.watch_only_balance || + unconfirmed_watch_only_balance != prev.unconfirmed_watch_only_balance || + immature_watch_only_balance != prev.immature_watch_only_balance; + } +}; + +// Wallet transaction information. +struct WalletTx +{ + CTransactionRef tx; + std::vector<isminetype> txin_is_mine; + std::vector<isminetype> txout_is_mine; + std::vector<CTxDestination> txout_address; + std::vector<isminetype> txout_address_is_mine; + CAmount credit; + CAmount debit; + CAmount change; + int64_t time; + std::map<std::string, std::string> value_map; + bool is_coinbase; +}; + +//! Updated transaction status. +struct WalletTxStatus +{ + int block_height; + int blocks_to_maturity; + int depth_in_main_chain; + int request_count; + unsigned int time_received; + uint32_t lock_time; + bool is_final; + bool is_trusted; + bool is_abandoned; + bool is_coinbase; + bool is_in_main_chain; +}; + +//! Wallet transaction output. +struct WalletTxOut +{ + CTxOut txout; + int64_t time; + int depth_in_main_chain = -1; + bool is_spent = false; +}; + +//! Return implementation of Wallet interface. This function will be undefined +//! in builds where ENABLE_WALLET is false. +std::unique_ptr<Wallet> MakeWallet(CWallet& wallet); + +} // namespace interfaces + +#endif // BITCOIN_INTERFACES_WALLET_H |