From 3374ddd2a60a5f92b0cc2eb79ea2fd0de5ecbd88 Mon Sep 17 00:00:00 2001 From: Rusty Russell Date: Fri, 22 Jan 2016 06:41:47 +1030 Subject: [PATCH] bitcoin: use a length arg to bitcoin_tx_from_hex Our json parser doesn't use nul-terminated strings. Signed-off-by: Rusty Russell --- bitcoin/tx.c | 20 ++++++++++++++------ bitcoin/tx.h | 3 ++- test-cli/tx_from_file.c | 2 +- 3 files changed, 17 insertions(+), 8 deletions(-) diff --git a/bitcoin/tx.c b/bitcoin/tx.c index 56e8a6856..c14995f79 100644 --- a/bitcoin/tx.c +++ b/bitcoin/tx.c @@ -432,7 +432,8 @@ static struct bitcoin_tx *pull_bitcoin_tx(const tal_t *ctx, return tx; } -struct bitcoin_tx *bitcoin_tx_from_hex(const tal_t *ctx, const char *hex) +struct bitcoin_tx *bitcoin_tx_from_hex(const tal_t *ctx, const char *hex, + size_t hexlen) { char *end; u8 *linear_tx; @@ -440,10 +441,10 @@ struct bitcoin_tx *bitcoin_tx_from_hex(const tal_t *ctx, const char *hex) struct bitcoin_tx *tx; size_t len; - end = strchr(hex, ':'); + end = memchr(hex, ':', hexlen); if (!end) { - end = cast_const(char *, hex) + strlen(hex); - if (strends(hex, "\n")) + end = cast_const(char *, hex) + hexlen; + if (hexlen > 0 && hex[hexlen-1] == '\n') end--; } @@ -460,10 +461,17 @@ struct bitcoin_tx *bitcoin_tx_from_hex(const tal_t *ctx, const char *hex) for (len = 0; len < tx->input_count; len++) { if (*end != ':') break; - tx->input[len].input_amount = strtoull(end + 1, &end, 10); + + tx->input[len].input_amount = 0; + end++; + while (end < hex + hexlen && cisdigit(*end)) { + tx->input[len].input_amount *= 10; + tx->input[len].input_amount += *end - '0'; + end++; + } } if (len == tx->input_count) { - if (*end != '\0' && *end != '\n') + if (end != hex + hexlen && *end != '\n') goto fail_free_tx; } else { /* Input amounts are compulsory for alpha, to generate sigs */ diff --git a/bitcoin/tx.h b/bitcoin/tx.h index 59563a89b..7ac8815d0 100644 --- a/bitcoin/tx.h +++ b/bitcoin/tx.h @@ -56,7 +56,8 @@ struct bitcoin_tx *bitcoin_tx(const tal_t *ctx, varint_t input_count, /* This takes a raw bitcoin tx in hex, with [:<64-bit-satoshi>] appended * for each input (required for -DALPHA). */ -struct bitcoin_tx *bitcoin_tx_from_hex(const tal_t *ctx, const char *hex); +struct bitcoin_tx *bitcoin_tx_from_hex(const tal_t *ctx, const char *hex, + size_t hexlen); bool bitcoin_tx_write(int fd, const struct bitcoin_tx *tx); diff --git a/test-cli/tx_from_file.c b/test-cli/tx_from_file.c index 6c64c56e1..6b387e4b6 100644 --- a/test-cli/tx_from_file.c +++ b/test-cli/tx_from_file.c @@ -13,7 +13,7 @@ struct bitcoin_tx *bitcoin_tx_from_file(const tal_t *ctx, const char *filename) if (!hex) err(1, "Opening %s", filename); - tx = bitcoin_tx_from_hex(ctx, hex); + tx = bitcoin_tx_from_hex(ctx, hex, strlen(hex)); if (!tx) err(1, "Failed to decode tx '%s'", hex); tal_free(hex);