serialize amounts as string instead of an object

This commit is contained in:
Florian Dold 2018-01-29 19:26:10 +01:00
parent afe945167a
commit d126b16624
No known key found for this signature in database
GPG Key ID: D2E4F00F29D02A4B
2 changed files with 33 additions and 18 deletions

View File

@ -35,25 +35,15 @@
json_t * json_t *
TALER_JSON_from_amount (const struct TALER_Amount *amount) TALER_JSON_from_amount (const struct TALER_Amount *amount)
{ {
json_t *j; char *amount_str = TALER_amount_to_string (amount);
GNUNET_assert (NULL != amount_str);
if ( (amount->value != (uint64_t) ((json_int_t) amount->value)) ||
(0 > ((json_int_t) amount->value)) )
{ {
/* Theoretically, json_int_t can be a 32-bit "long", or we might json_t *j = json_string (amount_str);
have a 64-bit value which converted to a 63-bit signed long GNUNET_free (amount_str);
long causes problems here. So we check. Note that depending
on the platform, the compiler may be able to statically tell
that at least the first check is always false. */
GNUNET_break (0);
return NULL;
}
j = json_pack ("{s:s, s:I, s:I}",
"currency", amount->currency,
"value", (json_int_t) amount->value,
"fraction", (json_int_t) amount->fraction);
GNUNET_assert (NULL != j);
return j; return j;
}
} }
@ -93,6 +83,20 @@ parse_amount (void *cls,
json_int_t fraction; json_int_t fraction;
const char *currency; const char *currency;
if (json_is_string (root))
{
if (GNUNET_OK !=
TALER_string_to_amount (json_string_value (root), r_amount))
{
GNUNET_break_op (0);
return GNUNET_SYSERR;
}
return GNUNET_OK;
}
/* Also allow the legacy { value, fraction, currency} format.
This might be removed in the future. */
memset (r_amount, memset (r_amount,
0, 0,
sizeof (struct TALER_Amount)); sizeof (struct TALER_Amount));
@ -179,6 +183,17 @@ parse_amount_nbo (void *cls,
json_int_t fraction; json_int_t fraction;
const char *currency; const char *currency;
if (json_is_string (root))
{
if (GNUNET_OK !=
TALER_string_to_amount_nbo (json_string_value (root), r_amount))
{
GNUNET_break_op (0);
return GNUNET_SYSERR;
}
return GNUNET_OK;
}
memset (&amount, memset (&amount,
0, 0,
sizeof (struct TALER_Amount)); sizeof (struct TALER_Amount));

View File

@ -36,14 +36,14 @@ test_amount ()
struct TALER_Amount a1; struct TALER_Amount a1;
struct TALER_Amount a2; struct TALER_Amount a2;
struct GNUNET_JSON_Specification spec[] = { struct GNUNET_JSON_Specification spec[] = {
TALER_JSON_spec_amount (NULL, &a2), TALER_JSON_spec_amount ("amount", &a2),
GNUNET_JSON_spec_end() GNUNET_JSON_spec_end()
}; };
GNUNET_assert (GNUNET_OK == GNUNET_assert (GNUNET_OK ==
TALER_string_to_amount ("EUR:4.3", TALER_string_to_amount ("EUR:4.3",
&a1)); &a1));
j = TALER_JSON_from_amount (&a1); j = json_pack("{s:o}", "amount", TALER_JSON_from_amount (&a1));
GNUNET_assert (NULL != j); GNUNET_assert (NULL != j);
GNUNET_assert (GNUNET_OK == GNUNET_assert (GNUNET_OK ==
GNUNET_JSON_parse (j, spec, GNUNET_JSON_parse (j, spec,