From 725512fb0391905355f7452b2abf0503608a1870 Mon Sep 17 00:00:00 2001 From: Rusty Russell Date: Fri, 22 Jan 2016 06:41:48 +1030 Subject: [PATCH] json: parse bitcoind-style bitcoin amount. Always of form d*.dddddddd; we turn that into satoshis, because we're sane. Signed-off-by: Rusty Russell --- daemon/json.c | 28 ++++++++++++++++++++++++++++ daemon/json.h | 4 ++++ 2 files changed, 32 insertions(+) diff --git a/daemon/json.c b/daemon/json.c index 1991ed0c0..f6c3d75a8 100644 --- a/daemon/json.c +++ b/daemon/json.c @@ -78,6 +78,34 @@ bool json_tok_number(const char *buffer, const jsmntok_t *tok, return true; } +bool json_tok_bitcoin_amount(const char *buffer, const jsmntok_t *tok, + uint64_t *satoshi) +{ + char *end; + unsigned long btc, sat; + + btc = strtoul(buffer + tok->start, &end, 0); + if (btc == ULONG_MAX && errno == ERANGE) + return false; + if (end != buffer + tok->end) { + /* Expect always 8 decimal places. */ + if (*end != '.' || buffer + tok->start - end != 9) + return false; + sat = strtoul(end+1, &end, 0); + if (sat == ULONG_MAX && errno == ERANGE) + return false; + if (end != buffer + tok->end) + return false; + } else + sat = 0; + + *satoshi = btc * (uint64_t)100000000 + sat; + if (*satoshi != btc * (uint64_t)100000000 + sat) + return false; + + return true; +} + bool json_tok_is_null(const char *buffer, const jsmntok_t *tok) { if (tok->type != JSMN_PRIMITIVE) diff --git a/daemon/json.h b/daemon/json.h index fc990ea1c..68347d68a 100644 --- a/daemon/json.h +++ b/daemon/json.h @@ -28,6 +28,10 @@ bool json_tok_number(const char *buffer, const jsmntok_t *tok, bool json_tok_u64(const char *buffer, const jsmntok_t *tok, uint64_t *num); +/* Extract satoshis from this (may be a string, or a decimal number literal) */ +bool json_tok_bitcoin_amount(const char *buffer, const jsmntok_t *tok, + uint64_t *satoshi); + /* Is this the null primitive? */ bool json_tok_is_null(const char *buffer, const jsmntok_t *tok);