2022-09-28 18:02:23 +00:00
|
|
|
// Copyright (c) 2022 The Bitcoin Core developers
|
|
|
|
// Distributed under the MIT software license, see the accompanying
|
|
|
|
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
|
|
|
|
|
|
|
#if defined(HAVE_CONFIG_H)
|
|
|
|
#include <config/bitcoin-config.h>
|
|
|
|
#endif
|
|
|
|
|
2022-10-04 18:15:53 +00:00
|
|
|
#include <common/run_command.h>
|
2022-09-28 18:02:23 +00:00
|
|
|
|
|
|
|
#include <tinyformat.h>
|
|
|
|
#include <univalue.h>
|
|
|
|
|
|
|
|
#ifdef ENABLE_EXTERNAL_SIGNER
|
2024-04-19 11:02:01 +01:00
|
|
|
#include <util/subprocess.h>
|
2022-09-28 18:02:23 +00:00
|
|
|
#endif // ENABLE_EXTERNAL_SIGNER
|
|
|
|
|
|
|
|
UniValue RunCommandParseJSON(const std::string& str_command, const std::string& str_std_in)
|
|
|
|
{
|
|
|
|
#ifdef ENABLE_EXTERNAL_SIGNER
|
2023-03-12 18:59:25 +01:00
|
|
|
namespace sp = subprocess;
|
2022-09-28 18:02:23 +00:00
|
|
|
|
|
|
|
UniValue result_json;
|
2023-03-12 18:59:25 +01:00
|
|
|
std::istringstream stdout_stream;
|
|
|
|
std::istringstream stderr_stream;
|
2022-09-28 18:02:23 +00:00
|
|
|
|
|
|
|
if (str_command.empty()) return UniValue::VNULL;
|
|
|
|
|
2023-03-12 18:59:25 +01:00
|
|
|
auto c = sp::Popen(str_command, sp::input{sp::PIPE}, sp::output{sp::PIPE}, sp::error{sp::PIPE});
|
2022-09-28 18:02:23 +00:00
|
|
|
if (!str_std_in.empty()) {
|
2023-03-12 18:59:25 +01:00
|
|
|
c.send(str_std_in);
|
2022-09-28 18:02:23 +00:00
|
|
|
}
|
2023-03-12 18:59:25 +01:00
|
|
|
auto [out_res, err_res] = c.communicate();
|
|
|
|
stdout_stream.str(std::string{out_res.buf.begin(), out_res.buf.end()});
|
|
|
|
stderr_stream.str(std::string{err_res.buf.begin(), err_res.buf.end()});
|
2022-09-28 18:02:23 +00:00
|
|
|
|
|
|
|
std::string result;
|
|
|
|
std::string error;
|
|
|
|
std::getline(stdout_stream, result);
|
|
|
|
std::getline(stderr_stream, error);
|
|
|
|
|
2023-03-12 18:59:25 +01:00
|
|
|
const int n_error = c.retcode();
|
2022-09-28 18:02:23 +00:00
|
|
|
if (n_error) throw std::runtime_error(strprintf("RunCommandParseJSON error: process(%s) returned %d: %s\n", str_command, n_error, error));
|
|
|
|
if (!result_json.read(result)) throw std::runtime_error("Unable to parse JSON: " + result);
|
|
|
|
|
|
|
|
return result_json;
|
|
|
|
#else
|
|
|
|
throw std::runtime_error("Compiled without external signing support (required for external signing).");
|
|
|
|
#endif // ENABLE_EXTERNAL_SIGNER
|
|
|
|
}
|