|
| 1 | +// Copyright (c) 2022 The Bitcoin Core developers |
| 2 | +// Distributed under the MIT software license, see the accompanying |
| 3 | +// file COPYING or http://www.opensource.org/licenses/mit-license.php. |
| 4 | + |
| 5 | +#if defined(HAVE_CONFIG_H) |
| 6 | +#include <config/bitcoin-config.h> |
| 7 | +#endif |
| 8 | + |
| 9 | +#include <common/run_command.h> |
| 10 | + |
| 11 | +#include <tinyformat.h> |
| 12 | +#include <univalue.h> |
| 13 | + |
| 14 | +#ifdef ENABLE_EXTERNAL_SIGNER |
| 15 | +#if defined(__GNUC__) |
| 16 | +// Boost 1.78 requires the following workaround. |
| 17 | +// See: https://github.com/boostorg/process/issues/235 |
| 18 | +#pragma GCC diagnostic push |
| 19 | +#pragma GCC diagnostic ignored "-Wnarrowing" |
| 20 | +#endif |
| 21 | +#include <boost/process.hpp> |
| 22 | +#if defined(__GNUC__) |
| 23 | +#pragma GCC diagnostic pop |
| 24 | +#endif |
| 25 | +#endif // ENABLE_EXTERNAL_SIGNER |
| 26 | + |
| 27 | +UniValue RunCommandParseJSON(const std::string& str_command, const std::string& str_std_in) |
| 28 | +{ |
| 29 | +#ifdef ENABLE_EXTERNAL_SIGNER |
| 30 | + namespace bp = boost::process; |
| 31 | + |
| 32 | + UniValue result_json; |
| 33 | + bp::opstream stdin_stream; |
| 34 | + bp::ipstream stdout_stream; |
| 35 | + bp::ipstream stderr_stream; |
| 36 | + |
| 37 | + if (str_command.empty()) return UniValue::VNULL; |
| 38 | + |
| 39 | + bp::child c( |
| 40 | + str_command, |
| 41 | + bp::std_out > stdout_stream, |
| 42 | + bp::std_err > stderr_stream, |
| 43 | + bp::std_in < stdin_stream |
| 44 | + ); |
| 45 | + if (!str_std_in.empty()) { |
| 46 | + stdin_stream << str_std_in << std::endl; |
| 47 | + } |
| 48 | + stdin_stream.pipe().close(); |
| 49 | + |
| 50 | + std::string result; |
| 51 | + std::string error; |
| 52 | + std::getline(stdout_stream, result); |
| 53 | + std::getline(stderr_stream, error); |
| 54 | + |
| 55 | + c.wait(); |
| 56 | + const int n_error = c.exit_code(); |
| 57 | + if (n_error) throw std::runtime_error(strprintf("RunCommandParseJSON error: process(%s) returned %d: %s\n", str_command, n_error, error)); |
| 58 | + if (!result_json.read(result)) throw std::runtime_error("Unable to parse JSON: " + result); |
| 59 | + |
| 60 | + return result_json; |
| 61 | +#else |
| 62 | + throw std::runtime_error("Compiled without external signing support (required for external signing)."); |
| 63 | +#endif // ENABLE_EXTERNAL_SIGNER |
| 64 | +} |
0 commit comments