Bitcoin Core 31.99.0
P2P Digital Currency
run_command.cpp
Go to the documentation of this file.
1// Copyright (c) 2022-present 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#include <bitcoin-build-config.h> // IWYU pragma: keep
6
8
9#include <tinyformat.h>
10#include <univalue.h>
11#include <util/string.h>
12
13#ifdef ENABLE_EXTERNAL_SIGNER
14#include <util/subprocess.h>
15#endif // ENABLE_EXTERNAL_SIGNER
16
17#include <sstream>
18#include <stdexcept>
19#include <utility>
20
21UniValue RunCommandParseJSON(const std::vector<std::string>& cmd_args, const std::string& str_std_in)
22{
23#ifdef ENABLE_EXTERNAL_SIGNER
24 namespace sp = subprocess;
25
26 UniValue result_json;
27 std::istringstream stdout_stream;
28 std::istringstream stderr_stream;
29
30 if (cmd_args.empty()) return UniValue::VNULL;
31
32 auto c = sp::Popen(cmd_args, sp::input{sp::PIPE}, sp::output{sp::PIPE}, sp::error{sp::PIPE});
33 if (!str_std_in.empty()) {
34 c.send(str_std_in);
35 }
36 auto [out_res, err_res] = c.communicate();
37 stdout_stream.str(std::string{out_res.buf.begin(), out_res.buf.end()});
38 stderr_stream.str(std::string{err_res.buf.begin(), err_res.buf.end()});
39
40 std::string result;
41 std::string error;
42 std::getline(stdout_stream, result);
43 std::getline(stderr_stream, error);
44
45 const int n_error = c.retcode();
46 if (n_error) throw std::runtime_error(strprintf("RunCommandParseJSON error: process(%s) returned %d: %s\n", util::Join(cmd_args, " "), n_error, error));
47 if (!result_json.read(result)) throw std::runtime_error("Unable to parse JSON: " + result);
48
49 return result_json;
50#else
51 throw std::runtime_error("Compiled without external signing support (required for external signing).");
52#endif // ENABLE_EXTERNAL_SIGNER
53}
@ VNULL
Definition: univalue.h:24
bool read(std::string_view raw)
auto Join(const C &container, const S &separator, UnaryOp unary_op)
Join all container items.
Definition: string.h:208
UniValue RunCommandParseJSON(const std::vector< std::string > &cmd_args, const std::string &str_std_in)
Execute a command which returns JSON, and parse the result.
Definition: run_command.cpp:21
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1172