Use dedicated type for error codes

Before this patch we used `int` for error codes. The problem with
`int` is that we try to pass it to/from wire and the size of `int` is
not defined by the standard. So a sender with 4-byte `int` would write
4 bytes to the wire and a receiver with 2-byte `int` (for example) would
read just 2 bytes from the wire.

To resolve this:

* Introduce an error code type with a known size:
  `typedef s32 errcode_t`.

* Change all error code macros to constants of type `errcode_t`.
  Constants also play better with gdb - it would visualize the name of
  the constant instead of the numeric value.

* Change all functions that take error codes to take the new type
  `errcode_t` instead of `int`.

* Introduce towire / fromwire functions to send / receive the newly added
  type `errcode_t` and use it instead of `towire_int()`.

In addition:

* Remove the now unneeded `towire_int()`.

* Replace a hardcoded error code `-2` with a new constant
  `INVOICE_EXPIRED_DURING_WAIT` (903).

Changelog-Changed: The waitinvoice command would now return error code 903 to designate that the invoice expired during wait, instead of the previous -2
This commit is contained in:
Vasil Dimov
2020-01-26 13:52:29 +01:00
committed by ZmnSCPxj, ZmnSCPxj jxPCSmnZ
parent 295ca2a436
commit 55173a56b7
29 changed files with 187 additions and 108 deletions

View File

@@ -65,6 +65,30 @@ bool json_to_u64(const char *buffer, const jsmntok_t *tok,
return true;
}
bool json_to_s64(const char *buffer, const jsmntok_t *tok, s64 *num)
{
char *end;
long long l;
l = strtoll(buffer + tok->start, &end, 0);
if (end != buffer + tok->end)
return false;
BUILD_ASSERT(sizeof(l) >= sizeof(*num));
*num = l;
/* Check for overflow/underflow */
if ((l == LONG_MAX || l == LONG_MIN) && errno == ERANGE)
return false;
/* Check if the number did not fit in `s64` (in case `long long`
is a bigger type). */
if (*num != l)
return false;
return true;
}
bool json_to_double(const char *buffer, const jsmntok_t *tok, double *num)
{
char *end;
@@ -122,22 +146,29 @@ bool json_to_u32(const char *buffer, const jsmntok_t *tok,
bool json_to_int(const char *buffer, const jsmntok_t *tok, int *num)
{
char *end;
long l;
s64 tmp;
l = strtol(buffer + tok->start, &end, 0);
if (end != buffer + tok->end)
if (!json_to_s64(buffer, tok, &tmp))
return false;
*num = tmp;
/* Just in case it doesn't fit. */
if (*num != tmp)
return false;
BUILD_ASSERT(sizeof(l) >= sizeof(*num));
*num = l;
return true;
}
/* Check for overflow/underflow */
if ((l == LONG_MAX || l == LONG_MIN) && errno == ERANGE)
bool json_to_errcode(const char *buffer, const jsmntok_t *tok, errcode_t *errcode)
{
s64 tmp;
if (!json_to_s64(buffer, tok, &tmp))
return false;
*errcode = tmp;
/* Check for truncation */
if (*num != l)
/* Just in case it doesn't fit. */
if (*errcode != tmp)
return false;
return true;