Skip to content

Commit

Permalink
json: Add a helper to decode a hex-encoded value from JSON
Browse files Browse the repository at this point in the history
Signed-off-by: Christian Decker <decker.christian@gmail.com>
  • Loading branch information
cdecker authored and rustyrussell committed Jan 17, 2019
1 parent 05ec56a commit ed356da
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
20 changes: 20 additions & 0 deletions common/json.c
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
7 changes: 7 additions & 0 deletions common/json.h
Original file line number Diff line number Diff line change
@@ -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>
Expand All @@ -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);
Expand Down

0 comments on commit ed356da

Please sign in to comment.