diff --git a/src/qt/test/rpcnestedtests.cpp b/src/qt/test/rpcnestedtests.cpp index 93c2a45479..237d85b008 100644 --- a/src/qt/test/rpcnestedtests.cpp +++ b/src/qt/test/rpcnestedtests.cpp @@ -1,202 +1,200 @@ // Copyright (c) 2016 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 "rpcnestedtests.h" #include "chainparams.h" #include "config.h" #include "consensus/validation.h" #include "fs.h" #include "rpc/register.h" #include "rpc/server.h" #include "rpcconsole.h" #include "test/test_bitcoin.h" #include "univalue.h" #include "util.h" #include "validation.h" #include #include static UniValue rpcNestedTest_rpc(const Config &config, const JSONRPCRequest &request) { if (request.fHelp) { return "help message"; } return request.params.write(0, 0); } static const ContextFreeRPCCommand vRPCCommands[] = { {"test", "rpcNestedTest", &rpcNestedTest_rpc, {}}, }; void RPCNestedTests::rpcNestedTests() { // do some test setup // could be moved to a more generic place when we add more tests on QT level tableRPC.appendCommand("rpcNestedTest", &vRPCCommands[0]); ClearDatadirCache(); std::string path = QDir::tempPath().toStdString() + "/" + strprintf("test_bitcoin_qt_%lu_%i", (unsigned long)GetTime(), (int)(GetRand(100000))); QDir dir(QString::fromStdString(path)); dir.mkpath("."); gArgs.ForceSetArg("-datadir", path); // mempool.setSanityCheck(1.0); TestingSetup test; - SetRPCWarmupFinished(); - std::string result; std::string result2; std::string filtered; // Simple result filtering with path. RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo()[chain]", &filtered); QVERIFY(result == "main"); QVERIFY(filtered == "getblockchaininfo()[chain]"); // Simple 2 level nesting. RPCConsole::RPCExecuteCommandLine(result, "getblock(getbestblockhash())"); RPCConsole::RPCExecuteCommandLine( result, "getblock(getblock(getbestblockhash())[hash], true)"); // 4 level nesting with whitespace, filtering path and boolean parameter. RPCConsole::RPCExecuteCommandLine( result, "getblock( getblock( getblock(getbestblockhash())[hash] " ")[hash], true)"); RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo"); QVERIFY(result.substr(0, 1) == "{"); RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo()"); QVERIFY(result.substr(0, 1) == "{"); // Whitespace at the end will be tolerated. RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo "); QVERIFY(result.substr(0, 1) == "{"); // Quote path identifier are allowed, but look after a child contaning the // quotes in the key. (RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo()[\"chain\"]")); QVERIFY(result == "null"); // parameter not in brackets are allowed. (RPCConsole::RPCExecuteCommandLine(result, "createrawtransaction [] {} 0")); // Parameter in brackets are allowed. (RPCConsole::RPCExecuteCommandLine(result2, "createrawtransaction([],{},0)")); QVERIFY(result == result2); // Whitespace between parametres is allowed. (RPCConsole::RPCExecuteCommandLine( result2, "createrawtransaction( [], {} , 0 )")); QVERIFY(result == result2); RPCConsole::RPCExecuteCommandLine( result, "getblock(getbestblockhash())[tx][0]", &filtered); QVERIFY(result == "4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"); QVERIFY(filtered == "getblock(getbestblockhash())[tx][0]"); RPCConsole::RPCParseCommandLine(result, "importprivkey", false, &filtered); QVERIFY(filtered == "importprivkey(…)"); RPCConsole::RPCParseCommandLine(result, "signmessagewithprivkey abc", false, &filtered); QVERIFY(filtered == "signmessagewithprivkey(…)"); RPCConsole::RPCParseCommandLine(result, "signmessagewithprivkey abc,def", false, &filtered); QVERIFY(filtered == "signmessagewithprivkey(…)"); RPCConsole::RPCParseCommandLine(result, "signrawtransaction(abc)", false, &filtered); QVERIFY(filtered == "signrawtransaction(…)"); RPCConsole::RPCParseCommandLine(result, "walletpassphrase(help())", false, &filtered); QVERIFY(filtered == "walletpassphrase(…)"); RPCConsole::RPCParseCommandLine( result, "walletpassphrasechange(help(walletpassphrasechange(abc)))", false, &filtered); QVERIFY(filtered == "walletpassphrasechange(…)"); RPCConsole::RPCParseCommandLine(result, "help(encryptwallet(abc, def))", false, &filtered); QVERIFY(filtered == "help(encryptwallet(…))"); RPCConsole::RPCParseCommandLine(result, "help(importprivkey())", false, &filtered); QVERIFY(filtered == "help(importprivkey(…))"); RPCConsole::RPCParseCommandLine(result, "help(importprivkey(help()))", false, &filtered); QVERIFY(filtered == "help(importprivkey(…))"); RPCConsole::RPCParseCommandLine( result, "help(importprivkey(abc), walletpassphrase(def))", false, &filtered); QVERIFY(filtered == "help(importprivkey(…), walletpassphrase(…))"); RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest"); QVERIFY(result == "[]"); RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest ''"); QVERIFY(result == "[\"\"]"); RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest \"\""); QVERIFY(result == "[\"\"]"); RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest '' abc"); QVERIFY(result == "[\"\",\"abc\"]"); RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest abc '' abc"); QVERIFY(result == "[\"abc\",\"\",\"abc\"]"); RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest abc abc"); QVERIFY(result == "[\"abc\",\"abc\"]"); RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest abc\t\tabc"); QVERIFY(result == "[\"abc\",\"abc\"]"); RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest(abc )"); QVERIFY(result == "[\"abc\"]"); RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest( abc )"); QVERIFY(result == "[\"abc\"]"); RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest( abc , cba )"); QVERIFY(result == "[\"abc\",\"cba\"]"); #if QT_VERSION >= 0x050300 // do the QVERIFY_EXCEPTION_THROWN checks only with Qt5.3 and higher // (QVERIFY_EXCEPTION_THROWN was introduced in Qt5.3) // invalid syntax QVERIFY_EXCEPTION_THROWN( RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo() .\n"), std::runtime_error); // invalid syntax QVERIFY_EXCEPTION_THROWN( RPCConsole::RPCExecuteCommandLine( result, "getblockchaininfo() getblockchaininfo()"), std::runtime_error); // tolerate non closing brackets if we have no arguments. (RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo(")); // tolerate non command brackts (RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo()()()")); // invalid argument QVERIFY_EXCEPTION_THROWN( RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo(True)"), UniValue); // method not found QVERIFY_EXCEPTION_THROWN( RPCConsole::RPCExecuteCommandLine(result, "a(getblockchaininfo(True))"), UniValue); // don't tollerate empty arguments when using , QVERIFY_EXCEPTION_THROWN( RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest abc,,abc"), std::runtime_error); // don't tollerate empty arguments when using , QVERIFY_EXCEPTION_THROWN( RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest(abc,,abc)"), std::runtime_error); // don't tollerate empty arguments when using , QVERIFY_EXCEPTION_THROWN( RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest(abc,,)"), std::runtime_error); #endif fs::remove_all(fs::path(path)); } diff --git a/src/test/test_bitcoin.cpp b/src/test/test_bitcoin.cpp index b5df70105e..029b41d557 100644 --- a/src/test/test_bitcoin.cpp +++ b/src/test/test_bitcoin.cpp @@ -1,275 +1,286 @@ // Copyright (c) 2011-2016 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 "test_bitcoin.h" #include "chainparams.h" #include "config.h" #include "consensus/consensus.h" #include "consensus/validation.h" #include "crypto/sha256.h" #include "fs.h" #include "key.h" #include "logging.h" #include "miner.h" #include "net_processing.h" #include "pubkey.h" #include "random.h" #include "rpc/register.h" #include "rpc/server.h" #include "script/scriptcache.h" #include "script/sigcache.h" #include "txdb.h" #include "txmempool.h" #include "ui_interface.h" #include "validation.h" #include #include #include #include #include #include #include #include void CConnmanTest::AddNode(CNode &node) { LOCK(g_connman->cs_vNodes); g_connman->vNodes.push_back(&node); } void CConnmanTest::ClearNodes() { LOCK(g_connman->cs_vNodes); g_connman->vNodes.clear(); } uint256 insecure_rand_seed = GetRandHash(); FastRandomContext insecure_rand_ctx(insecure_rand_seed); extern void noui_connect(); BasicTestingSetup::BasicTestingSetup(const std::string &chainName) { SHA256AutoDetect(); RandomInit(); ECC_Start(); SetupEnvironment(); SetupNetworking(); InitSignatureCache(); InitScriptExecutionCache(); // Don't want to write to debug.log file. GetLogger().m_print_to_file = false; fCheckBlockIndex = true; SelectParams(chainName); noui_connect(); // Set config parameters to default. GlobalConfig config; config.SetMaxBlockSize(DEFAULT_MAX_BLOCK_SIZE); } BasicTestingSetup::~BasicTestingSetup() { ECC_Stop(); } TestingSetup::TestingSetup(const std::string &chainName) : BasicTestingSetup(chainName) { const Config &config = GetConfig(); const CChainParams &chainparams = config.GetChainParams(); // Ideally we'd move all the RPC tests to the functional testing framework // instead of unit tests, but for now we need these here. RPCServer rpcServer; RegisterAllRPCCommands(config, rpcServer, tableRPC); + + /** + * RPC does not come out of the warmup state on its own. Normally, this is + * handled in bitcoind's init path, but unit tests do not trigger this + * codepath, so we call it explicitly as part of setup. + */ + std::string rpcWarmupStatus; + if (RPCIsInWarmup(&rpcWarmupStatus)) { + SetRPCWarmupFinished(); + } + ClearDatadirCache(); pathTemp = fs::temp_directory_path() / strprintf("test_bitcoin_%lu_%i", (unsigned long)GetTime(), (int)(InsecureRandRange(100000))); fs::create_directories(pathTemp); gArgs.ForceSetArg("-datadir", pathTemp.string()); // Note that because we don't bother running a scheduler thread here, // callbacks via CValidationInterface are unreliable, but that's OK, // our unit tests aren't testing multiple parts of the code at once. GetMainSignals().RegisterBackgroundSignalScheduler(scheduler); g_mempool.setSanityCheck(1.0); pblocktree.reset(new CBlockTreeDB(1 << 20, true)); pcoinsdbview.reset(new CCoinsViewDB(1 << 23, true)); pcoinsTip.reset(new CCoinsViewCache(pcoinsdbview.get())); if (!LoadGenesisBlock(chainparams)) { throw std::runtime_error("InitBlockIndex failed."); } { CValidationState state; if (!ActivateBestChain(config, state)) { throw std::runtime_error("ActivateBestChain failed."); } } nScriptCheckThreads = 3; for (int i = 0; i < nScriptCheckThreads - 1; i++) { threadGroup.create_thread(&ThreadScriptCheck); } // Deterministic randomness for tests. g_connman = std::unique_ptr(new CConnman(config, 0x1337, 0x1337)); connman = g_connman.get(); peerLogic.reset(new PeerLogicValidation(connman, scheduler)); } TestingSetup::~TestingSetup() { threadGroup.interrupt_all(); threadGroup.join_all(); GetMainSignals().FlushBackgroundCallbacks(); GetMainSignals().UnregisterBackgroundSignalScheduler(); g_connman.reset(); peerLogic.reset(); UnloadBlockIndex(); pcoinsTip.reset(); pcoinsdbview.reset(); pblocktree.reset(); fs::remove_all(pathTemp); } TestChain100Setup::TestChain100Setup() : TestingSetup(CBaseChainParams::REGTEST) { // Generate a 100-block chain: coinbaseKey.MakeNewKey(true); CScript scriptPubKey = CScript() << ToByteVector(coinbaseKey.GetPubKey()) << OP_CHECKSIG; for (int i = 0; i < COINBASE_MATURITY; i++) { std::vector noTxns; CBlock b = CreateAndProcessBlock(noTxns, scriptPubKey); coinbaseTxns.push_back(*b.vtx[0]); } } // // Create a new block with just given transactions, coinbase paying to // scriptPubKey, and try to add it to the current chain. // CBlock TestChain100Setup::CreateAndProcessBlock( const std::vector &txns, const CScript &scriptPubKey) { const Config &config = GetConfig(); std::unique_ptr pblocktemplate = BlockAssembler(config, g_mempool).CreateNewBlock(scriptPubKey); CBlock &block = pblocktemplate->block; // Replace mempool-selected txns with just coinbase plus passed-in txns: block.vtx.resize(1); for (const CMutableTransaction &tx : txns) { block.vtx.push_back(MakeTransactionRef(tx)); } // Order transactions by canonical order std::sort(std::begin(block.vtx) + 1, std::end(block.vtx), [](const std::shared_ptr &txa, const std::shared_ptr &txb) -> bool { return txa->GetId() < txb->GetId(); }); // IncrementExtraNonce creates a valid coinbase and merkleRoot unsigned int extraNonce = 0; IncrementExtraNonce(config, &block, chainActive.Tip(), extraNonce); while (!CheckProofOfWork(block.GetHash(), block.nBits, config)) { ++block.nNonce; } std::shared_ptr shared_pblock = std::make_shared(block); ProcessNewBlock(GetConfig(), shared_pblock, true, nullptr); CBlock result = block; return result; } TestChain100Setup::~TestChain100Setup() {} CTxMemPoolEntry TestMemPoolEntryHelper::FromTx(const CMutableTransaction &tx, CTxMemPool *pool) { CTransaction txn(tx); return FromTx(txn, pool); } CTxMemPoolEntry TestMemPoolEntryHelper::FromTx(const CTransaction &txn, CTxMemPool *pool) { // Hack to assume either it's completely dependent on other mempool txs or // not at all. Amount inChainValue = pool && pool->HasNoInputsOf(txn) ? txn.GetValueOut() : Amount::zero(); return CTxMemPoolEntry(MakeTransactionRef(txn), nFee, nTime, dPriority, nHeight, inChainValue, spendsCoinbase, sigOpCost, lp); } namespace { // A place to put misc. setup code eg "the travis workaround" that needs to run // at program startup and exit struct Init { Init(); ~Init(); std::list> cleanup; }; Init init; Init::Init() { if (getenv("TRAVIS_NOHANG_WORKAROUND")) { // This is a workaround for MinGW/Win32 builds on Travis sometimes // hanging due to no output received by Travis after a 10-minute // timeout. // The strategy here is to let the jobs finish however long they take // on Travis, by feeding Travis output. We start a parallel thread // that just prints out '.' once per second. struct Private { Private() : stop(false) {} std::atomic_bool stop; std::thread thr; std::condition_variable cond; std::mutex mut; } *p = new Private; p->thr = std::thread([p] { // thread func.. print dots std::unique_lock lock(p->mut); unsigned ctr = 0; while (!p->stop) { if (ctr) { // skip first period to allow app to print first std::cerr << "." << std::flush; } if (!(++ctr % 79)) { // newline once in a while to keep travis happy std::cerr << std::endl; } p->cond.wait_for(lock, std::chrono::milliseconds(1000)); } }); cleanup.emplace_back([p]() { // cleanup function to kill the thread and delete the struct p->mut.lock(); p->stop = true; p->cond.notify_all(); p->mut.unlock(); if (p->thr.joinable()) { p->thr.join(); } delete p; }); } } Init::~Init() { for (auto &f : cleanup) { if (f) { f(); } } } } // end anonymous namespace