diff --git a/wire/fromwire.c b/wire/fromwire.c index b7d5a6ad1..edcda6ae3 100644 --- a/wire/fromwire.c +++ b/wire/fromwire.c @@ -101,6 +101,27 @@ bool fromwire_bool(const u8 **cursor, size_t *max) return ret; } +u64 fromwire_var_int(const u8 **cursor, size_t *max) +{ + if (*max < 1) { + fromwire_fail(cursor, max); + return 0; + } + + u8 flag = fromwire_u8(cursor, max); + + switch(flag) { + case 0xff: + return fromwire_u64(cursor, max); + case 0xfe: + return (u64)fromwire_u32(cursor, max); + case 0xfd: + return (u64)fromwire_u16(cursor, max); + default: + return (u64)flag; + } +} + void fromwire_pubkey(const u8 **cursor, size_t *max, struct pubkey *pubkey) { u8 der[PUBKEY_DER_LEN]; diff --git a/wire/towire.c b/wire/towire.c index 35bcb6bcd..2f36d5f5c 100644 --- a/wire/towire.c +++ b/wire/towire.c @@ -54,6 +54,22 @@ void towire_bool(u8 **pptr, bool v) towire(pptr, &val, sizeof(val)); } +void towire_var_int(u8 **pptr, const u64 val) +{ + if (val < 0xfd) { + towire_u8(pptr, (u8)val); + } else if (val <= 0xffff) { + towire_u8(pptr, 0xfd); + towire_u16(pptr, (u16)val); + } else if (val <= 0xffffffff) { + towire_u8(pptr, 0xfe); + towire_u32(pptr, (u32)val); + } else { + towire_u8(pptr, 0xff); + towire_u64(pptr, val); + } +} + void towire_pubkey(u8 **pptr, const struct pubkey *pubkey) { u8 output[PUBKEY_DER_LEN]; diff --git a/wire/wire.h b/wire/wire.h index c72c350a2..69a8a209d 100644 --- a/wire/wire.h +++ b/wire/wire.h @@ -67,6 +67,7 @@ void towire_u64(u8 **pptr, u64 v); void towire_double(u8 **pptr, const double *v); void towire_pad(u8 **pptr, size_t num); void towire_bool(u8 **pptr, bool v); +void towire_var_int(u8 **pptr, const u64 val); void towire_u8_array(u8 **pptr, const u8 *arr, size_t num); @@ -83,6 +84,7 @@ u32 fromwire_u32(const u8 **cursor, size_t *max); u64 fromwire_u64(const u8 **cursor, size_t *max); void fromwire_double(const u8 **cursor, size_t *max, double *v); bool fromwire_bool(const u8 **cursor, size_t *max); +u64 fromwire_var_int(const u8 **cursor, size_t *max); void fromwire_secret(const u8 **cursor, size_t *max, struct secret *secret); void fromwire_privkey(const u8 **cursor, size_t *max, struct privkey *privkey); void fromwire_pubkey(const u8 **cursor, size_t *max, struct pubkey *pubkey);