Bitcoin Core  27.99.0
P2P Digital Currency
run_command.cpp
Go to the documentation of this file.
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)
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 #include <boost/process.hpp>
16 #endif // ENABLE_EXTERNAL_SIGNER
17 
18 UniValue RunCommandParseJSON(const std::string& str_command, const std::string& str_std_in)
19 {
20 #ifdef ENABLE_EXTERNAL_SIGNER
21  namespace bp = boost::process;
22 
23  UniValue result_json;
24  bp::opstream stdin_stream;
25  bp::ipstream stdout_stream;
26  bp::ipstream stderr_stream;
27 
28  if (str_command.empty()) return UniValue::VNULL;
29 
30  bp::child c(
31  str_command,
32  bp::std_out > stdout_stream,
33  bp::std_err > stderr_stream,
34  bp::std_in < stdin_stream
35  );
36  if (!str_std_in.empty()) {
37  stdin_stream << str_std_in << std::endl;
38  }
39  stdin_stream.pipe().close();
40 
41  std::string result;
42  std::string error;
43  std::getline(stdout_stream, result);
44  std::getline(stderr_stream, error);
45 
46  c.wait();
47  const int n_error = c.exit_code();
48  if (n_error) throw std::runtime_error(strprintf("RunCommandParseJSON error: process(%s) returned %d: %s\n", str_command, n_error, error));
49  if (!result_json.read(result)) throw std::runtime_error("Unable to parse JSON: " + result);
50 
51  return result_json;
52 #else
53  throw std::runtime_error("Compiled without external signing support (required for external signing).");
54 #endif // ENABLE_EXTERNAL_SIGNER
55 }
@ VNULL
Definition: univalue.h:23
bool read(std::string_view raw)
UniValue RunCommandParseJSON(const std::string &str_command, const std::string &str_std_in)
Execute a command which returns JSON, and parse the result.
Definition: run_command.cpp:18
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1162