json: Add a helper to decode a hex-encoded value from JSON

Signed-off-by: Christian Decker <decker.christian@gmail.com>
This commit is contained in:
Christian Decker 2019-01-09 16:06:34 +01:00 committed by Rusty Russell
parent 05ec56a968
commit ed356dae62
2 changed files with 27 additions and 0 deletions

View File

@ -128,6 +128,26 @@ bool json_to_bool(const char *buffer, const jsmntok_t *tok, bool *b)
return false;
}
u8 *json_tok_bin_from_hex(const tal_t *ctx, const char *buffer, const jsmntok_t *tok)
{
u8 *result;
size_t hexlen, rawlen;
hexlen = tok->end - tok->start;
rawlen = hex_data_size(hexlen);
result = tal_arr(ctx, u8, rawlen);
if (!hex_decode(buffer + tok->start, hexlen, result, rawlen))
return tal_free(result);
return result;
}
bool json_to_preimage(const char *buffer, const jsmntok_t *tok, struct preimage *preimage)
{
size_t hexlen = tok->end - tok->start;
return hex_decode(buffer + tok->start, hexlen, preimage->r, sizeof(preimage->r));
}
bool json_tok_is_num(const char *buffer, const jsmntok_t *tok)
{
if (tok->type != JSMN_PRIMITIVE)

View File

@ -1,6 +1,7 @@
#ifndef LIGHTNING_COMMON_JSON_H
#define LIGHTNING_COMMON_JSON_H
#include "config.h"
#include <bitcoin/preimage.h>
#include <ccan/tal/tal.h>
#include <stdbool.h>
#include <stdint.h>
@ -21,6 +22,12 @@ bool json_tok_streq(const char *buffer, const jsmntok_t *tok, const char *str);
/* Allocate a tal string copy */
char *json_strdup(const tal_t *ctx, const char *buffer, const jsmntok_t *tok);
/* Decode a hex-encoded binary */
u8 *json_tok_bin_from_hex(const tal_t *ctx, const char *buffer, const jsmntok_t *tok);
/* Decode a hex-encoded payment preimage */
bool json_to_preimage(const char *buffer, const jsmntok_t *tok, struct preimage *preimage);
/* Extract number from this (may be a string, or a number literal) */
bool json_to_number(const char *buffer, const jsmntok_t *tok,
unsigned int *num);