Pass NodeContext, ConnMan, BanMan references more places

So g_connman and g_banman globals can be removed next commit.
This commit is contained in:
Russell Yanofsky 2019-09-17 18:28:03 -04:00
parent 4d5448c76b
commit e6f4f895d5
34 changed files with 154 additions and 62 deletions

View file

@ -285,6 +285,7 @@ libbitcoin_server_a_SOURCES = \
net_processing.cpp \ net_processing.cpp \
node/coin.cpp \ node/coin.cpp \
node/coinstats.cpp \ node/coinstats.cpp \
node/context.cpp \
node/psbt.cpp \ node/psbt.cpp \
node/transaction.cpp \ node/transaction.cpp \
noui.cpp \ noui.cpp \

View file

@ -4,6 +4,7 @@
#include <bench/bench.h> #include <bench/bench.h>
#include <interfaces/chain.h> #include <interfaces/chain.h>
#include <node/context.h>
#include <wallet/coinselection.h> #include <wallet/coinselection.h>
#include <wallet/wallet.h> #include <wallet/wallet.h>
@ -28,7 +29,8 @@ static void addCoin(const CAmount& nValue, const CWallet& wallet, std::vector<st
// (https://github.com/bitcoin/bitcoin/issues/7883#issuecomment-224807484) // (https://github.com/bitcoin/bitcoin/issues/7883#issuecomment-224807484)
static void CoinSelection(benchmark::State& state) static void CoinSelection(benchmark::State& state)
{ {
auto chain = interfaces::MakeChain(); NodeContext node;
auto chain = interfaces::MakeChain(node);
const CWallet wallet(chain.get(), WalletLocation(), WalletDatabase::CreateDummy()); const CWallet wallet(chain.get(), WalletLocation(), WalletDatabase::CreateDummy());
std::vector<std::unique_ptr<CWalletTx>> wtxs; std::vector<std::unique_ptr<CWalletTx>> wtxs;
LOCK(wallet.cs_wallet); LOCK(wallet.cs_wallet);
@ -60,7 +62,8 @@ static void CoinSelection(benchmark::State& state)
} }
typedef std::set<CInputCoin> CoinSet; typedef std::set<CInputCoin> CoinSet;
static auto testChain = interfaces::MakeChain(); static NodeContext testNode;
static auto testChain = interfaces::MakeChain(testNode);
static const CWallet testWallet(testChain.get(), WalletLocation(), WalletDatabase::CreateDummy()); static const CWallet testWallet(testChain.get(), WalletLocation(), WalletDatabase::CreateDummy());
std::vector<std::unique_ptr<CWalletTx>> wtxn; std::vector<std::unique_ptr<CWalletTx>> wtxn;

View file

@ -4,6 +4,7 @@
#include <bench/bench.h> #include <bench/bench.h>
#include <interfaces/chain.h> #include <interfaces/chain.h>
#include <node/context.h>
#include <optional.h> #include <optional.h>
#include <test/util.h> #include <test/util.h>
#include <validationinterface.h> #include <validationinterface.h>
@ -13,7 +14,8 @@ static void WalletBalance(benchmark::State& state, const bool set_dirty, const b
{ {
const auto& ADDRESS_WATCHONLY = ADDRESS_BCRT1_UNSPENDABLE; const auto& ADDRESS_WATCHONLY = ADDRESS_BCRT1_UNSPENDABLE;
std::unique_ptr<interfaces::Chain> chain = interfaces::MakeChain(); NodeContext node;
std::unique_ptr<interfaces::Chain> chain = interfaces::MakeChain(node);
CWallet wallet{chain.get(), WalletLocation(), WalletDatabase::CreateMock()}; CWallet wallet{chain.get(), WalletLocation(), WalletDatabase::CreateMock()};
{ {
bool first_run; bool first_run;

View file

@ -12,6 +12,7 @@
#include <compat.h> #include <compat.h>
#include <init.h> #include <init.h>
#include <interfaces/chain.h> #include <interfaces/chain.h>
#include <node/context.h>
#include <noui.h> #include <noui.h>
#include <shutdown.h> #include <shutdown.h>
#include <ui_interface.h> #include <ui_interface.h>
@ -24,13 +25,13 @@
const std::function<std::string(const char*)> G_TRANSLATION_FUN = nullptr; const std::function<std::string(const char*)> G_TRANSLATION_FUN = nullptr;
static void WaitForShutdown() static void WaitForShutdown(NodeContext& node)
{ {
while (!ShutdownRequested()) while (!ShutdownRequested())
{ {
MilliSleep(200); MilliSleep(200);
} }
Interrupt(); Interrupt(node);
} }
////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////
@ -40,7 +41,7 @@ static void WaitForShutdown()
static bool AppInit(int argc, char* argv[]) static bool AppInit(int argc, char* argv[])
{ {
NodeContext node; NodeContext node;
node.chain = interfaces::MakeChain(); node.chain = interfaces::MakeChain(node);
bool fRet = false; bool fRet = false;
@ -152,9 +153,9 @@ static bool AppInit(int argc, char* argv[])
if (!fRet) if (!fRet)
{ {
Interrupt(); Interrupt(node);
} else { } else {
WaitForShutdown(); WaitForShutdown(node);
} }
Shutdown(node); Shutdown(node);

View file

@ -29,6 +29,7 @@
#include <net_permissions.h> #include <net_permissions.h>
#include <net_processing.h> #include <net_processing.h>
#include <netbase.h> #include <netbase.h>
#include <node/context.h>
#include <policy/feerate.h> #include <policy/feerate.h>
#include <policy/fees.h> #include <policy/fees.h>
#include <policy/policy.h> #include <policy/policy.h>
@ -154,7 +155,7 @@ static std::unique_ptr<ECCVerifyHandle> globalVerifyHandle;
static boost::thread_group threadGroup; static boost::thread_group threadGroup;
static CScheduler scheduler; static CScheduler scheduler;
void Interrupt() void Interrupt(NodeContext& node)
{ {
InterruptHTTPServer(); InterruptHTTPServer();
InterruptHTTPRPC(); InterruptHTTPRPC();
@ -1819,8 +1820,9 @@ bool AppInitMain(NodeContext& node)
client->start(scheduler); client->start(scheduler);
} }
scheduler.scheduleEvery([]{ BanMan* banman = g_banman.get();
g_banman->DumpBanlist(); scheduler.scheduleEvery([banman]{
banman->DumpBanlist();
}, DUMP_BANS_INTERVAL * 1000); }, DUMP_BANS_INTERVAL * 1000);
return true; return true;

View file

@ -7,17 +7,16 @@
#define BITCOIN_INIT_H #define BITCOIN_INIT_H
#include <memory> #include <memory>
#include <node/context.h>
#include <string> #include <string>
#include <util/system.h> #include <util/system.h>
namespace boost struct NodeContext;
{ namespace boost {
class thread_group; class thread_group;
} // namespace boost } // namespace boost
/** Interrupt threads */ /** Interrupt threads */
void Interrupt(); void Interrupt(NodeContext& node);
void Shutdown(NodeContext& node); void Shutdown(NodeContext& node);
//!Initialize the logging infrastructure //!Initialize the logging infrastructure
void InitLogging(); void InitLogging();

View file

@ -11,6 +11,7 @@
#include <net.h> #include <net.h>
#include <net_processing.h> #include <net_processing.h>
#include <node/coin.h> #include <node/coin.h>
#include <node/context.h>
#include <node/transaction.h> #include <node/transaction.h>
#include <policy/fees.h> #include <policy/fees.h>
#include <policy/policy.h> #include <policy/policy.h>
@ -238,6 +239,7 @@ public:
class ChainImpl : public Chain class ChainImpl : public Chain
{ {
public: public:
explicit ChainImpl(NodeContext& node) : m_node(node) {}
std::unique_ptr<Chain::Lock> lock(bool try_lock) override std::unique_ptr<Chain::Lock> lock(bool try_lock) override
{ {
auto result = MakeUnique<LockImpl>(::cs_main, "cs_main", __FILE__, __LINE__, try_lock); auto result = MakeUnique<LockImpl>(::cs_main, "cs_main", __FILE__, __LINE__, try_lock);
@ -286,7 +288,7 @@ public:
} }
bool broadcastTransaction(const CTransactionRef& tx, std::string& err_string, const CAmount& max_tx_fee, bool relay) override bool broadcastTransaction(const CTransactionRef& tx, std::string& err_string, const CAmount& max_tx_fee, bool relay) override
{ {
const TransactionError err = BroadcastTransaction(tx, err_string, max_tx_fee, relay, /*wait_callback*/ false); const TransactionError err = BroadcastTransaction(m_node, tx, err_string, max_tx_fee, relay, /*wait_callback*/ false);
// Chain clients only care about failures to accept the tx to the mempool. Disregard non-mempool related failures. // Chain clients only care about failures to accept the tx to the mempool. Disregard non-mempool related failures.
// Note: this will need to be updated if BroadcastTransactions() is updated to return other non-mempool failures // Note: this will need to be updated if BroadcastTransactions() is updated to return other non-mempool failures
// that Chain clients do not need to know about. // that Chain clients do not need to know about.
@ -378,9 +380,10 @@ public:
notifications.TransactionAddedToMempool(entry.GetSharedTx()); notifications.TransactionAddedToMempool(entry.GetSharedTx());
} }
} }
NodeContext& m_node;
}; };
} // namespace } // namespace
std::unique_ptr<Chain> MakeChain() { return MakeUnique<ChainImpl>(); } std::unique_ptr<Chain> MakeChain(NodeContext& node) { return MakeUnique<ChainImpl>(node); }
} // namespace interfaces } // namespace interfaces

View file

@ -24,6 +24,7 @@ class uint256;
enum class RBFTransactionState; enum class RBFTransactionState;
struct CBlockLocator; struct CBlockLocator;
struct FeeCalculation; struct FeeCalculation;
struct NodeContext;
namespace interfaces { namespace interfaces {
@ -291,7 +292,7 @@ public:
}; };
//! Return implementation of Chain interface. //! Return implementation of Chain interface.
std::unique_ptr<Chain> MakeChain(); std::unique_ptr<Chain> MakeChain(NodeContext& node);
//! Return implementation of ChainClient interface for a wallet client. This //! Return implementation of ChainClient interface for a wallet client. This
//! function will be undefined in builds where ENABLE_WALLET is false. //! function will be undefined in builds where ENABLE_WALLET is false.

View file

@ -16,6 +16,7 @@
#include <net_processing.h> #include <net_processing.h>
#include <netaddress.h> #include <netaddress.h>
#include <netbase.h> #include <netbase.h>
#include <node/context.h>
#include <policy/feerate.h> #include <policy/feerate.h>
#include <policy/fees.h> #include <policy/fees.h>
#include <policy/settings.h> #include <policy/settings.h>
@ -52,7 +53,6 @@ namespace {
class NodeImpl : public Node class NodeImpl : public Node
{ {
public: public:
NodeImpl() { m_context.chain = MakeChain(); }
void initError(const std::string& message) override { InitError(message); } void initError(const std::string& message) override { InitError(message); }
bool parseParameters(int argc, const char* const argv[], std::string& error) override bool parseParameters(int argc, const char* const argv[], std::string& error) override
{ {
@ -75,10 +75,14 @@ public:
return AppInitBasicSetup() && AppInitParameterInteraction() && AppInitSanityChecks() && return AppInitBasicSetup() && AppInitParameterInteraction() && AppInitSanityChecks() &&
AppInitLockDataDirectory(); AppInitLockDataDirectory();
} }
bool appInitMain() override { return AppInitMain(m_context); } bool appInitMain() override
{
m_context.chain = MakeChain(m_context);
return AppInitMain(m_context);
}
void appShutdown() override void appShutdown() override
{ {
Interrupt(); Interrupt(m_context);
Shutdown(m_context); Shutdown(m_context);
} }
void startShutdown() override { StartShutdown(); } void startShutdown() override { StartShutdown(); }
@ -315,6 +319,7 @@ public:
/* verification progress is unused when a header was received */ 0); /* verification progress is unused when a header was received */ 0);
})); }));
} }
NodeContext* context() override { return &m_context; }
NodeContext m_context; NodeContext m_context;
}; };

