From fb14452c6cadb8d977c405dddb0a94115250d7c4 Mon Sep 17 00:00:00 2001 From: Jeff Garzik Date: Mon, 18 Aug 2014 23:14:29 -0400 Subject: [PATCH] bitcoin-tx: Accept input via stdin. Add input handling to tests. --- src/bitcoin-tx.cpp | 28 ++++++++++++++++++++++++++-- src/test/bctest.py | 12 ++++++++++-- src/test/data/bitcoin-util-test.json | 4 ++++ 3 files changed, 40 insertions(+), 4 deletions(-) diff --git a/src/bitcoin-tx.cpp b/src/bitcoin-tx.cpp index ffe87298f..6cd2768d7 100644 --- a/src/bitcoin-tx.cpp +++ b/src/bitcoin-tx.cpp @@ -13,6 +13,7 @@ #include #include +#include using namespace std; using namespace boost::assign; @@ -501,13 +502,34 @@ static void OutputTx(const CTransaction& tx) OutputTxHex(tx); } +static string readStdin() +{ + char buf[4096]; + string ret; + + while (!feof(stdin)) { + size_t bread = fread(buf, 1, sizeof(buf), stdin); + ret.append(buf, bread); + if (bread < sizeof(buf)) + break; + } + + if (ferror(stdin)) + throw runtime_error("error reading stdin"); + + boost::algorithm::trim_right(ret); + + return ret; +} + static int CommandLineRawTx(int argc, char* argv[]) { string strPrint; int nRet = 0; try { - // Skip switches - while (argc > 1 && IsSwitchChar(argv[1][0])) { + // Skip switches; Permit common stdin convention "-" + while (argc > 1 && IsSwitchChar(argv[1][0]) && + (argv[1][1] != 0)) { argc--; argv++; } @@ -522,6 +544,8 @@ static int CommandLineRawTx(int argc, char* argv[]) // param: hex-encoded bitcoin transaction string strHexTx(argv[1]); + if (strHexTx == "-") // "-" implies standard input + strHexTx = readStdin(); if (!DecodeHexTx(txDecodeTmp, strHexTx)) throw runtime_error("invalid transaction encoding"); diff --git a/src/test/bctest.py b/src/test/bctest.py index 3b17acb75..b12647908 100644 --- a/src/test/bctest.py +++ b/src/test/bctest.py @@ -9,12 +9,20 @@ import sys def bctest(testDir, testObj): execargs = testObj['exec'] + + stdinCfg = None + inputData = None + if "input" in testObj: + filename = testDir + "/" + testObj['input'] + inputData = open(filename).read() + stdinCfg = subprocess.PIPE + outputFn = testObj['output_cmp'] outputData = open(testDir + "/" + outputFn).read() - proc = subprocess.Popen(execargs, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + proc = subprocess.Popen(execargs, stdin=stdinCfg, stdout=subprocess.PIPE, stderr=subprocess.PIPE) try: - outs = proc.communicate() + outs = proc.communicate(input=inputData) except OSError: print("OSError, Failed to execute " + execargs[0]) sys.exit(1) diff --git a/src/test/data/bitcoin-util-test.json b/src/test/data/bitcoin-util-test.json index af29fd75a..16bcb4489 100644 --- a/src/test/data/bitcoin-util-test.json +++ b/src/test/data/bitcoin-util-test.json @@ -1,5 +1,9 @@ [ { "exec": ["./bitcoin-tx", "-create"], "output_cmp": "blanktx.hex" + }, + { "exec": ["./bitcoin-tx", "-"], + "input": "blanktx.hex", + "output_cmp": "blanktx.hex" } ]