Byte length of the run of TLV records whose type is in [minfield, maxfield], * storing its offset into tlvstream in *startp. TLV records are ordered by * type, so the wanted records are contiguous: we track two byte offsets into * the stream, `start` (the first record at or above minfield) and `end` (just * past the last record at or below maxfield), and return end - start. * * Offsets, not
| 958 | * Offsets, not pointers: a pointer past the end of a range that was never |
| 959 | * entered would underflow to a near-SIZE_MAX length, which callers hash. */ |
| 960 | size_t tlv_span(const u8 *tlvstream, u64 minfield, u64 maxfield, |
| 961 | size_t *startp) |
| 962 | { |
| 963 | const u8 *cursor = tlvstream; |
| 964 | size_t tlvlen = tal_bytelen(tlvstream); |
| 965 | size_t start, end; |
| 966 | /* Distinguishes "start is offset 0" from "no in-range field seen". */ |
| 967 | bool have_start = false; |
| 968 | |
| 969 | start = end = 0; |
| 970 | while (tlvlen) { |
| 971 | size_t before = cursor - tlvstream; |
| 972 | bigsize_t type = fromwire_bigsize(&cursor, &tlvlen); |
| 973 | bigsize_t len = fromwire_bigsize(&cursor, &tlvlen); |
| 974 | /* Truncated header: stop, keeping the span so far. */ |
| 975 | if (!cursor) |
| 976 | break; |
| 977 | if (type >= minfield && !have_start) { |
| 978 | start = before; |
| 979 | have_start = true; |
| 980 | } |
| 981 | /* Past the range: later records are all higher, so we're done. */ |
| 982 | if (type > maxfield) |
| 983 | break; |
| 984 | fromwire_pad(&cursor, &tlvlen, len); |
| 985 | /* Truncated value: this record does not count. */ |
| 986 | if (!cursor) |
| 987 | break; |
| 988 | end = cursor - tlvstream; |
| 989 | } |
| 990 | /* No in-range field, or the range opened only after the last record we |
| 991 | * accepted: collapse to an empty span at end rather than a bogus length. */ |
| 992 | if (!have_start || end < start) |
| 993 | start = end; |
| 994 | |
| 995 | if (startp) |
| 996 | *startp = start; |
| 997 | return end - start; |
| 998 | } |
| 999 | |
| 1000 | static void calc_offer(const u8 *tlvstream, struct sha256 *id) |
| 1001 | { |