View file

@ -28,6 +28,7 @@ class RPCTimerInterface;
class UniValue; class UniValue;
class proxyType; class proxyType;
struct CNodeStateStats; struct CNodeStateStats;
struct NodeContext;
enum class WalletCreationStatus; enum class WalletCreationStatus;
namespace interfaces { namespace interfaces {
@ -254,6 +255,9 @@ public:
using NotifyHeaderTipFn = using NotifyHeaderTipFn =
std::function<void(bool initial_download, int height, int64_t block_time, double verification_progress)>; std::function<void(bool initial_download, int height, int64_t block_time, double verification_progress)>;
virtual std::unique_ptr<Handler> handleNotifyHeaderTip(NotifyHeaderTipFn fn) = 0; virtual std::unique_ptr<Handler> handleNotifyHeaderTip(NotifyHeaderTipFn fn) = 0;
//! Return pointer to internal chain interface, useful for testing.
virtual NodeContext* context() { return nullptr; }
}; };
//! Return implementation of Node interface. //! Return implementation of Node interface.

View file

@ -1860,7 +1860,7 @@ void static ProcessOrphanTx(CConnman* connman, std::set<uint256>& orphan_work_se
} }
} }
bool static ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStream& vRecv, int64_t nTimeReceived, const CChainParams& chainparams, CConnman* connman, const std::atomic<bool>& interruptMsgProc) bool static ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStream& vRecv, int64_t nTimeReceived, const CChainParams& chainparams, CConnman* connman, BanMan* banman, const std::atomic<bool>& interruptMsgProc)
{ {
LogPrint(BCLog::NET, "received: %s (%u bytes) peer=%d\n", SanitizeString(strCommand), vRecv.size(), pfrom->GetId()); LogPrint(BCLog::NET, "received: %s (%u bytes) peer=%d\n", SanitizeString(strCommand), vRecv.size(), pfrom->GetId());
if (gArgs.IsArgSet("-dropmessagestest") && GetRand(gArgs.GetArg("-dropmessagestest", 0)) == 0) if (gArgs.IsArgSet("-dropmessagestest") && GetRand(gArgs.GetArg("-dropmessagestest", 0)) == 0)
@ -2136,7 +2136,7 @@ bool static ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStr
if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60) if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
addr.nTime = nNow - 5 * 24 * 60 * 60; addr.nTime = nNow - 5 * 24 * 60 * 60;
pfrom->AddAddressKnown(addr); pfrom->AddAddressKnown(addr);
if (g_banman->IsBanned(addr)) continue; // Do not process banned addresses beyond remembering we received them if (banman->IsBanned(addr)) continue; // Do not process banned addresses beyond remembering we received them
bool fReachable = IsReachable(addr); bool fReachable = IsReachable(addr);
if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable()) if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
{ {
@ -2772,7 +2772,7 @@ bool static ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStr
} // cs_main } // cs_main
if (fProcessBLOCKTXN) if (fProcessBLOCKTXN)
return ProcessMessage(pfrom, NetMsgType::BLOCKTXN, blockTxnMsg, nTimeReceived, chainparams, connman, interruptMsgProc); return ProcessMessage(pfrom, NetMsgType::BLOCKTXN, blockTxnMsg, nTimeReceived, chainparams, connman, banman, interruptMsgProc);
if (fRevertToHeaderProcessing) { if (fRevertToHeaderProcessing) {
// Headers received from HB compact block peers are permitted to be // Headers received from HB compact block peers are permitted to be
@ -2990,7 +2990,7 @@ bool static ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStr
std::vector<CAddress> vAddr = connman->GetAddresses(); std::vector<CAddress> vAddr = connman->GetAddresses();
FastRandomContext insecure_rand; FastRandomContext insecure_rand;
for (const CAddress &addr : vAddr) { for (const CAddress &addr : vAddr) {
if (!g_banman->IsBanned(addr)) { if (!banman->IsBanned(addr)) {
pfrom->PushAddress(addr, insecure_rand); pfrom->PushAddress(addr, insecure_rand);
} }
} }
@ -3310,7 +3310,7 @@ bool PeerLogicValidation::ProcessMessages(CNode* pfrom, std::atomic<bool>& inter
bool fRet = false; bool fRet = false;
try try
{ {
fRet = ProcessMessage(pfrom, strCommand, vRecv, msg.m_time, chainparams, connman, interruptMsgProc); fRet = ProcessMessage(pfrom, strCommand, vRecv, msg.m_time, chainparams, connman, m_banman, interruptMsgProc);
if (interruptMsgProc) if (interruptMsgProc)
return false; return false;
if (!pfrom->vRecvGetData.empty()) if (!pfrom->vRecvGetData.empty())

10
src/node/context.cpp Normal file
View file

@ -0,0 +1,10 @@
// Copyright (c) 2019 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 <node/context.h>
#include <interfaces/chain.h>
NodeContext::NodeContext() {}
NodeContext::~NodeContext() {}

View file

@ -13,11 +13,26 @@ class Chain;
class ChainClient; class ChainClient;
} // namespace interfaces } // namespace interfaces
//! Pointers to interfaces used during init and destroyed on shutdown. //! NodeContext struct containing references to chain state and connection
//! state.
//!
//! This is used by init, rpc, and test code to pass object references around
//! without needing to declare the same variables and parameters repeatedly, or
//! to use globals. More variables could be added to this struct (particularly
//! references to validation and mempool objects) to eliminate use of globals
//! and make code more modular and testable. The struct isn't intended to have
//! any member functions. It should just be a collection of references that can
//! be used without pulling in unwanted dependencies or functionality.
struct NodeContext struct NodeContext
{ {
std::unique_ptr<interfaces::Chain> chain; std::unique_ptr<interfaces::Chain> chain;
std::vector<std::unique_ptr<interfaces::ChainClient>> chain_clients; std::vector<std::unique_ptr<interfaces::ChainClient>> chain_clients;
//! Declare default constructor and destructor that are not inline, so code
//! instantiating the NodeContext struct doesn't need to #include class
//! definitions for all the unique_ptr members.
NodeContext();
~NodeContext();
}; };
#endif // BITCOIN_NODE_CONTEXT_H #endif // BITCOIN_NODE_CONTEXT_H

View file

@ -6,6 +6,7 @@
#include <consensus/validation.h> #include <consensus/validation.h>
#include <net.h> #include <net.h>
#include <net_processing.h> #include <net_processing.h>
#include <node/context.h>
#include <util/validation.h> #include <util/validation.h>
#include <validation.h> #include <validation.h>
#include <validationinterface.h> #include <validationinterface.h>
@ -13,7 +14,7 @@
#include <future> #include <future>
TransactionError BroadcastTransaction(const CTransactionRef tx, std::string& err_string, const CAmount& max_tx_fee, bool relay, bool wait_callback) TransactionError BroadcastTransaction(NodeContext& node, const CTransactionRef tx, std::string& err_string, const CAmount& max_tx_fee, bool relay, bool wait_callback)
{ {
// BroadcastTransaction can be called by either sendrawtransaction RPC or wallet RPCs. // BroadcastTransaction can be called by either sendrawtransaction RPC or wallet RPCs.
// g_connman is assigned both before chain clients and before RPC server is accepting calls, // g_connman is assigned both before chain clients and before RPC server is accepting calls,

View file

@ -9,6 +9,8 @@
#include <primitives/transaction.h> #include <primitives/transaction.h>
#include <util/error.h> #include <util/error.h>
struct NodeContext;
/** /**
* Submit a transaction to the mempool and (optionally) relay it to all P2P peers. * Submit a transaction to the mempool and (optionally) relay it to all P2P peers.
* *
@ -18,6 +20,7 @@
* NOT be set while cs_main, cs_mempool or cs_wallet are held to avoid * NOT be set while cs_main, cs_mempool or cs_wallet are held to avoid
* deadlock. * deadlock.
* *
* @param[in] node reference to node context
* @param[in] tx the transaction to broadcast * @param[in] tx the transaction to broadcast
* @param[out] &err_string reference to std::string to fill with error string if available * @param[out] &err_string reference to std::string to fill with error string if available
* @param[in] max_tx_fee reject txs with fees higher than this (if 0, accept any fee) * @param[in] max_tx_fee reject txs with fees higher than this (if 0, accept any fee)
@ -25,6 +28,6 @@
* @param[in] wait_callback, wait until callbacks have been processed to avoid stale result due to a sequentially RPC. * @param[in] wait_callback, wait until callbacks have been processed to avoid stale result due to a sequentially RPC.
* return error * return error
*/ */
NODISCARD TransactionError BroadcastTransaction(CTransactionRef tx, std::string& err_string, const CAmount& max_tx_fee, bool relay, bool wait_callback); NODISCARD TransactionError BroadcastTransaction(NodeContext& node, CTransactionRef tx, std::string& err_string, const CAmount& max_tx_fee, bool relay, bool wait_callback);
#endif // BITCOIN_NODE_TRANSACTION_H #endif // BITCOIN_NODE_TRANSACTION_H

View file

@ -51,11 +51,10 @@ void EditAddressAndSubmit(
* In each case, verify the resulting state of the address book and optionally * In each case, verify the resulting state of the address book and optionally
* the warning message presented to the user. * the warning message presented to the user.
*/ */
void TestAddAddressesToSendBook() void TestAddAddressesToSendBook(interfaces::Node& node)
{ {
TestChain100Setup test; TestChain100Setup test;
auto chain = interfaces::MakeChain(); std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(node.context()->chain.get(), WalletLocation(), WalletDatabase::CreateMock());
std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(chain.get(), WalletLocation(), WalletDatabase::CreateMock());
bool firstRun; bool firstRun;
wallet->LoadWallet(firstRun); wallet->LoadWallet(firstRun);
@ -101,10 +100,9 @@ void TestAddAddressesToSendBook()
// Initialize relevant QT models. // Initialize relevant QT models.
std::unique_ptr<const PlatformStyle> platformStyle(PlatformStyle::instantiate("other")); std::unique_ptr<const PlatformStyle> platformStyle(PlatformStyle::instantiate("other"));
auto node = interfaces::MakeNode(); OptionsModel optionsModel(node);
OptionsModel optionsModel(*node);
AddWallet(wallet); AddWallet(wallet);
WalletModel walletModel(std::move(node->getWallets()[0]), *node, platformStyle.get(), &optionsModel); WalletModel walletModel(interfaces::MakeWallet(wallet), node, platformStyle.get(), &optionsModel);
RemoveWallet(wallet); RemoveWallet(wallet);
EditAddressDialog editAddressDialog(EditAddressDialog::NewSendingAddress); EditAddressDialog editAddressDialog(EditAddressDialog::NewSendingAddress);
editAddressDialog.setModel(walletModel.getAddressTableModel()); editAddressDialog.setModel(walletModel.getAddressTableModel());
@ -150,5 +148,5 @@ void AddressBookTests::addressBookTests()
return; return;
} }
#endif #endif
TestAddAddressesToSendBook(); TestAddAddressesToSendBook(m_node);
} }

View file

@ -4,8 +4,16 @@
#include <QObject> #include <QObject>
#include <QTest> #include <QTest>
namespace interfaces {
class Node;
} // namespace interfaces
class AddressBookTests : public QObject class AddressBookTests : public QObject
{ {
public:
AddressBookTests(interfaces::Node& node) : m_node(node) {}
interfaces::Node& m_node;
Q_OBJECT Q_OBJECT
private Q_SLOTS: private Q_SLOTS:

View file

@ -41,7 +41,7 @@ void RPCNestedTests::rpcNestedTests()
std::string result; std::string result;
std::string result2; std::string result2;
std::string filtered; std::string filtered;
auto node = interfaces::MakeNode(); interfaces::Node* node = &m_node;
RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo()[chain]", &filtered); //simple result filtering with path RPCConsole::RPCExecuteCommandLine(*node, result, "getblockchaininfo()[chain]", &filtered); //simple result filtering with path
QVERIFY(result=="main"); QVERIFY(result=="main");
QVERIFY(filtered == "getblockchaininfo()[chain]"); QVERIFY(filtered == "getblockchaininfo()[chain]");

View file

@ -8,8 +8,16 @@
#include <QObject> #include <QObject>
#include <QTest> #include <QTest>
namespace interfaces {
class Node;
} // namespace interfaces
class RPCNestedTests : public QObject class RPCNestedTests : public QObject
{ {
public:
RPCNestedTests(interfaces::Node& node) : m_node(node) {}
interfaces::Node& m_node;
Q_OBJECT Q_OBJECT
private Q_SLOTS: private Q_SLOTS:

View file

@ -50,7 +50,7 @@ int main(int argc, char *argv[])
BasicTestingSetup dummy{CBaseChainParams::REGTEST}; BasicTestingSetup dummy{CBaseChainParams::REGTEST};
} }
auto node = interfaces::MakeNode(); std::unique_ptr<interfaces::Node> node = interfaces::MakeNode();
bool fInvalid = false; bool fInvalid = false;
@ -76,7 +76,7 @@ int main(int argc, char *argv[])
if (QTest::qExec(&test1) != 0) { if (QTest::qExec(&test1) != 0) {
fInvalid = true; fInvalid = true;
} }
RPCNestedTests test3; RPCNestedTests test3(*node);
if (QTest::qExec(&test3) != 0) { if (QTest::qExec(&test3) != 0) {
fInvalid = true; fInvalid = true;
} }
@ -85,11 +85,11 @@ int main(int argc, char *argv[])
fInvalid = true; fInvalid = true;
} }
#ifdef ENABLE_WALLET #ifdef ENABLE_WALLET
WalletTests test5; WalletTests test5(*node);
if (QTest::qExec(&test5) != 0) { if (QTest::qExec(&test5) != 0) {
fInvalid = true; fInvalid = true;
} }
AddressBookTests test6; AddressBookTests test6(*node);
if (QTest::qExec(&test6) != 0) { if (QTest::qExec(&test6) != 0) {
fInvalid = true; fInvalid = true;
} }

View file

@ -126,15 +126,14 @@ void BumpFee(TransactionView& view, const uint256& txid, bool expectDisabled, st
// QT_QPA_PLATFORM=xcb src/qt/test/test_bitcoin-qt # Linux // QT_QPA_PLATFORM=xcb src/qt/test/test_bitcoin-qt # Linux
// QT_QPA_PLATFORM=windows src/qt/test/test_bitcoin-qt # Windows // QT_QPA_PLATFORM=windows src/qt/test/test_bitcoin-qt # Windows
// QT_QPA_PLATFORM=cocoa src/qt/test/test_bitcoin-qt # macOS // QT_QPA_PLATFORM=cocoa src/qt/test/test_bitcoin-qt # macOS
void TestGUI() void TestGUI(interfaces::Node& node)
{ {
// Set up wallet and chain with 105 blocks (5 mature blocks for spending). // Set up wallet and chain with 105 blocks (5 mature blocks for spending).
TestChain100Setup test; TestChain100Setup test;
for (int i = 0; i < 5; ++i) { for (int i = 0; i < 5; ++i) {
test.CreateAndProcessBlock({}, GetScriptForRawPubKey(test.coinbaseKey.GetPubKey())); test.CreateAndProcessBlock({}, GetScriptForRawPubKey(test.coinbaseKey.GetPubKey()));
} }
auto chain = interfaces::MakeChain(); std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(node.context()->chain.get(), WalletLocation(), WalletDatabase::CreateMock());
std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(chain.get(), WalletLocation(), WalletDatabase::CreateMock());
bool firstRun; bool firstRun;
wallet->LoadWallet(firstRun); wallet->LoadWallet(firstRun);
{ {
@ -159,10 +158,9 @@ void TestGUI()
std::unique_ptr<const PlatformStyle> platformStyle(PlatformStyle::instantiate("other")); std::unique_ptr<const PlatformStyle> platformStyle(PlatformStyle::instantiate("other"));
SendCoinsDialog sendCoinsDialog(platformStyle.get()); SendCoinsDialog sendCoinsDialog(platformStyle.get());
TransactionView transactionView(platformStyle.get()); TransactionView transactionView(platformStyle.get());
auto node = interfaces::MakeNode(); OptionsModel optionsModel(node);
OptionsModel optionsModel(*node);
AddWallet(wallet); AddWallet(wallet);
WalletModel walletModel(std::move(node->getWallets().back()), *node, platformStyle.get(), &optionsModel); WalletModel walletModel(interfaces::MakeWallet(wallet), node, platformStyle.get(), &optionsModel);
RemoveWallet(wallet); RemoveWallet(wallet);
sendCoinsDialog.setModel(&walletModel); sendCoinsDialog.setModel(&walletModel);
transactionView.setModel(&walletModel); transactionView.setModel(&walletModel);
@ -260,5 +258,5 @@ void WalletTests::walletTests()
return; return;
} }
#endif #endif
TestGUI(); TestGUI(m_node);
} }

View file

@ -4,8 +4,16 @@
#include <QObject> #include <QObject>
#include <QTest> #include <QTest>
namespace interfaces {
class Node;
} // namespace interfaces
class WalletTests : public QObject class WalletTests : public QObject
{ {
public:
WalletTests(interfaces::Node& node) : m_node(node) {}
interfaces::Node& m_node;
Q_OBJECT Q_OBJECT
private Q_SLOTS: private Q_SLOTS:

View file

@ -13,6 +13,7 @@
#include <key_io.h> #include <key_io.h>
#include <miner.h> #include <miner.h>
#include <net.h> #include <net.h>
#include <node/context.h>
#include <policy/fees.h> #include <policy/fees.h>
#include <pow.h> #include <pow.h>
#include <rpc/blockchain.h> #include <rpc/blockchain.h>

View file

@ -11,6 +11,7 @@
#include <net_processing.h> #include <net_processing.h>
#include <net_permissions.h> #include <net_permissions.h>
#include <netbase.h> #include <netbase.h>
#include <node/context.h>
#include <policy/settings.h> #include <policy/settings.h>
#include <rpc/protocol.h> #include <rpc/protocol.h>
#include <rpc/util.h> #include <rpc/util.h>

View file

@ -10,7 +10,9 @@
#include <index/txindex.h> #include <index/txindex.h>
#include <key_io.h> #include <key_io.h>
#include <merkleblock.h> #include <merkleblock.h>
#include <net.h>
#include <node/coin.h> #include <node/coin.h>
#include <node/context.h>
#include <node/psbt.h> #include <node/psbt.h>
#include <node/transaction.h> #include <node/transaction.h>
#include <policy/policy.h> #include <policy/policy.h>
@ -817,7 +819,7 @@ static UniValue sendrawtransaction(const JSONRPCRequest& request)
std::string err_string; std::string err_string;
AssertLockNotHeld(cs_main); AssertLockNotHeld(cs_main);
const TransactionError err = BroadcastTransaction(tx, err_string, max_raw_tx_fee, /*relay*/ true, /*wait_callback*/ true); const TransactionError err = BroadcastTransaction(*g_rpc_node, tx, err_string, max_raw_tx_fee, /*relay*/ true, /*wait_callback*/ true);
if (TransactionError::OK != err) { if (TransactionError::OK != err) {
throw JSONRPCTransactionError(err, err_string); throw JSONRPCTransactionError(err, err_string);
} }

View file

@ -7,8 +7,8 @@
#include <rpc/util.h> #include <rpc/util.h>
#include <core_io.h> #include <core_io.h>
#include <init.h>
#include <interfaces/chain.h> #include <interfaces/chain.h>
#include <node/context.h>
#include <test/setup_common.h> #include <test/setup_common.h>
#include <util/time.h> #include <util/time.h>
@ -113,7 +113,7 @@ BOOST_AUTO_TEST_CASE(rpc_rawsign)
std::string privkey1 = "\"KzsXybp9jX64P5ekX1KUxRQ79Jht9uzW7LorgwE65i5rWACL6LQe\""; std::string privkey1 = "\"KzsXybp9jX64P5ekX1KUxRQ79Jht9uzW7LorgwE65i5rWACL6LQe\"";
std::string privkey2 = "\"Kyhdf5LuKTRx4ge69ybABsiUAWjVRK4XGxAKk2FQLp2HjGMy87Z4\""; std::string privkey2 = "\"Kyhdf5LuKTRx4ge69ybABsiUAWjVRK4XGxAKk2FQLp2HjGMy87Z4\"";
NodeContext node; NodeContext node;
node.chain = interfaces::MakeChain(); node.chain = interfaces::MakeChain(node);
g_rpc_node = &node; g_rpc_node = &node;
r = CallRPC(std::string("signrawtransactionwithkey ")+notsigned+" [] "+prevout); r = CallRPC(std::string("signrawtransactionwithkey ")+notsigned+" [] "+prevout);
BOOST_CHECK(find_value(r.get_obj(), "complete").get_bool() == false); BOOST_CHECK(find_value(r.get_obj(), "complete").get_bool() == false);

View file

@ -8,6 +8,7 @@
#include <chainparamsbase.h> #include <chainparamsbase.h>
#include <fs.h> #include <fs.h>
#include <key.h> #include <key.h>
#include <node/context.h>
#include <pubkey.h> #include <pubkey.h>
#include <random.h> #include <random.h>
#include <scheduler.h> #include <scheduler.h>
@ -67,6 +68,7 @@ private:
* Included are coins database, script check threads setup. * Included are coins database, script check threads setup.
*/ */
struct TestingSetup : public BasicTestingSetup { struct TestingSetup : public BasicTestingSetup {
NodeContext m_node;
boost::thread_group threadGroup; boost::thread_group threadGroup;
CScheduler scheduler; CScheduler scheduler;

View file

@ -6,6 +6,7 @@
#include <init.h> #include <init.h>
#include <interfaces/chain.h> #include <interfaces/chain.h>
#include <net.h> #include <net.h>
#include <node/context.h>
#include <outputtype.h> #include <outputtype.h>
#include <util/moneystr.h> #include <util/moneystr.h>
#include <util/system.h> #include <util/system.h>

View file

@ -5,9 +5,9 @@
#include <amount.h> #include <amount.h>
#include <core_io.h> #include <core_io.h>
#include <init.h>
#include <interfaces/chain.h> #include <interfaces/chain.h>
#include <key_io.h> #include <key_io.h>
#include <node/context.h>
#include <outputtype.h> #include <outputtype.h>
#include <policy/feerate.h> #include <policy/feerate.h>
#include <policy/fees.h> #include <policy/fees.h>

View file

@ -2,6 +2,7 @@
// Distributed under the MIT software license, see the accompanying // Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php. // file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <node/context.h>
#include <wallet/wallet.h> #include <wallet/wallet.h>
#include <wallet/coinselection.h> #include <wallet/coinselection.h>
#include <wallet/coincontrol.h> #include <wallet/coincontrol.h>
@ -28,7 +29,8 @@ std::vector<std::unique_ptr<CWalletTx>> wtxn;
typedef std::set<CInputCoin> CoinSet; typedef std::set<CInputCoin> CoinSet;
static std::vector<COutput> vCoins; static std::vector<COutput> vCoins;
static auto testChain = interfaces::MakeChain(); static NodeContext testNode;
static auto testChain = interfaces::MakeChain(testNode);
static CWallet testWallet(testChain.get(), WalletLocation(), WalletDatabase::CreateDummy()); static CWallet testWallet(testChain.get(), WalletLocation(), WalletDatabase::CreateDummy());
static CAmount balance = 0; static CAmount balance = 0;

View file

@ -6,6 +6,7 @@
#define BITCOIN_WALLET_TEST_INIT_TEST_FIXTURE_H #define BITCOIN_WALLET_TEST_INIT_TEST_FIXTURE_H
#include <interfaces/chain.h> #include <interfaces/chain.h>
#include <node/context.h>
#include <test/setup_common.h> #include <test/setup_common.h>
@ -17,7 +18,8 @@ struct InitWalletDirTestingSetup: public BasicTestingSetup {
fs::path m_datadir; fs::path m_datadir;
fs::path m_cwd; fs::path m_cwd;
std::map<std::string, fs::path> m_walletdir_path_cases; std::map<std::string, fs::path> m_walletdir_path_cases;
std::unique_ptr<interfaces::Chain> m_chain = interfaces::MakeChain(); NodeContext m_node;
std::unique_ptr<interfaces::Chain> m_chain = interfaces::MakeChain(m_node);
std::unique_ptr<interfaces::ChainClient> m_chain_client; std::unique_ptr<interfaces::ChainClient> m_chain_client;
}; };

View file

@ -3,6 +3,7 @@
// file COPYING or http://www.opensource.org/licenses/mit-license.php. // file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <key.h> #include <key.h>
#include <node/context.h>
#include <script/script.h> #include <script/script.h>
#include <script/standard.h> #include <script/standard.h>
#include <test/setup_common.h> #include <test/setup_common.h>
@ -26,7 +27,8 @@ BOOST_AUTO_TEST_CASE(ismine_standard)
CKey uncompressedKey; CKey uncompressedKey;
uncompressedKey.MakeNewKey(false); uncompressedKey.MakeNewKey(false);
CPubKey uncompressedPubkey = uncompressedKey.GetPubKey(); CPubKey uncompressedPubkey = uncompressedKey.GetPubKey();
std::unique_ptr<interfaces::Chain> chain = interfaces::MakeChain(); NodeContext node;
std::unique_ptr<interfaces::Chain> chain = interfaces::MakeChain(node);
CScript scriptPubKey; CScript scriptPubKey;
isminetype result; isminetype result;

View file

@ -9,6 +9,7 @@
#include <interfaces/chain.h> #include <interfaces/chain.h>
#include <interfaces/wallet.h> #include <interfaces/wallet.h>
#include <node/context.h>
#include <wallet/wallet.h> #include <wallet/wallet.h>
#include <memory> #include <memory>
@ -18,7 +19,8 @@
struct WalletTestingSetup: public TestingSetup { struct WalletTestingSetup: public TestingSetup {
explicit WalletTestingSetup(const std::string& chainName = CBaseChainParams::MAIN); explicit WalletTestingSetup(const std::string& chainName = CBaseChainParams::MAIN);
std::unique_ptr<interfaces::Chain> m_chain = interfaces::MakeChain(); NodeContext m_node;
std::unique_ptr<interfaces::Chain> m_chain = interfaces::MakeChain(m_node);
std::unique_ptr<interfaces::ChainClient> m_chain_client = interfaces::MakeWalletClient(*m_chain, {}); std::unique_ptr<interfaces::ChainClient> m_chain_client = interfaces::MakeWalletClient(*m_chain, {});
CWallet m_wallet; CWallet m_wallet;
}; };

View file

@ -9,6 +9,7 @@
#include <vector> #include <vector>
#include <interfaces/chain.h> #include <interfaces/chain.h>
#include <node/context.h>
#include <policy/policy.h> #include <policy/policy.h>
#include <rpc/server.h> #include <rpc/server.h>
#include <test/setup_common.h> #include <test/setup_common.h>
@ -39,7 +40,8 @@ BOOST_FIXTURE_TEST_CASE(scan_for_wallet_transactions, TestChain100Setup)
CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())); CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
CBlockIndex* newTip = ::ChainActive().Tip(); CBlockIndex* newTip = ::ChainActive().Tip();
auto chain = interfaces::MakeChain(); NodeContext node;
auto chain = interfaces::MakeChain(node);
auto locked_chain = chain->lock(); auto locked_chain = chain->lock();
LockAssertion lock(::cs_main); LockAssertion lock(::cs_main);
@ -118,7 +120,8 @@ BOOST_FIXTURE_TEST_CASE(importmulti_rescan, TestChain100Setup)
CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())); CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
CBlockIndex* newTip = ::ChainActive().Tip(); CBlockIndex* newTip = ::ChainActive().Tip();
auto chain = interfaces::MakeChain(); NodeContext node;
auto chain = interfaces::MakeChain(node);
auto locked_chain = chain->lock(); auto locked_chain = chain->lock();
LockAssertion lock(::cs_main); LockAssertion lock(::cs_main);
@ -185,7 +188,8 @@ BOOST_FIXTURE_TEST_CASE(importwallet_rescan, TestChain100Setup)
SetMockTime(KEY_TIME); SetMockTime(KEY_TIME);
m_coinbase_txns.emplace_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]); m_coinbase_txns.emplace_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]);
auto chain = interfaces::MakeChain(); NodeContext node;
auto chain = interfaces::MakeChain(node);
auto locked_chain = chain->lock(); auto locked_chain = chain->lock();
LockAssertion lock(::cs_main); LockAssertion lock(::cs_main);
@ -239,7 +243,8 @@ BOOST_FIXTURE_TEST_CASE(importwallet_rescan, TestChain100Setup)
// debit functions. // debit functions.
BOOST_FIXTURE_TEST_CASE(coin_mark_dirty_immature_credit, TestChain100Setup) BOOST_FIXTURE_TEST_CASE(coin_mark_dirty_immature_credit, TestChain100Setup)
{ {
auto chain = interfaces::MakeChain(); NodeContext node;
auto chain = interfaces::MakeChain(node);
CWallet wallet(chain.get(), WalletLocation(), WalletDatabase::CreateDummy()); CWallet wallet(chain.get(), WalletLocation(), WalletDatabase::CreateDummy());
CWalletTx wtx(&wallet, m_coinbase_txns.back()); CWalletTx wtx(&wallet, m_coinbase_txns.back());
@ -466,7 +471,8 @@ public:
return it->second; return it->second;
} }
std::unique_ptr<interfaces::Chain> m_chain = interfaces::MakeChain(); NodeContext m_node;
std::unique_ptr<interfaces::Chain> m_chain = interfaces::MakeChain(m_node);
std::unique_ptr<CWallet> wallet; std::unique_ptr<CWallet> wallet;
}; };
@ -538,7 +544,8 @@ BOOST_FIXTURE_TEST_CASE(ListCoins, ListCoinsTestingSetup)
BOOST_FIXTURE_TEST_CASE(wallet_disableprivkeys, TestChain100Setup) BOOST_FIXTURE_TEST_CASE(wallet_disableprivkeys, TestChain100Setup)
{ {
auto chain = interfaces::MakeChain(); NodeContext node;
auto chain = interfaces::MakeChain(node);
std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(chain.get(), WalletLocation(), WalletDatabase::CreateDummy()); std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(chain.get(), WalletLocation(), WalletDatabase::CreateDummy());
wallet->SetMinVersion(FEATURE_LATEST); wallet->SetMinVersion(FEATURE_LATEST);
wallet->SetWalletFlag(WALLET_FLAG_DISABLE_PRIVATE_KEYS); wallet->SetWalletFlag(WALLET_FLAG_DISABLE_PRIVATE_KEYS);