1 #include <bitcoin/chainparams.h>
2 #include <ccan/tal/str/str.h>
3 #include <common/bech32_util.h>
4 #include <common/bolt12.h>
5 #include <common/bolt12_merkle.h>
6 #include <common/configdir.h>
7 #include <common/features.h>
8 #include <secp256k1_schnorrsig.h>
9 #include <time.h>
10 
bolt12_chains_match(const struct bitcoin_blkid * chains,const struct chainparams * must_be_chain)11 bool bolt12_chains_match(const struct bitcoin_blkid *chains,
12 			 const struct chainparams *must_be_chain)
13 {
14 	size_t num_chains;
15 
16 	/* BOLT-offers #12:
17 	 *   - if the chain for the invoice is not solely bitcoin:
18 	 *     - MUST specify `chains` the offer is valid for.
19 	 *   - otherwise:
20 	 *     - the bitcoin chain is implied as the first and only entry.
21 	 */
22 	/* BOLT-offers #12:
23 	 * The reader of an invoice_request:
24 	 *...
25 	 *  - MUST fail the request if `chains` does not include (or
26 	 *    imply) a supported chain.
27 	 */
28 	/* BOLT-offers #12:
29 	 *
30 	 * - if the chain for the invoice is not solely bitcoin:
31 	 *   - MUST specify `chains` the invoice is valid for.
32 	 * - otherwise:
33 	 *   - the bitcoin chain is implied as the first and only entry.
34 	 */
35 	num_chains = tal_count(chains);
36 	if (num_chains == 0) {
37 		num_chains = 1;
38 		chains = &chainparams_for_network("bitcoin")->genesis_blockhash;
39 	}
40 
41 	for (size_t i = 0; i < num_chains; i++) {
42 		if (bitcoin_blkid_eq(&chains[i],
43 				     &must_be_chain->genesis_blockhash))
44 			return true;
45 	}
46 
47 	return false;
48 }
49 
bolt12_chain_matches(const struct bitcoin_blkid * chain,const struct chainparams * must_be_chain,const struct bitcoin_blkid * deprecated_chains)50 bool bolt12_chain_matches(const struct bitcoin_blkid *chain,
51 			  const struct chainparams *must_be_chain,
52 			  const struct bitcoin_blkid *deprecated_chains)
53 {
54 	/* Obsolete: We used to put an array in here, but we only ever
55 	 * used a single value */
56 	if (deprecated_apis && !chain)
57 		chain = deprecated_chains;
58 
59 	if (!chain)
60 		chain = &chainparams_for_network("bitcoin")->genesis_blockhash;
61 
62 	return bitcoin_blkid_eq(chain, &must_be_chain->genesis_blockhash);
63 }
64 
check_features_and_chain(const tal_t * ctx,const struct feature_set * our_features,const struct chainparams * must_be_chain,const u8 * features,const struct bitcoin_blkid * chains)65 static char *check_features_and_chain(const tal_t *ctx,
66 				      const struct feature_set *our_features,
67 				      const struct chainparams *must_be_chain,
68 				      const u8 *features,
69 				      const struct bitcoin_blkid *chains)
70 {
71 	if (must_be_chain) {
72 		if (!bolt12_chains_match(chains, must_be_chain))
73 			return tal_fmt(ctx, "wrong chain");
74 	}
75 
76 	if (our_features) {
77 		int badf = features_unsupported(our_features, features,
78 						BOLT11_FEATURE);
79 		if (badf != -1)
80 			return tal_fmt(ctx, "unknown feature bit %i", badf);
81 	}
82 
83 	return NULL;
84 }
85 
bolt12_check_signature(const struct tlv_field * fields,const char * messagename,const char * fieldname,const struct point32 * key,const struct bip340sig * sig)86 bool bolt12_check_signature(const struct tlv_field *fields,
87 			    const char *messagename,
88 			    const char *fieldname,
89 			    const struct point32 *key,
90 			    const struct bip340sig *sig)
91 {
92 	struct sha256 m, shash;
93 
94 	merkle_tlv(fields, &m);
95 	sighash_from_merkle(messagename, fieldname, &m, &shash);
96 	return secp256k1_schnorrsig_verify(secp256k1_ctx,
97 					   sig->u8,
98 					   shash.u.u8,
99 					   &key->pubkey) == 1;
100 }
101 
check_signature(const tal_t * ctx,const struct tlv_field * fields,const char * messagename,const char * fieldname,const struct point32 * node_id,const struct bip340sig * sig)102 static char *check_signature(const tal_t *ctx,
103 			     const struct tlv_field *fields,
104 			     const char *messagename,
105 			     const char *fieldname,
106 			     const struct point32 *node_id,
107 			     const struct bip340sig *sig)
108 {
109 	if (!node_id)
110 		return tal_fmt(ctx, "Missing node_id");
111 	if (!sig)
112 		return tal_fmt(ctx, "Missing signature");
113 
114 	if (!bolt12_check_signature(fields,
115 				    messagename, fieldname, node_id, sig))
116 		return tal_fmt(ctx, "Invalid signature");
117 	return NULL;
118 }
119 
string_to_data(const tal_t * ctx,const char * str,size_t str_len,const char * hrp_expected,size_t * dlen,char ** fail)120 static const u8 *string_to_data(const tal_t *ctx,
121 				const char *str,
122 				size_t str_len,
123 				const char *hrp_expected,
124 				size_t *dlen,
125 				char **fail)
126 {
127 	char *hrp;
128 	u8 *data;
129 	char *bech32;
130 	size_t bech32_len;
131 	bool have_plus = false;
132 
133 	/* First we collapse +\s*, except at start/end. */
134 	bech32 = tal_arr(tmpctx, char, str_len);
135 	bech32_len = 0;
136 	for (size_t i = 0; i < str_len; i++) {
137 		if (i != 0 && i+1 != str_len && !have_plus && str[i] == '+') {
138 			have_plus = true;
139 			continue;
140 		}
141 		if (have_plus && cisspace(str[i]))
142 			continue;
143 		have_plus = false;
144 		bech32[bech32_len++] = str[i];
145 	}
146 
147 	if (have_plus) {
148 		*fail = tal_fmt(ctx, "unfinished string");
149 		return NULL;
150 	}
151 
152 	if (!from_bech32_charset(ctx, bech32, bech32_len, &hrp, &data)) {
153 		*fail = tal_fmt(ctx, "invalid bech32 string");
154 		return NULL;
155 	}
156 	if (!streq(hrp, hrp_expected)) {
157 		*fail = tal_fmt(ctx, "unexpected prefix %s", hrp);
158 		data = tal_free(data);
159 	} else
160 		*dlen = tal_bytelen(data);
161 
162 	tal_free(hrp);
163 	return data;
164 }
165 
offer_encode(const tal_t * ctx,const struct tlv_offer * offer_tlv)166 char *offer_encode(const tal_t *ctx, const struct tlv_offer *offer_tlv)
167 {
168 	u8 *wire;
169 
170 	wire = tal_arr(tmpctx, u8, 0);
171 	towire_offer(&wire, offer_tlv);
172 
173 	return to_bech32_charset(ctx, "lno", wire);
174 }
175 
offer_decode(const tal_t * ctx,const char * b12,size_t b12len,const struct feature_set * our_features,const struct chainparams * must_be_chain,char ** fail)176 struct tlv_offer *offer_decode(const tal_t *ctx,
177 			       const char *b12, size_t b12len,
178 			       const struct feature_set *our_features,
179 			       const struct chainparams *must_be_chain,
180 			       char **fail)
181 {
182 	struct tlv_offer *offer = tlv_offer_new(ctx);
183 	const u8 *data;
184 	size_t dlen;
185 
186 	data = string_to_data(tmpctx, b12, b12len, "lno", &dlen, fail);
187 	if (!data)
188 		return tal_free(offer);
189 
190 	if (!fromwire_offer(&data, &dlen, offer)) {
191 		*fail = tal_fmt(ctx, "invalid offer data");
192 		return tal_free(offer);
193 	}
194 
195 	*fail = check_features_and_chain(ctx,
196 					 our_features, must_be_chain,
197 					 offer->features,
198 					 offer->chains);
199 	if (*fail)
200 		return tal_free(offer);
201 
202 	/* BOLT-offers #12:
203 	 * - if `signature` is present, but is not a valid signature using
204 	 *   `node_id` as described in [Signature Calculation](#signature-calculation):
205 	 *   - MUST NOT respond to the offer.
206 	 */
207 	if (offer->signature) {
208 		*fail = check_signature(ctx, offer->fields,
209 					"offer", "signature",
210 					offer->node_id, offer->signature);
211 		if (*fail)
212 			return tal_free(offer);
213 	}
214 
215 	return offer;
216 }
217 
invrequest_encode(const tal_t * ctx,const struct tlv_invoice_request * invrequest_tlv)218 char *invrequest_encode(const tal_t *ctx, const struct tlv_invoice_request *invrequest_tlv)
219 {
220 	u8 *wire;
221 
222 	wire = tal_arr(tmpctx, u8, 0);
223 	towire_invoice_request(&wire, invrequest_tlv);
224 
225 	return to_bech32_charset(ctx, "lnr", wire);
226 }
227 
invrequest_decode(const tal_t * ctx,const char * b12,size_t b12len,const struct feature_set * our_features,const struct chainparams * must_be_chain,char ** fail)228 struct tlv_invoice_request *invrequest_decode(const tal_t *ctx,
229 					      const char *b12, size_t b12len,
230 					      const struct feature_set *our_features,
231 					      const struct chainparams *must_be_chain,
232 					      char **fail)
233 {
234 	struct tlv_invoice_request *invrequest = tlv_invoice_request_new(ctx);
235 	const u8 *data;
236 	size_t dlen;
237 
238 	data = string_to_data(tmpctx, b12, b12len, "lnr", &dlen, fail);
239 	if (!data)
240 		return tal_free(invrequest);
241 
242 	if (!fromwire_invoice_request(&data, &dlen, invrequest)) {
243 		*fail = tal_fmt(ctx, "invalid invoice_request data");
244 		return tal_free(invrequest);
245 	}
246 
247 	*fail = check_features_and_chain(ctx,
248 					 our_features, must_be_chain,
249 					 invrequest->features,
250 					 invrequest->chain
251 					 ? invrequest->chain
252 					 : invrequest->chains);
253 	if (*fail)
254 		return tal_free(invrequest);
255 
256 	return invrequest;
257 }
258 
invoice_encode(const tal_t * ctx,const struct tlv_invoice * invoice_tlv)259 char *invoice_encode(const tal_t *ctx, const struct tlv_invoice *invoice_tlv)
260 {
261 	u8 *wire;
262 
263 	wire = tal_arr(tmpctx, u8, 0);
264 	towire_invoice(&wire, invoice_tlv);
265 
266 	return to_bech32_charset(ctx, "lni", wire);
267 }
268 
invoice_decode_nosig(const tal_t * ctx,const char * b12,size_t b12len,const struct feature_set * our_features,const struct chainparams * must_be_chain,char ** fail)269 struct tlv_invoice *invoice_decode_nosig(const tal_t *ctx,
270 					 const char *b12, size_t b12len,
271 					 const struct feature_set *our_features,
272 					 const struct chainparams *must_be_chain,
273 					 char **fail)
274 {
275 	struct tlv_invoice *invoice = tlv_invoice_new(ctx);
276 	const u8 *data;
277 	size_t dlen;
278 
279 	data = string_to_data(tmpctx, b12, b12len, "lni", &dlen, fail);
280 	if (!data)
281 		return tal_free(invoice);
282 
283 	if (!fromwire_invoice(&data, &dlen, invoice)) {
284 		*fail = tal_fmt(ctx, "invalid invoice data");
285 		return tal_free(invoice);
286 	}
287 
288 	*fail = check_features_and_chain(ctx,
289 					 our_features, must_be_chain,
290 					 invoice->features,
291 					 invoice->chain
292 					 ? invoice->chain : invoice->chains);
293 	if (*fail)
294 		return tal_free(invoice);
295 
296 	return invoice;
297 }
298 
add_days(struct tm * tm,u32 number)299 static void add_days(struct tm *tm, u32 number)
300 {
301 	tm->tm_mday += number;
302 }
303 
add_months(struct tm * tm,u32 number)304 static void add_months(struct tm *tm, u32 number)
305 {
306 	tm->tm_mon += number;
307 }
308 
add_years(struct tm * tm,u32 number)309 static void add_years(struct tm *tm, u32 number)
310 {
311 	tm->tm_year += number;
312 }
313 
time_change(u64 prevstart,u32 number,void (* add_time)(struct tm * tm,u32 number),bool day_const)314 static u64 time_change(u64 prevstart, u32 number,
315 		       void (*add_time)(struct tm *tm, u32 number),
316 		       bool day_const)
317 {
318 	struct tm tm;
319 	time_t prev = prevstart, ret;
320 
321 	tm = *gmtime(&prev);
322 
323 	for (;;) {
324 		struct tm new_tm = tm;
325 		add_time(&new_tm, number);
326 		ret = mktime(&new_tm);
327 
328 		if (ret == (time_t)-1)
329 			return 0;
330 
331 		/* If we overflowed that month, try one less. */
332 		if (!day_const || new_tm.tm_mday == tm.tm_mday)
333 			break;
334 		tm.tm_mday--;
335 	}
336 
337 	return ret;
338 }
339 
offer_period_start(u64 basetime,size_t n,const struct tlv_offer_recurrence * recur)340 u64 offer_period_start(u64 basetime, size_t n,
341 		       const struct tlv_offer_recurrence *recur)
342 {
343 	/* BOLT-offers #12:
344 	 * 1. A `time_unit` defining 0 (seconds), 1 (days), 2 (months),
345 	 *    3 (years).
346 	 */
347 	switch (recur->time_unit) {
348 	case 0:
349 		return basetime + recur->period * n;
350 	case 1:
351 		return time_change(basetime, recur->period * n, add_days, false);
352 	case 2:
353 		return time_change(basetime, recur->period * n, add_months, true);
354 	case 3:
355 		return time_change(basetime, recur->period * n, add_years, true);
356 	default:
357 		/* This is our offer, how did we get here? */
358 		return 0;
359 	}
360 }
361 
offer_period_paywindow(const struct tlv_offer_recurrence * recurrence,const struct tlv_offer_recurrence_paywindow * recurrence_paywindow,const struct tlv_offer_recurrence_base * recurrence_base,u64 basetime,u64 period_idx,u64 * start,u64 * end)362 void offer_period_paywindow(const struct tlv_offer_recurrence *recurrence,
363 			    const struct tlv_offer_recurrence_paywindow *recurrence_paywindow,
364 			    const struct tlv_offer_recurrence_base *recurrence_base,
365 			    u64 basetime, u64 period_idx,
366 			    u64 *start, u64 *end)
367 {
368 	/* BOLT-offers #12:
369 	 * - if the offer contains `recurrence_paywindow`:
370 	 */
371 	if (recurrence_paywindow) {
372 		u64 pstart = offer_period_start(basetime, period_idx,
373 						recurrence);
374 		/* BOLT-offers #12:
375 		 * - if the offer has a `recurrence_basetime` or the
376 		 *    `recurrence_counter` is non-zero:
377 		 *   - SHOULD NOT send an `invoice_request` for a period prior to
378 		 *     `seconds_before` seconds before that period start.
379 		 *   - SHOULD NOT send an `invoice_request` for a period later
380 		 *     than `seconds_after` seconds past that period start.
381 		 */
382 		*start = pstart - recurrence_paywindow->seconds_before;
383 		*end = pstart + recurrence_paywindow->seconds_after;
384 
385 		/* First payment without recurrence_base, we give
386 		 * ourselves 60 seconds, since period will start
387 		 * now */
388 		if (!recurrence_base && period_idx == 0
389 		    && recurrence_paywindow->seconds_after < 60)
390 			*end = pstart + 60;
391 	} else {
392 		/* BOLT-offers #12:
393 		 * - otherwise:
394 		 *   - SHOULD NOT send an `invoice_request` with
395 		 *     `recurrence_counter` is non-zero for a period whose
396 		 *     immediate predecessor has not yet begun.
397 		 */
398 		if (period_idx == 0)
399 			*start = 0;
400 		else
401 			*start = offer_period_start(basetime, period_idx-1,
402 						    recurrence);
403 
404 		/* BOLT-offers #12:
405 		 *     - SHOULD NOT send an `invoice_request` for a period which
406 		 *       has already passed.
407 		 */
408 		*end = offer_period_start(basetime, period_idx+1,
409 					  recurrence) - 1;
410 	}
411 }
412 
invoice_decode(const tal_t * ctx,const char * b12,size_t b12len,const struct feature_set * our_features,const struct chainparams * must_be_chain,char ** fail)413 struct tlv_invoice *invoice_decode(const tal_t *ctx,
414 				   const char *b12, size_t b12len,
415 				   const struct feature_set *our_features,
416 				   const struct chainparams *must_be_chain,
417 				   char **fail)
418 {
419 	struct tlv_invoice *invoice;
420 
421 	invoice = invoice_decode_nosig(ctx, b12, b12len, our_features,
422 				       must_be_chain, fail);
423 	if (invoice) {
424 		*fail = check_signature(ctx, invoice->fields,
425 					"invoice", "signature",
426 					invoice->node_id, invoice->signature);
427 		if (*fail)
428 			invoice = tal_free(invoice);
429 	}
430 	return invoice;
431 }
432 
bolt12_has_invoice_prefix(const char * str)433 bool bolt12_has_invoice_prefix(const char *str)
434 {
435 	return strstarts(str, "lni1") || strstarts(str, "LNI1");
436 }
437 
bolt12_has_request_prefix(const char * str)438 bool bolt12_has_request_prefix(const char *str)
439 {
440 	return strstarts(str, "lnr1") || strstarts(str, "LNR1");
441 }
442 
bolt12_has_offer_prefix(const char * str)443 bool bolt12_has_offer_prefix(const char *str)
444 {
445 	return strstarts(str, "lno1") || strstarts(str, "LNO1");
446 }
447 
bolt12_has_prefix(const char * str)448 bool bolt12_has_prefix(const char *str)
449 {
450 	return bolt12_has_invoice_prefix(str) || bolt12_has_offer_prefix(str) ||
451 	       bolt12_has_request_prefix(str);
452 }
453