1 #include <bitcoin/address.h>
2 #include <bitcoin/script.h>
3 #include <ccan/array_size/array_size.h>
4 #include <ccan/tal/str/str.h>
5 #include <common/bech32.h>
6 #include <common/bech32_util.h>
7 #include <common/bolt11.h>
8 #include <common/features.h>
9 #include <errno.h>
10 #include <inttypes.h>
11 #include <lightningd/lightningd.h>
12 
13 struct multiplier {
14 	const char letter;
15 	/* We can't represent p postfix to msat, so we multiply this by 10 */
16 	u64 m10;
17 };
18 
19 /* BOLT #11:
20  *
21  * The following `multiplier` letters are defined:
22  *
23  * * `m` (milli): multiply by 0.001
24  * * `u` (micro): multiply by 0.000001
25  * * `n` (nano): multiply by 0.000000001
26  * * `p` (pico): multiply by 0.000000000001
27  */
28 static struct multiplier multipliers[] = {
29 	{ 'm', 10 * MSAT_PER_BTC / 1000 },
30 	{ 'u', 10 * MSAT_PER_BTC / 1000000 },
31 	{ 'n', 10 * MSAT_PER_BTC / 1000000000 },
32 	{ 'p', 10 * MSAT_PER_BTC / 1000000000000ULL }
33 };
34 
35 /* If pad is false, we discard any bits which don't fit in the last byte.
36  * Otherwise we add an extra byte */
pull_bits(struct hash_u5 * hu5,u5 ** data,size_t * data_len,void * dst,size_t nbits,bool pad)37 static bool pull_bits(struct hash_u5 *hu5,
38 		      u5 **data, size_t *data_len, void *dst, size_t nbits,
39 		      bool pad)
40 {
41 	size_t n5 = nbits / 5;
42 	size_t len = 0;
43 
44 	if (nbits % 5)
45 		n5++;
46 
47 	if (*data_len < n5)
48 		return false;
49 	if (!bech32_convert_bits(dst, &len, 8, *data, n5, 5, pad))
50 		return false;
51 	if (hu5)
52 		hash_u5(hu5, *data, n5);
53 	*data += n5;
54 	*data_len -= n5;
55 
56 	return true;
57 }
58 
59 /* For pulling fields where we should have checked it will succeed already. */
60 #ifndef NDEBUG
61 #define pull_bits_certain(hu5, data, data_len, dst, nbits, pad)	     \
62 	assert(pull_bits((hu5), (data), (data_len), (dst), (nbits), (pad)))
63 #else
64 #define pull_bits_certain pull_bits
65 #endif
66 
67 /* Helper for pulling a variable-length big-endian int. */
pull_uint(struct hash_u5 * hu5,u5 ** data,size_t * data_len,u64 * val,size_t databits)68 static bool pull_uint(struct hash_u5 *hu5,
69 		      u5 **data, size_t *data_len,
70 		      u64 *val, size_t databits)
71 {
72 	be64 be_val;
73 
74 	/* Too big. */
75 	if (databits > sizeof(be_val) * CHAR_BIT)
76 		return false;
77 	if (!pull_bits(hu5, data, data_len, &be_val, databits, true))
78 		return false;
79 	*val = be64_to_cpu(be_val) >> (sizeof(be_val) * CHAR_BIT - databits);
80 	return true;
81 }
82 
num_u8(size_t num_u5)83 static size_t num_u8(size_t num_u5)
84 {
85 	return (num_u5 * 5 + 4) / 8;
86 }
87 
88 /* Frees bolt11, returns NULL. */
89 static struct bolt11 *decode_fail(struct bolt11 *b11, char **fail,
90 				  const char *fmt, ...)
91 	PRINTF_FMT(3,4);
92 
decode_fail(struct bolt11 * b11,char ** fail,const char * fmt,...)93 static struct bolt11 *decode_fail(struct bolt11 *b11, char **fail,
94 				  const char *fmt, ...)
95 {
96 	va_list ap;
97 
98 	va_start(ap, fmt);
99 	*fail = tal_vfmt(tal_parent(b11), fmt, ap);
100 	va_end(ap);
101 	return tal_free(b11);
102 }
103 
104 /*
105  * These handle specific fields in the payment request; returning the problem
106  * if any, or NULL.
107  */
unknown_field(struct bolt11 * b11,struct hash_u5 * hu5,u5 ** data,size_t * data_len,u5 type,size_t length)108 static char *unknown_field(struct bolt11 *b11,
109 			   struct hash_u5 *hu5,
110 			   u5 **data, size_t *data_len,
111 			   u5 type, size_t length)
112 {
113 	struct bolt11_field *extra = tal(b11, struct bolt11_field);
114 	u8 u8data[num_u8(length)];
115 
116 	extra->tag = type;
117 	extra->data = tal_dup_arr(extra, u5, *data, length, 0);
118 	list_add_tail(&b11->extra_fields, &extra->list);
119 
120 	pull_bits_certain(hu5, data, data_len, u8data, length * 5, true);
121 	return NULL;
122 }
123 
124 /* BOLT #11:
125  *
126  * `p` (1): `data_length` 52.  256-bit SHA256 payment_hash.  Preimage of this
127  * provides proof of payment
128  */
decode_p(struct bolt11 * b11,struct hash_u5 * hu5,u5 ** data,size_t * data_len,size_t data_length,bool * have_p)129 static void decode_p(struct bolt11 *b11,
130 		     struct hash_u5 *hu5,
131 		     u5 **data, size_t *data_len,
132 		     size_t data_length, bool *have_p)
133 {
134 	/* BOLT #11:
135 	 *
136 	 * A payer... SHOULD use the first `p` field that it did NOT
137 	 * skip as the payment hash.
138 	 */
139 	if (*have_p) {
140 		unknown_field(b11, hu5, data, data_len, 'p', data_length);
141 		return;
142 	}
143 
144 	/* BOLT #11:
145 	 *
146 	 * A reader... MUST skip over unknown fields, OR an `f` field
147 	 * with unknown `version`, OR `p`, `h`, `s` or `n` fields that do
148 	 * NOT have `data_length`s of 52, 52, 52 or 53, respectively.
149 	*/
150 	if (data_length != 52) {
151 		unknown_field(b11, hu5, data, data_len, 'p', data_length);
152 		return;
153 	}
154 
155 	pull_bits_certain(hu5, data, data_len, &b11->payment_hash, 256, false);
156 	*have_p = true;
157 }
158 
159 /* BOLT #11:
160  *
161  * `d` (13): `data_length` variable.  Short description of purpose of payment
162  * (UTF-8), e.g. '1 cup of coffee' or 'ナンセンス 1杯'
163  */
decode_d(struct bolt11 * b11,struct hash_u5 * hu5,u5 ** data,size_t * data_len,size_t data_length,bool * have_d)164 static char *decode_d(struct bolt11 *b11,
165 		      struct hash_u5 *hu5,
166 		      u5 **data, size_t *data_len,
167 		      size_t data_length, bool *have_d)
168 {
169 	u8 *desc;
170 	if (*have_d)
171 		return unknown_field(b11, hu5, data, data_len, 'd', data_length);
172 
173 	desc = tal_arr(NULL, u8, data_length * 5 / 8);
174 	pull_bits_certain(hu5, data, data_len, desc, data_length*5, false);
175 
176 	*have_d = true;
177 	b11->description = utf8_str(b11, take(desc), tal_bytelen(desc));
178 	if (b11->description)
179 		return NULL;
180 
181 	return tal_fmt(b11, "d: invalid utf8");
182 }
183 
184 /* BOLT #11:
185  *
186  * `h` (23): `data_length` 52.  256-bit description of purpose of payment
187  * (SHA256).  This is used to commit to an associated description that is over
188  * 639 bytes, but the transport mechanism for the description in that case is
189  * transport specific and not defined here.
190  */
decode_h(struct bolt11 * b11,struct hash_u5 * hu5,u5 ** data,size_t * data_len,size_t data_length,bool * have_h)191 static void decode_h(struct bolt11 *b11,
192 		     struct hash_u5 *hu5,
193 		     u5 **data, size_t *data_len,
194 		     size_t data_length, bool *have_h)
195 {
196 	if (*have_h) {
197 		unknown_field(b11, hu5, data, data_len, 'h', data_length);
198 		return;
199 	}
200 
201 	/* BOLT #11:
202 	 *
203 	 * A reader... MUST skip over unknown fields, OR an `f` field
204 	 * with unknown `version`, OR `p`, `h`, `s` or `n` fields that do
205 	 * NOT have `data_length`s of 52, 52, 52 or 53, respectively. */
206 	if (data_length != 52) {
207 		unknown_field(b11, hu5, data, data_len, 'h', data_length);
208 		return;
209 	}
210 
211 	b11->description_hash = tal(b11, struct sha256);
212 	pull_bits_certain(hu5, data, data_len, b11->description_hash, 256,
213 			  false);
214 	*have_h = true;
215 }
216 
217 /* BOLT #11:
218  *
219  * `x` (6): `data_length` variable.  `expiry` time in seconds
220  * (big-endian). Default is 3600 (1 hour) if not specified.
221  */
222 #define DEFAULT_X 3600
decode_x(struct bolt11 * b11,struct hash_u5 * hu5,u5 ** data,size_t * data_len,size_t data_length,const bool * have_x)223 static char *decode_x(struct bolt11 *b11,
224 		      struct hash_u5 *hu5,
225 		      u5 **data, size_t *data_len,
226 		      size_t data_length, const bool *have_x)
227 {
228 	if (*have_x)
229 		return unknown_field(b11, hu5, data, data_len, 'x',
230 				     data_length);
231 
232 	/* FIXME: Put upper limit in bolt 11 */
233 	if (!pull_uint(hu5, data, data_len, &b11->expiry, data_length * 5))
234 		return tal_fmt(b11, "x: length %zu chars is excessive",
235 			       *data_len);
236 	return NULL;
237 }
238 
239 /* BOLT #11:
240  *
241  * `c` (24): `data_length` variable.  `min_final_cltv_expiry` to use for the
242  * last HTLC in the route. Default is 18 if not specified.
243  */
decode_c(struct bolt11 * b11,struct hash_u5 * hu5,u5 ** data,size_t * data_len,size_t data_length,const bool * have_c)244 static char *decode_c(struct bolt11 *b11,
245 		      struct hash_u5 *hu5,
246 		      u5 **data, size_t *data_len,
247 		      size_t data_length, const bool *have_c)
248 {
249 	u64 c;
250 	if (*have_c)
251 		return unknown_field(b11, hu5, data, data_len, 'c',
252 				     data_length);
253 
254 	/* FIXME: Put upper limit in bolt 11 */
255 	if (!pull_uint(hu5, data, data_len, &c, data_length * 5))
256 		return tal_fmt(b11, "c: length %zu chars is excessive",
257 			       *data_len);
258 	b11->min_final_cltv_expiry = c;
259 	/* Can overflow, since c is 64 bits but value must be < 32 bits */
260 	if (b11->min_final_cltv_expiry != c)
261 		return tal_fmt(b11, "c: %"PRIu64" is too large", c);
262 
263 	return NULL;
264 }
265 
decode_n(struct bolt11 * b11,struct hash_u5 * hu5,u5 ** data,size_t * data_len,size_t data_length,bool * have_n)266 static char *decode_n(struct bolt11 *b11,
267 		      struct hash_u5 *hu5,
268 		      u5 **data, size_t *data_len,
269 		      size_t data_length, bool *have_n)
270 {
271 	if (*have_n)
272 		return unknown_field(b11, hu5, data, data_len, 'n',
273 				     data_length);
274 
275 	/* BOLT #11:
276 	 *
277 	 * A reader... MUST skip over unknown fields, OR an `f` field
278 	 * with unknown `version`, OR `p`, `h`, `s` or `n` fields that do
279 	 * NOT have `data_length`s of 52, 52, 52 or 53, respectively. */
280 	if (data_length != 53)
281 		return unknown_field(b11, hu5, data, data_len, 'n',
282 				     data_length);
283 
284 	pull_bits_certain(hu5, data, data_len, &b11->receiver_id.k,
285 			  data_length * 5, false);
286 	if (!node_id_valid(&b11->receiver_id))
287 		return tal_fmt(b11, "n: invalid pubkey %s",
288 			       node_id_to_hexstr(tmpctx, &b11->receiver_id));
289 
290 	*have_n = true;
291 	return NULL;
292 }
293 
294 /* BOLT #11:
295  *
296  * * `s` (16): `data_length` 52. This 256-bit secret prevents
297  *    forwarding nodes from probing the payment recipient.
298  */
decode_s(struct bolt11 * b11,struct hash_u5 * hu5,u5 ** data,size_t * data_len,size_t data_length,bool * have_s)299 static char *decode_s(struct bolt11 *b11,
300 		      struct hash_u5 *hu5,
301 		      u5 **data, size_t *data_len,
302 		      size_t data_length,
303 		      bool *have_s)
304 {
305 	if (*have_s)
306 		return unknown_field(b11, hu5, data, data_len, 's',
307 				     data_length);
308 
309 	/* BOLT #11:
310 	 *
311 	 * A reader... MUST skip over unknown fields, OR an `f` field
312 	 * with unknown `version`, OR `p`, `h`, `s` or `n` fields that do
313 	 * NOT have `data_length`s of 52, 52, 52 or 53, respectively. */
314 	if (data_length != 52)
315 		return unknown_field(b11, hu5, data, data_len, 's',
316 				     data_length);
317 
318 	b11->payment_secret = tal(b11, struct secret);
319 	pull_bits_certain(hu5, data, data_len, b11->payment_secret, 256,
320 			  false);
321 	*have_s = true;
322 	return NULL;
323 }
324 
325 /* BOLT #11:
326  *
327  * `f` (9): `data_length` variable, depending on version. Fallback
328  * on-chain address: for Bitcoin, this starts with a 5-bit `version`
329  * and contains a witness program or P2PKH or P2SH address.
330  */
decode_f(struct bolt11 * b11,struct hash_u5 * hu5,u5 ** data,size_t * data_len,size_t data_length)331 static char *decode_f(struct bolt11 *b11,
332 		      struct hash_u5 *hu5,
333 		      u5 **data, size_t *data_len,
334 		      size_t data_length)
335 {
336 	u64 version;
337 	u8 *fallback;
338 
339 	if (!pull_uint(hu5, data, data_len, &version, 5))
340 		return tal_fmt(b11, "f: data_length %zu short", data_length);
341 	data_length--;
342 
343 	/* BOLT #11:
344 	 *
345 	 * for Bitcoin payments... MUST set an `f` field to a valid
346 	 * witness version and program, OR to `17` followed by a
347 	 * public key hash, OR to `18` followed by a script hash.
348 	*/
349 	if (version == 17) {
350 		/* Pay to pubkey hash (P2PKH) */
351 		struct bitcoin_address pkhash;
352 		if (num_u8(data_length) != sizeof(pkhash))
353 			return tal_fmt(b11, "f: pkhash length %zu",
354 				       data_length);
355 
356 		pull_bits_certain(hu5, data, data_len, &pkhash, data_length*5,
357 				  false);
358 		fallback = scriptpubkey_p2pkh(b11, &pkhash);
359 	} else if (version == 18) {
360 		/* Pay to pubkey script hash (P2SH) */
361 		struct ripemd160 shash;
362 		if (num_u8(data_length) != sizeof(shash))
363 			return tal_fmt(b11, "f: p2sh length %zu",
364 				       data_length);
365 
366 		pull_bits_certain(hu5, data, data_len, &shash, data_length*5,
367 				  false);
368 		fallback = scriptpubkey_p2sh_hash(b11, &shash);
369 	} else if (version < 17) {
370 		u8 *f = tal_arr(b11, u8, data_length * 5 / 8);
371 		if (version == 0) {
372 			if (tal_count(f) != 20 && tal_count(f) != 32)
373 				return tal_fmt(b11,
374 					       "f: witness v0 bad length %zu",
375 					       data_length);
376 		}
377 		pull_bits_certain(hu5, data, data_len, f, data_length * 5,
378 				  false);
379 		fallback = scriptpubkey_witness_raw(b11, version,
380 						    f, tal_count(f));
381 		tal_free(f);
382 	} else {
383 		/* Restore version for unknown field! */
384 		(*data)--;
385 		(*data_len)++;
386 		data_length++;
387 		return unknown_field(b11, hu5, data, data_len, 'f',
388 				     data_length);
389 	}
390 
391 	if (b11->fallbacks == NULL)
392 		b11->fallbacks = tal_arr(b11, const u8 *, 1);
393 	else
394 		tal_resize(&b11->fallbacks, tal_count(b11->fallbacks) + 1);
395 
396 	b11->fallbacks[tal_count(b11->fallbacks)-1]
397 		= tal_steal(b11->fallbacks, fallback);
398 	return NULL;
399 }
400 
fromwire_route_info(const u8 ** cursor,size_t * max,struct route_info * route_info)401 static bool fromwire_route_info(const u8 **cursor, size_t *max,
402 				struct route_info *route_info)
403 {
404 	fromwire_node_id(cursor, max, &route_info->pubkey);
405 	fromwire_short_channel_id(cursor, max, &route_info->short_channel_id);
406 	route_info->fee_base_msat = fromwire_u32(cursor, max);
407 	route_info->fee_proportional_millionths = fromwire_u32(cursor, max);
408 	route_info->cltv_expiry_delta = fromwire_u16(cursor, max);
409 	return *cursor != NULL;
410 }
411 
towire_route_info(u8 ** pptr,const struct route_info * route_info)412 static void towire_route_info(u8 **pptr, const struct route_info *route_info)
413 {
414 	towire_node_id(pptr, &route_info->pubkey);
415 	towire_short_channel_id(pptr, &route_info->short_channel_id);
416 	towire_u32(pptr, route_info->fee_base_msat);
417 	towire_u32(pptr, route_info->fee_proportional_millionths);
418 	towire_u16(pptr, route_info->cltv_expiry_delta);
419 }
420 
421 /* BOLT #11:
422  *
423  * `r` (3): `data_length` variable.  One or more entries containing
424  * extra routing information for a private route; there may be more
425  * than one `r` field
426  *
427  *   * `pubkey` (264 bits)
428  *   * `short_channel_id` (64 bits)
429  *   * `fee_base_msat` (32 bits, big-endian)
430  *   * `fee_proportional_millionths` (32 bits, big-endian)
431  *   * `cltv_expiry_delta` (16 bits, big-endian)
432  */
decode_r(struct bolt11 * b11,struct hash_u5 * hu5,u5 ** data,size_t * data_len,size_t data_length)433 static char *decode_r(struct bolt11 *b11,
434 		      struct hash_u5 *hu5,
435 		      u5 **data, size_t *data_len,
436 		      size_t data_length)
437 {
438 	size_t rlen = data_length * 5 / 8;
439 	u8 *r8 = tal_arr(tmpctx, u8, rlen);
440 	size_t n = 0;
441 	struct route_info *r = tal_arr(tmpctx, struct route_info, n);
442 	const u8 *cursor = r8;
443 
444 	/* Route hops don't split in 5 bit boundaries, so convert whole thing */
445 	pull_bits_certain(hu5, data, data_len, r8, data_length * 5, false);
446 
447 	do {
448 		struct route_info ri;
449 		if (!fromwire_route_info(&cursor, &rlen, &ri)) {
450 			return tal_fmt(b11, "r: hop %zu truncated", n);
451 		}
452 		tal_arr_expand(&r, ri);
453 	} while (rlen);
454 
455 	/* Append route */
456 	tal_arr_expand(&b11->routes, tal_steal(b11, r));
457 	return NULL;
458 }
459 
shift_bitmap_down(u8 * bitmap,size_t bits)460 static void shift_bitmap_down(u8 *bitmap, size_t bits)
461 {
462 	u8 prev = 0;
463 	assert(bits < CHAR_BIT);
464 
465 	for (size_t i = 0; i < tal_bytelen(bitmap); i++) {
466 		/* Save top bits for next one */
467 		u8 v = bitmap[i];
468 		bitmap[i] = (prev | (v >> bits));
469 		prev = (v << (8 - bits));
470 	}
471 	assert(prev == 0);
472 }
473 
474 /* BOLT #11:
475  *
476  * `9` (5): `data_length` variable. One or more 5-bit values containing features
477  *  supported or required for receiving this payment.
478  *  See [Feature Bits](#feature-bits).
479  */
decode_9(struct bolt11 * b11,const struct feature_set * our_features,struct hash_u5 * hu5,u5 ** data,size_t * data_len,size_t data_length)480 static char *decode_9(struct bolt11 *b11,
481 		      const struct feature_set *our_features,
482 		      struct hash_u5 *hu5,
483 		      u5 **data, size_t *data_len,
484 		      size_t data_length)
485 {
486 	size_t flen = (data_length * 5 + 7) / 8;
487 	int badf;
488 
489 	b11->features = tal_arr(b11, u8, flen);
490 	pull_bits_certain(hu5, data, data_len, b11->features,
491 			  data_length * 5, true);
492 
493 	/* pull_bits pads with zero bits: we need to remove them. */
494 	shift_bitmap_down(b11->features,
495 			  flen * 8 - data_length * 5);
496 
497 	/* BOLT #11:
498 	 *
499 	 * - if the `9` field contains unknown _odd_ bits that are non-zero:
500 	 *   - MUST ignore the bit.
501 	 * - if the `9` field contains unknown _even_ bits that are non-zero:
502 	 *   - MUST fail the payment.
503 	 */
504 	/* We skip this check for the cli tool, which sets our_features to NULL */
505 	if (our_features) {
506 		badf = features_unsupported(our_features,
507 					    b11->features, BOLT11_FEATURE);
508 		if (badf != -1)
509 			return tal_fmt(b11, "9: unknown feature bit %i", badf);
510 	}
511 
512 	return NULL;
513 }
514 
new_bolt11(const tal_t * ctx,const struct amount_msat * msat TAKES)515 struct bolt11 *new_bolt11(const tal_t *ctx,
516 			  const struct amount_msat *msat TAKES)
517 {
518 	struct bolt11 *b11 = tal(ctx, struct bolt11);
519 
520 	list_head_init(&b11->extra_fields);
521 	b11->description = NULL;
522 	b11->description_hash = NULL;
523 	b11->fallbacks = NULL;
524 	b11->routes = NULL;
525 	b11->msat = NULL;
526 	b11->expiry = DEFAULT_X;
527 	b11->features = tal_arr(b11, u8, 0);
528 	/* BOLT #11:
529 	 *   - if the `c` field (`min_final_cltv_expiry`) is not provided:
530 	 *     - MUST use an expiry delta of at least 18 when making the payment
531 	 */
532 	b11->min_final_cltv_expiry = 18;
533 	b11->payment_secret = NULL;
534 
535 	if (msat)
536 		b11->msat = tal_dup(b11, struct amount_msat, msat);
537 	return b11;
538 }
539 
540 /* Extracts signature but does not check it. */
bolt11_decode_nosig(const tal_t * ctx,const char * str,const struct feature_set * our_features,const char * description,const struct chainparams * must_be_chain,struct sha256 * hash,u5 ** sig,bool * have_n,char ** fail)541 struct bolt11 *bolt11_decode_nosig(const tal_t *ctx, const char *str,
542 				   const struct feature_set *our_features,
543 				   const char *description,
544 				   const struct chainparams *must_be_chain,
545 				   struct sha256 *hash,
546 				   u5 **sig,
547 				   bool *have_n,
548 				   char **fail)
549 {
550 	char *hrp, *amountstr, *prefix;
551 	u5 *data;
552 	size_t data_len;
553 	struct bolt11 *b11 = new_bolt11(ctx, NULL);
554 	struct hash_u5 hu5;
555 	bool have_p = false, have_d = false, have_h = false,
556 		have_x = false, have_c = false, have_s = false;
557 
558 	*have_n = false;
559 	b11->routes = tal_arr(b11, struct route_info *, 0);
560 
561 	/* BOLT #11:
562 	 *
563 	 * If a URI scheme is desired, the current recommendation is to either
564 	 * use 'lightning:' as a prefix before the BOLT-11 encoding
565 	 */
566 	if (strstarts(str, "lightning:") || strstarts(str, "LIGHTNING:"))
567 		str += strlen("lightning:");
568 
569 	if (strlen(str) < 8)
570 		return decode_fail(b11, fail, "Bad bech32 string");
571 
572 	hrp = tal_arr(tmpctx, char, strlen(str) - 6);
573 	data = tal_arr(tmpctx, u5, strlen(str) - 8);
574 
575 	if (bech32_decode(hrp, data, &data_len, str, (size_t)-1)
576 	    != BECH32_ENCODING_BECH32)
577 		return decode_fail(b11, fail, "Bad bech32 string");
578 
579 	/* For signature checking at the end. */
580 	hash_u5_init(&hu5, hrp);
581 
582 	/* BOLT #11:
583 	 *
584 	 * The human-readable part of a Lightning invoice consists of two sections:
585 	 * 1. `prefix`: `ln` + BIP-0173 currency prefix (e.g. `lnbc` for Bitcoin mainnet,
586 	 *    `lntb` for Bitcoin testnet, `lntbs` for Bitcoin signet, and `lnbcrt` for Bitcoin regtest)
587 	 * 1. `amount`: optional number in that currency, followed by an optional
588 	 *    `multiplier` letter. The unit encoded here is the 'social' convention of a payment unit -- in the case of Bitcoin the unit is 'bitcoin' NOT satoshis.
589 	*/
590 	prefix = tal_strndup(tmpctx, hrp, strcspn(hrp, "0123456789"));
591 
592 	/* BOLT #11:
593 	 *
594 	 * A reader...if it does NOT understand the `prefix`... MUST fail the payment.
595 	 */
596 	if (!strstarts(prefix, "ln"))
597 		return decode_fail(b11, fail,
598 				   "Prefix '%s' does not start with ln", prefix);
599 
600 	/* Signet chose to use prefix 'tb', just like testnet.  So we tread
601 	 * carefully here: */
602 	if (must_be_chain) {
603 		if (streq(prefix + 2, must_be_chain->bip173_name))
604 			b11->chain = must_be_chain;
605 		else
606 			return decode_fail(b11, fail, "Prefix %s is not for %s",
607 					   prefix + 2,
608 					   must_be_chain->network_name);
609 	} else {
610 		b11->chain = chainparams_by_bip173(prefix + 2);
611 		if (!b11->chain)
612 			return decode_fail(b11, fail, "Unknown chain %s",
613 					   prefix + 2);
614 	}
615 
616 	/* BOLT #11:
617 	 *
618 	 *   - if the `amount` is empty:
619 	 * */
620 	amountstr = tal_strdup(tmpctx, hrp + strlen(prefix));
621 	if (streq(amountstr, "")) {
622 		/* BOLT #11:
623 		 *
624 		 * - SHOULD indicate to the payer that amount is unspecified.
625 		 */
626 		b11->msat = NULL;
627 	} else {
628 		u64 m10 = 10 * MSAT_PER_BTC; /* Pico satoshis in a Bitcoin */
629 		u64 amount;
630 		char *end;
631 
632 		/* Gather and trim multiplier */
633 		end = amountstr + strlen(amountstr)-1;
634 		for (size_t i = 0; i < ARRAY_SIZE(multipliers); i++) {
635 			if (*end == multipliers[i].letter) {
636 				m10 = multipliers[i].m10;
637 				*end = '\0';
638 				break;
639 			}
640 		}
641 
642 		/* BOLT #11:
643 		 *
644 		 * if `amount` contains a non-digit OR is followed by
645 		 * anything except a `multiplier` (see table above)... MUST fail the
646 		 * payment.
647 		 **/
648 		amount = strtoull(amountstr, &end, 10);
649 		if (amount == ULLONG_MAX && errno == ERANGE)
650 			return decode_fail(b11, fail,
651 					   "Invalid amount '%s'", amountstr);
652 		if (!*amountstr || *end)
653 			return decode_fail(b11, fail,
654 					   "Invalid amount postfix '%s'", end);
655 
656 		/* BOLT #11:
657 		 *
658 		 * if the `multiplier` is present...  MUST multiply
659 		 * `amount` by the `multiplier` value to derive the
660 		 * amount required for payment.
661 		*/
662 		b11->msat = tal(b11, struct amount_msat);
663 		/* BOLT #11:
664 		 *
665 		 * - if multiplier is `p` and the last decimal of `amount` is
666 		 *   not 0:
667 		 *    - MUST fail the payment.
668 		 */
669 		if (amount * m10 % 10 != 0)
670 			return decode_fail(b11, fail,
671 					   "Invalid sub-millisatoshi amount"
672 					   " '%sp'", amountstr);
673 
674 		*b11->msat = amount_msat(amount * m10 / 10);
675 	}
676 
677 	/* BOLT #11:
678 	 *
679 	 * The data part of a Lightning invoice consists of multiple sections:
680 	 *
681 	 * 1. `timestamp`: seconds-since-1970 (35 bits, big-endian)
682 	 * 1. zero or more tagged parts
683 	 * 1. `signature`: Bitcoin-style signature of above (520 bits)
684 	 */
685 	if (!pull_uint(&hu5, &data, &data_len, &b11->timestamp, 35))
686 		return decode_fail(b11, fail, "Can't get 35-bit timestamp");
687 
688 	while (data_len > 520 / 5) {
689 		const char *problem = NULL;
690 		u64 type, data_length;
691 
692 		/* BOLT #11:
693 		 *
694 		 * Each Tagged Field is of the form:
695 		 *
696 		 * 1. `type` (5 bits)
697 		 * 1. `data_length` (10 bits, big-endian)
698 		 * 1. `data` (`data_length` x 5 bits)
699 		 */
700 		if (!pull_uint(&hu5, &data, &data_len, &type, 5)
701 		    || !pull_uint(&hu5, &data, &data_len, &data_length, 10))
702 			return decode_fail(b11, fail,
703 					   "Can't get tag and length");
704 
705 		/* Can't exceed total data remaining. */
706 		if (data_length > data_len)
707 			return decode_fail(b11, fail, "%c: truncated",
708 					   bech32_charset[type]);
709 
710 		switch (bech32_charset[type]) {
711 		case 'p':
712 			decode_p(b11, &hu5, &data, &data_len, data_length,
713 				 &have_p);
714 			break;
715 
716 		case 'd':
717 			problem = decode_d(b11, &hu5, &data, &data_len,
718 					   data_length, &have_d);
719 			break;
720 
721 		case 'h':
722 			decode_h(b11, &hu5, &data, &data_len, data_length,
723 				 &have_h);
724 			break;
725 
726 		case 'n':
727 			problem = decode_n(b11, &hu5, &data,
728 					   &data_len, data_length,
729 					   have_n);
730 			break;
731 
732 		case 'x':
733 			problem = decode_x(b11, &hu5, &data,
734 					   &data_len, data_length,
735 					   &have_x);
736 			break;
737 
738 		case 'c':
739 			problem = decode_c(b11, &hu5, &data,
740 					   &data_len, data_length,
741 					   &have_c);
742 			break;
743 
744 		case 'f':
745 			problem = decode_f(b11, &hu5, &data,
746 					   &data_len, data_length);
747 			break;
748 		case 'r':
749 			problem = decode_r(b11, &hu5, &data, &data_len,
750 					   data_length);
751 			break;
752 		case '9':
753 			problem = decode_9(b11, our_features, &hu5,
754 					   &data, &data_len,
755 					   data_length);
756 			break;
757 		case 's':
758 			problem = decode_s(b11, &hu5, &data, &data_len,
759 					   data_length, &have_s);
760 			break;
761 		default:
762 			unknown_field(b11, &hu5, &data, &data_len,
763 				      bech32_charset[type], data_length);
764 		}
765 		if (problem)
766 			return decode_fail(b11, fail, "%s", problem);
767 	}
768 
769 	if (!have_p)
770 		return decode_fail(b11, fail, "No valid 'p' field found");
771 
772 	if (have_h && description) {
773 		struct sha256 sha;
774 
775 		/* BOLT #11:
776 		 *
777 		 * A reader... MUST check that the SHA2 256-bit hash
778 		 * in the `h` field exactly matches the hashed
779 		 * description.
780 		 */
781 		sha256(&sha, description, strlen(description));
782 		if (!sha256_eq(b11->description_hash, &sha))
783 			return decode_fail(b11, fail,
784 					   "h: does not match description");
785 	}
786 
787 	hash_u5_done(&hu5, hash);
788 	*sig = tal_dup_arr(ctx, u5, data, data_len, 0);
789 	return b11;
790 }
791 
792 /* Decodes and checks signature; returns NULL on error. */
bolt11_decode(const tal_t * ctx,const char * str,const struct feature_set * our_features,const char * description,const struct chainparams * must_be_chain,char ** fail)793 struct bolt11 *bolt11_decode(const tal_t *ctx, const char *str,
794 			     const struct feature_set *our_features,
795 			     const char *description,
796 			     const struct chainparams *must_be_chain,
797 			     char **fail)
798 {
799 	u5 *sigdata;
800 	size_t data_len;
801 	u8 sig_and_recid[65];
802 	secp256k1_ecdsa_recoverable_signature sig;
803 	struct bolt11 *b11;
804 	struct sha256 hash;
805 	bool have_n;
806 
807 	b11 = bolt11_decode_nosig(ctx, str, our_features, description,
808 				  must_be_chain, &hash, &sigdata, &have_n,
809 				  fail);
810 	if (!b11)
811 		return NULL;
812 
813 	/* BOLT #11:
814 	 *
815 	 * A writer...MUST set `signature` to a valid 512-bit
816 	 * secp256k1 signature of the SHA2 256-bit hash of the
817 	 * human-readable part, represented as UTF-8 bytes,
818 	 * concatenated with the data part (excluding the signature)
819 	 * with 0 bits appended to pad the data to the next byte
820 	 * boundary, with a trailing byte containing the recovery ID
821 	 * (0, 1, 2, or 3).
822 	 */
823 	data_len = tal_count(sigdata);
824 	if (!pull_bits(NULL, &sigdata, &data_len, sig_and_recid, 520, false))
825 		return decode_fail(b11, fail, "signature truncated");
826 
827 	assert(data_len == 0);
828 
829 	if (!secp256k1_ecdsa_recoverable_signature_parse_compact
830 	    (secp256k1_ctx, &sig, sig_and_recid, sig_and_recid[64]))
831 		return decode_fail(b11, fail, "signature invalid");
832 
833 	secp256k1_ecdsa_recoverable_signature_convert(secp256k1_ctx,
834 						      &b11->sig, &sig);
835 
836 	/* BOLT #11:
837 	 *
838 	 * A reader...  MUST check that the `signature` is valid (see
839 	 * the `n` tagged field specified below). ... A reader...
840 	 * MUST use the `n` field to validate the signature instead of
841 	 * performing signature recovery.
842 	 */
843 	if (!have_n) {
844 		struct pubkey k;
845 		if (!secp256k1_ecdsa_recover(secp256k1_ctx,
846 					     &k.pubkey,
847 					     &sig,
848 					     (const u8 *)&hash))
849 			return decode_fail(b11, fail,
850 					   "signature recovery failed");
851 		node_id_from_pubkey(&b11->receiver_id, &k);
852 	} else {
853 		struct pubkey k;
854 		/* n parsing checked this! */
855 		if (!pubkey_from_node_id(&k, &b11->receiver_id))
856 			abort();
857 		if (!secp256k1_ecdsa_verify(secp256k1_ctx, &b11->sig,
858 					    (const u8 *)&hash,
859 					    &k.pubkey))
860 			return decode_fail(b11, fail, "invalid signature");
861 	}
862 
863 	return b11;
864 }
865 
866 /* Helper for pushing a variable-length big-endian int. */
push_varlen_uint(u5 ** data,u64 val,size_t nbits)867 static void push_varlen_uint(u5 **data, u64 val, size_t nbits)
868 {
869 	be64 be_val = cpu_to_be64(val << (64 - nbits));
870 	bech32_push_bits(data, &be_val, nbits);
871 }
872 
873 /* BOLT #11:
874  *
875  * Each Tagged Field is of the form:
876  *
877  * 1. `type` (5 bits)
878  * 1. `data_length` (10 bits, big-endian)
879  * 1. `data` (`data_length` x 5 bits)
880  */
push_field_type_and_len(u5 ** data,char type,size_t nbits)881 static void push_field_type_and_len(u5 **data, char type, size_t nbits)
882 {
883 	assert(bech32_charset_rev[(unsigned char)type] >= 0);
884 	push_varlen_uint(data, bech32_charset_rev[(unsigned char)type], 5);
885 	push_varlen_uint(data, (nbits + 4) / 5, 10);
886 }
887 
push_field(u5 ** data,char type,const void * src,size_t nbits)888 static void push_field(u5 **data, char type, const void *src, size_t nbits)
889 {
890 	push_field_type_and_len(data, type, nbits);
891 	bech32_push_bits(data, src, nbits);
892 }
893 
894 /* BOLT #11:
895  *
896  * - if `x` is included:
897  *   - SHOULD use the minimum `data_length` possible.
898  * - MUST include one `c` field (`min_final_cltv_expiry`).
899  *...
900  *   - SHOULD use the minimum `data_length` possible.
901  */
push_varlen_field(u5 ** data,char type,u64 val)902 static void push_varlen_field(u5 **data, char type, u64 val)
903 {
904 	assert(bech32_charset_rev[(unsigned char)type] >= 0);
905 	push_varlen_uint(data, bech32_charset_rev[(unsigned char)type], 5);
906 
907 	for (size_t nbits = 5; nbits < 65; nbits += 5) {
908 		if ((val >> nbits) == 0) {
909 			push_varlen_uint(data, nbits / 5, 10);
910 			push_varlen_uint(data, val,  nbits);
911 			return;
912 		}
913 	}
914 	/* Can't be encoded in <= 60 bits. */
915 	abort();
916 }
917 
918 /* BOLT #11:
919  *
920  * `f` (9): `data_length` variable, depending on version. Fallback
921  * on-chain address: for Bitcoin, this starts with a 5-bit `version`
922  * and contains a witness program or P2PKH or P2SH address.
923  */
push_fallback_addr(u5 ** data,u5 version,const void * addr,u16 addr_len)924 static void push_fallback_addr(u5 **data, u5 version, const void *addr, u16 addr_len)
925 {
926 	push_varlen_uint(data, bech32_charset_rev[(unsigned char)'f'], 5);
927 	push_varlen_uint(data, ((5 + addr_len * CHAR_BIT) + 4) / 5, 10);
928 	push_varlen_uint(data, version, 5);
929 	bech32_push_bits(data, addr, addr_len * CHAR_BIT);
930 }
931 
encode_p(u5 ** data,const struct sha256 * hash)932 static void encode_p(u5 **data, const struct sha256 *hash)
933 {
934 	push_field(data, 'p', hash, 256);
935 }
936 
encode_d(u5 ** data,const char * description)937 static void encode_d(u5 **data, const char *description)
938 {
939 	push_field(data, 'd', description, strlen(description) * CHAR_BIT);
940 }
941 
encode_h(u5 ** data,const struct sha256 * hash)942 static void encode_h(u5 **data, const struct sha256 *hash)
943 {
944 	push_field(data, 'h', hash, 256);
945 }
946 
encode_n(u5 ** data,const struct node_id * id)947 static void encode_n(u5 **data, const struct node_id *id)
948 {
949 	assert(node_id_valid(id));
950 	push_field(data, 'n', id->k, sizeof(id->k) * CHAR_BIT);
951 }
952 
encode_x(u5 ** data,u64 expiry)953 static void encode_x(u5 **data, u64 expiry)
954 {
955 	push_varlen_field(data, 'x', expiry);
956 }
957 
encode_c(u5 ** data,u16 min_final_cltv_expiry)958 static void encode_c(u5 **data, u16 min_final_cltv_expiry)
959 {
960 	push_varlen_field(data, 'c', min_final_cltv_expiry);
961 }
962 
encode_s(u5 ** data,const struct secret * payment_secret)963 static void encode_s(u5 **data, const struct secret *payment_secret)
964 {
965 	push_field(data, 's', payment_secret, 256);
966 }
967 
encode_f(u5 ** data,const u8 * fallback)968 static void encode_f(u5 **data, const u8 *fallback)
969 {
970 	struct bitcoin_address pkh;
971 	struct ripemd160 sh;
972 	struct sha256 wsh;
973 
974 	/* BOLT #11:
975 	 *
976 	 * for Bitcoin payments... MUST set an `f` field to a valid
977 	 * witness version and program, OR to `17` followed by a
978 	 * public key hash, OR to `18` followed by a script hash.
979 	 */
980 	if (is_p2pkh(fallback, &pkh)) {
981 		push_fallback_addr(data, 17, &pkh, sizeof(pkh));
982 	} else if (is_p2sh(fallback, &sh)) {
983 		push_fallback_addr(data, 18, &sh, sizeof(sh));
984 	} else if (is_p2wpkh(fallback, &pkh)) {
985 		push_fallback_addr(data, 0, &pkh, sizeof(pkh));
986 	} else if (is_p2wsh(fallback, &wsh)) {
987 		push_fallback_addr(data, 0, &wsh, sizeof(wsh));
988 	} else if (tal_count(fallback)
989 		   && fallback[0] >= 0x50
990 		   && fallback[0] < (0x50+16)) {
991 		/* Other (future) witness versions: turn OP_N into N */
992 		push_fallback_addr(data, fallback[0] - 0x50, fallback + 1,
993 				   tal_count(fallback) - 1);
994 	} else {
995 		/* Copy raw. */
996 		push_field(data, 'f',
997 			   fallback, tal_count(fallback) * CHAR_BIT);
998 	}
999 }
1000 
encode_r(u5 ** data,const struct route_info * r)1001 static void encode_r(u5 **data, const struct route_info *r)
1002 {
1003 	u8 *rinfo = tal_arr(NULL, u8, 0);
1004 
1005 	for (size_t i = 0; i < tal_count(r); i++)
1006 		towire_route_info(&rinfo, &r[i]);
1007 
1008 	push_field(data, 'r', rinfo, tal_count(rinfo) * CHAR_BIT);
1009 	tal_free(rinfo);
1010 }
1011 
maybe_encode_9(u5 ** data,const u8 * features)1012 static void maybe_encode_9(u5 **data, const u8 *features)
1013 {
1014 	u5 *f5 = tal_arr(NULL, u5, 0);
1015 
1016 	for (size_t i = 0; i < tal_count(features) * CHAR_BIT; i++) {
1017 		if (!feature_is_set(features, i))
1018 			continue;
1019 		/* We expand it out so it makes a BE 5-bit/btye bitfield */
1020 		set_feature_bit(&f5, (i / 5) * 8 + (i % 5));
1021 	}
1022 
1023 	/* BOLT #11:
1024 	 *
1025 	 * - if `9` contains non-zero bits:
1026 	 *   - SHOULD use the minimum `data_length` possible.
1027 	 * - otherwise:
1028 	 *   - MUST omit the `9` field altogether.
1029 	 */
1030 	if (tal_count(f5) != 0) {
1031 		push_field_type_and_len(data, '9', tal_count(f5) * 5);
1032 		tal_expand(data, f5, tal_count(f5));
1033 	}
1034 	tal_free(f5);
1035 }
1036 
encode_extra(u5 ** data,const struct bolt11_field * extra)1037 static bool encode_extra(u5 **data, const struct bolt11_field *extra)
1038 {
1039 	size_t len;
1040 
1041 	/* Can't encode an invalid tag. */
1042 	if (bech32_charset_rev[(unsigned char)extra->tag] == -1)
1043 		return false;
1044 
1045 	push_varlen_uint(data, bech32_charset_rev[(unsigned char)extra->tag], 5);
1046 	push_varlen_uint(data, tal_count(extra->data), 10);
1047 
1048 	/* extra->data is already u5s, so do this raw. */
1049 	len = tal_count(*data);
1050 	tal_resize(data, len + tal_count(extra->data));
1051 	memcpy(*data + len, extra->data, tal_count(extra->data));
1052 	return true;
1053 }
1054 
1055 /* Encodes, even if it's nonsense. */
bolt11_encode_(const tal_t * ctx,const struct bolt11 * b11,bool n_field,bool (* sign)(const u5 * u5bytes,const u8 * hrpu8,secp256k1_ecdsa_recoverable_signature * rsig,void * arg),void * arg)1056 char *bolt11_encode_(const tal_t *ctx,
1057 		     const struct bolt11 *b11, bool n_field,
1058 		     bool (*sign)(const u5 *u5bytes,
1059 				  const u8 *hrpu8,
1060 				  secp256k1_ecdsa_recoverable_signature *rsig,
1061 				  void *arg),
1062 		     void *arg)
1063 {
1064 	u5 *data = tal_arr(tmpctx, u5, 0);
1065 	char *hrp, *output;
1066 	u64 amount;
1067 	struct bolt11_field *extra;
1068 	secp256k1_ecdsa_recoverable_signature rsig;
1069 	u8 sig_and_recid[65];
1070 	u8 *hrpu8;
1071 	int recid;
1072 
1073 	/* BOLT #11:
1074 	 *
1075 	 * A writer:
1076 	 * - MUST encode `prefix` using the currency required for successful payment.
1077 	 * - if a specific minimum `amount` is required for successful payment:
1078 	 *   - MUST include that `amount`.
1079 	 * - MUST encode `amount` as a positive decimal integer with no leading 0s.
1080 	 * - If the `p` multiplier is used the last decimal of `amount` MUST be `0`.
1081 	 * - SHOULD use the shortest representation possible, by using the largest multiplier or omitting the multiplier.
1082 	 */
1083 	if (b11->msat) {
1084 		char postfix;
1085 		u64 msat = b11->msat->millisatoshis; /* Raw: best-multiplier calc */
1086 		if (msat % MSAT_PER_BTC == 0) {
1087 			postfix = '\0';
1088 			amount = msat / MSAT_PER_BTC;
1089 		} else {
1090 			size_t i;
1091 			for (i = 0; i < ARRAY_SIZE(multipliers)-1; i++) {
1092 				if (!(msat * 10 % multipliers[i].m10))
1093 					break;
1094 			}
1095 			postfix = multipliers[i].letter;
1096 			amount = msat * 10 / multipliers[i].m10;
1097 		}
1098 		hrp = tal_fmt(tmpctx, "ln%s%"PRIu64"%c",
1099 			      b11->chain->bip173_name, amount, postfix);
1100 	} else
1101 		hrp = tal_fmt(tmpctx, "ln%s", b11->chain->bip173_name);
1102 
1103 	/* BOLT #11:
1104 	 *
1105 	 * 1. `timestamp`: seconds-since-1970 (35 bits, big-endian)
1106 	 * 1. zero or more tagged parts
1107 	 * 1. `signature`: Bitcoin-style signature of above (520 bits)
1108 	 */
1109 	push_varlen_uint(&data, b11->timestamp, 35);
1110 
1111 	/* BOLT #11:
1112 	 *
1113 	 * if a writer offers more than one of any field type,
1114 	 * it... MUST specify the most-preferred field first, followed
1115 	 * by less-preferred fields, in order.
1116 	 */
1117 	/* Thus we do built-in fields, then extras last. */
1118 	encode_p(&data, &b11->payment_hash);
1119 
1120 	if (b11->description)
1121 		encode_d(&data, b11->description);
1122 
1123 	if (b11->description_hash)
1124 		encode_h(&data, b11->description_hash);
1125 
1126 	if (n_field)
1127 		encode_n(&data, &b11->receiver_id);
1128 
1129 	if (b11->expiry != DEFAULT_X)
1130 		encode_x(&data, b11->expiry);
1131 
1132 	/* BOLT #11:
1133 	 *   - MUST include one `c` field (`min_final_cltv_expiry`).
1134 	 */
1135 	encode_c(&data, b11->min_final_cltv_expiry);
1136 
1137 	if (b11->payment_secret)
1138 		encode_s(&data, b11->payment_secret);
1139 
1140 	for (size_t i = 0; i < tal_count(b11->fallbacks); i++)
1141 		encode_f(&data, b11->fallbacks[i]);
1142 
1143 	for (size_t i = 0; i < tal_count(b11->routes); i++)
1144 		encode_r(&data, b11->routes[i]);
1145 
1146 	maybe_encode_9(&data, b11->features);
1147 
1148 	list_for_each(&b11->extra_fields, extra, list)
1149 		if (!encode_extra(&data, extra))
1150 			return NULL;
1151 
1152 	/* FIXME: towire_ should check this? */
1153 	if (tal_count(data) > 65535)
1154 		return NULL;
1155 
1156 	/* Need exact length here */
1157 	hrpu8 = tal_dup_arr(tmpctx, u8, (const u8 *)hrp, strlen(hrp), 0);
1158 	if (!sign(data, hrpu8, &rsig, arg))
1159 		return NULL;
1160 
1161 	secp256k1_ecdsa_recoverable_signature_serialize_compact(
1162 		secp256k1_ctx,
1163 		sig_and_recid,
1164 		&recid,
1165 		&rsig);
1166 	sig_and_recid[64] = recid;
1167 
1168 	bech32_push_bits(&data, sig_and_recid, sizeof(sig_and_recid) * CHAR_BIT);
1169 
1170 	output = tal_arr(ctx, char, strlen(hrp) + tal_count(data) + 8);
1171 	if (!bech32_encode(output, hrp, data, tal_count(data), (size_t)-1,
1172 			   BECH32_ENCODING_BECH32))
1173 		output = tal_free(output);
1174 
1175 	return output;
1176 }
1177