1 #include "invoice.h"
2 #include <ccan/array_size/array_size.h>
3 #include <ccan/asort/asort.h>
4 #include <ccan/cast/cast.h>
5 #include <ccan/str/hex/hex.h>
6 #include <ccan/tal/str/str.h>
7 #include <common/bolt11_json.h>
8 #include <common/bolt12_merkle.h>
9 #include <common/configdir.h>
10 #include <common/json_command.h>
11 #include <common/json_helpers.h>
12 #include <common/json_tok.h>
13 #include <common/onion.h>
14 #include <common/overflows.h>
15 #include <common/param.h>
16 #include <common/random_select.h>
17 #include <common/timeout.h>
18 #include <common/type_to_string.h>
19 #include <errno.h>
20 #include <hsmd/hsmd_wiregen.h>
21 #include <lightningd/channel.h>
22 #include <lightningd/notification.h>
23 #include <lightningd/plugin_hook.h>
24 #include <lightningd/routehint.h>
25 #include <sodium/randombytes.h>
26 #include <wire/wire_sync.h>
27 
invoice_status_str(const struct invoice_details * inv)28 static const char *invoice_status_str(const struct invoice_details *inv)
29 {
30 	if (inv->state == PAID)
31 		return "paid";
32 	if (inv->state == EXPIRED)
33 		return "expired";
34 	return "unpaid";
35 }
36 
json_add_invoice(struct json_stream * response,const struct invoice_details * inv)37 static void json_add_invoice(struct json_stream *response,
38 			     const struct invoice_details *inv)
39 {
40 	json_add_escaped_string(response, "label", inv->label);
41 	json_add_invstring(response, inv->invstring);
42 	json_add_sha256(response, "payment_hash", &inv->rhash);
43 	if (inv->msat)
44 		json_add_amount_msat_compat(response, *inv->msat,
45 					    "msatoshi", "amount_msat");
46 	json_add_string(response, "status", invoice_status_str(inv));
47 	if (inv->state == PAID) {
48 		json_add_u64(response, "pay_index", inv->pay_index);
49 		json_add_amount_msat_compat(response, inv->received,
50 					    "msatoshi_received",
51 					    "amount_received_msat");
52 		json_add_u64(response, "paid_at", inv->paid_timestamp);
53 		json_add_preimage(response, "payment_preimage", &inv->r);
54 	}
55 	if (inv->description)
56 		json_add_string(response, "description", inv->description);
57 
58 	json_add_u64(response, "expires_at", inv->expiry_time);
59 	if (inv->local_offer_id) {
60 		char *fail;
61 		struct tlv_invoice *tinv;
62 
63 		json_add_sha256(response, "local_offer_id", inv->local_offer_id);
64 
65 		/* Everyone loves seeing their own payer notes!
66 		 * Well: they will.  Trust me. */
67 		tinv = invoice_decode(tmpctx,
68 				      inv->invstring, strlen(inv->invstring),
69 				      NULL, NULL, &fail);
70 		if (tinv && tinv->payer_note)
71 			json_add_stringn(response, "payer_note",
72 					 tinv->payer_note,
73 					 tal_bytelen(tinv->payer_note));
74 	}
75 }
76 
tell_waiter(struct command * cmd,const struct invoice * inv)77 static struct command_result *tell_waiter(struct command *cmd,
78 					  const struct invoice *inv)
79 {
80 	struct json_stream *response;
81 	const struct invoice_details *details;
82 
83 	details = wallet_invoice_details(cmd, cmd->ld->wallet, *inv);
84 	if (details->state == PAID) {
85 		response = json_stream_success(cmd);
86 		json_add_invoice(response, details);
87 		return command_success(cmd, response);
88 	} else {
89 		response = json_stream_fail(cmd, INVOICE_EXPIRED_DURING_WAIT,
90 					    "invoice expired during wait");
91 		json_add_invoice(response, details);
92 		json_object_end(response);
93 		return command_failed(cmd, response);
94 	}
95 }
96 
tell_waiter_deleted(struct command * cmd)97 static void tell_waiter_deleted(struct command *cmd)
98 {
99 	was_pending(command_fail(cmd, LIGHTNINGD,
100 				 "Invoice deleted during wait"));
101 }
wait_on_invoice(const struct invoice * invoice,void * cmd)102 static void wait_on_invoice(const struct invoice *invoice, void *cmd)
103 {
104 	if (invoice)
105 		tell_waiter((struct command *) cmd, invoice);
106 	else
107 		tell_waiter_deleted((struct command *) cmd);
108 }
wait_timed_out(struct command * cmd)109 static void wait_timed_out(struct command *cmd)
110 {
111 	was_pending(command_fail(cmd, INVOICE_WAIT_TIMED_OUT,
112 				 "Timed out while waiting "
113 				 "for invoice to be paid"));
114 }
115 
116 /* We derive invoice secret using 1-way function from payment_preimage
117  * (just a different one from the payment_hash!) */
invoice_secret(const struct preimage * payment_preimage,struct secret * payment_secret)118 static void invoice_secret(const struct preimage *payment_preimage,
119 			   struct secret *payment_secret)
120 {
121 	struct preimage modified;
122 	struct sha256 secret;
123 
124 	modified = *payment_preimage;
125 	modified.r[0] ^= 1;
126 
127 	sha256(&secret, modified.r,
128 	       ARRAY_SIZE(modified.r) * sizeof(*modified.r));
129 	BUILD_ASSERT(sizeof(secret.u.u8) == sizeof(payment_secret->data));
130 	memcpy(payment_secret->data, secret.u.u8, sizeof(secret.u.u8));
131 }
132 
133 /* FIXME: This is a hack.  The real secret should be a signature of some
134  * onion key, using the payer_id */
invoice_secret_bolt12(struct lightningd * ld,const char * invstring,struct secret * payment_secret)135 static void invoice_secret_bolt12(struct lightningd *ld,
136 				  const char *invstring,
137 				  struct secret *payment_secret)
138 {
139 	char *fail;
140 	struct tlv_invoice *inv;
141 	struct sha256 merkle;
142 
143 	inv = invoice_decode(tmpctx, invstring, strlen(invstring),
144 			     NULL, NULL, &fail);
145 	if (!inv) {
146 		log_broken(ld->log, "Unable to decode our invoice %s",
147 			   invstring);
148 		return;
149 	}
150 
151 	merkle_tlv(inv->fields, &merkle);
152 	BUILD_ASSERT(sizeof(*payment_secret) == sizeof(merkle));
153 	memcpy(payment_secret, &merkle, sizeof(merkle));
154 }
155 
156 struct invoice_payment_hook_payload {
157 	struct lightningd *ld;
158 	/* Set to NULL if it is deleted while waiting for plugin */
159 	struct htlc_set *set;
160 	/* What invoice it's trying to pay. */
161 	const struct json_escape *label;
162 	/* Amount it's offering. */
163 	struct amount_msat msat;
164 	/* Preimage we'll give it if succeeds. */
165 	struct preimage preimage;
166 	/* FIXME: Include raw payload! */
167 };
168 
169 #ifdef DEVELOPER
invoice_payment_add_tlvs(struct json_stream * stream,struct htlc_set * hset)170 static void invoice_payment_add_tlvs(struct json_stream *stream,
171 				     struct htlc_set *hset)
172 {
173 	struct htlc_in *hin;
174 	struct tlv_tlv_payload *tlvs;
175 	assert(tal_count(hset->htlcs) > 0);
176 
177 	/* Pick the first HTLC as representative for the entire set. */
178 	hin = hset->htlcs[0];
179 
180 	if (hin->payload->type != ONION_TLV_PAYLOAD)
181 		return;
182 	tlvs = hin->payload->tlv;
183 
184 	json_array_start(stream, "extratlvs");
185 
186 	for (size_t i = 0; i < tal_count(tlvs->fields); i++) {
187 		struct tlv_field *field = &tlvs->fields[i];
188 		/* If we have metadata attached it is not an extra TLV field. */
189 		if (field->meta == NULL) {
190 			json_object_start(stream, NULL);
191 			json_add_u64(stream, "type", field->numtype);
192 			json_add_num(stream, "length", field->length);
193 			json_add_hex_talarr(stream, "value", field->value);
194 			json_object_end(stream);
195 		}
196 	}
197 	json_array_end(stream);
198 }
199 #endif
200 
201 static void
invoice_payment_serialize(struct invoice_payment_hook_payload * payload,struct json_stream * stream,struct plugin * plugin)202 invoice_payment_serialize(struct invoice_payment_hook_payload *payload,
203 			  struct json_stream *stream,
204 			  struct plugin *plugin)
205 {
206 	json_object_start(stream, "payment");
207 	json_add_escaped_string(stream, "label", payload->label);
208 	json_add_preimage(stream, "preimage", &payload->preimage);
209 	json_add_string(stream, "msat",
210 			type_to_string(tmpctx, struct amount_msat,
211 				       &payload->msat));
212 #ifdef DEVELOPER
213 	invoice_payment_add_tlvs(stream, payload->set);
214 #endif
215 	json_object_end(stream); /* .payment */
216 }
217 
218 /* Set times out or HTLC deleted?  Remove set ptr from payload so we
219  * know to ignore plugin return */
invoice_payload_remove_set(struct htlc_set * set,struct invoice_payment_hook_payload * payload)220 static void invoice_payload_remove_set(struct htlc_set *set,
221 				       struct invoice_payment_hook_payload *payload)
222 {
223 	assert(payload->set == set);
224 	payload->set = NULL;
225 }
226 
hook_gives_failmsg(const tal_t * ctx,struct lightningd * ld,const struct htlc_in * hin,const char * buffer,const jsmntok_t * toks)227 static const u8 *hook_gives_failmsg(const tal_t *ctx,
228 				    struct lightningd *ld,
229 				    const struct htlc_in *hin,
230 				    const char *buffer,
231 				    const jsmntok_t *toks)
232 {
233 	const jsmntok_t *resulttok;
234 	const jsmntok_t *t;
235 	unsigned int val;
236 
237 	/* No plugin registered on hook at all? */
238 	if (!buffer)
239 		return NULL;
240 
241 	resulttok = json_get_member(buffer, toks, "result");
242 	if (resulttok) {
243 		if (json_tok_streq(buffer, resulttok, "continue")) {
244 			return NULL;
245 		} else if (json_tok_streq(buffer, resulttok, "reject")) {
246 			return failmsg_incorrect_or_unknown(ctx, ld, hin);
247 		} else
248 			fatal("Invalid invoice_payment hook result: %.*s",
249 			      toks[0].end - toks[0].start, buffer);
250 	}
251 
252 	t = json_get_member(buffer, toks, "failure_message");
253 	if (t) {
254 		const u8 *failmsg = json_tok_bin_from_hex(ctx, buffer, t);
255 		if (!failmsg)
256 			fatal("Invalid invoice_payment_hook failure_message: %.*s",
257 			      toks[0].end - toks[1].start, buffer);
258 		return failmsg;
259 	}
260 
261 	if (!deprecated_apis)
262 		return NULL;
263 
264 	t = json_get_member(buffer, toks, "failure_code");
265 	if (!t) {
266 		static bool warned = false;
267 		if (!warned) {
268 			warned = true;
269 			log_unusual(ld->log,
270 				    "Plugin did not return object with "
271 				    "'result' or 'failure_message' fields.  "
272 				    "This is now deprecated and you should "
273 				    "return {'result': 'continue' } or "
274 				    "{'result': 'reject'} or "
275 				    "{'failure_message'... instead.");
276 		}
277 		return failmsg_incorrect_or_unknown(ctx, ld, hin);
278 	}
279 
280 	if (!json_to_number(buffer, t, &val))
281 		fatal("Invalid invoice_payment_hook failure_code: %.*s",
282 		      toks[0].end - toks[1].start, buffer);
283 
284 	if (val == WIRE_TEMPORARY_NODE_FAILURE)
285 		return towire_temporary_node_failure(ctx);
286 	if (val != WIRE_INCORRECT_OR_UNKNOWN_PAYMENT_DETAILS)
287 		log_broken(hin->key.channel->log,
288 			   "invoice_payment hook returned failcode %u,"
289 			   " changing to incorrect_or_unknown_payment_details",
290 			   val);
291 
292 	return failmsg_incorrect_or_unknown(ctx, ld, hin);
293 }
294 
295 static void
invoice_payment_hooks_done(struct invoice_payment_hook_payload * payload STEALS)296 invoice_payment_hooks_done(struct invoice_payment_hook_payload *payload STEALS)
297 {
298 	struct invoice invoice;
299 	struct lightningd *ld = payload->ld;
300 
301 	tal_del_destructor2(payload->set, invoice_payload_remove_set, payload);
302 	/* We want to free this, whatever happens. */
303 	tal_steal(tmpctx, payload);
304 
305 	/* If invoice gets paid meanwhile (plugin responds out-of-order?) then
306 	 * we can also fail */
307 	if (!wallet_invoice_find_by_label(ld->wallet, &invoice, payload->label)) {
308 		htlc_set_fail(payload->set, take(failmsg_incorrect_or_unknown(
309 							 NULL, ld, payload->set->htlcs[0])));
310 		return;
311 	}
312 
313 	/* Paid or expired in the meantime. */
314 	if (!wallet_invoice_resolve(ld->wallet, invoice, payload->msat)) {
315 		htlc_set_fail(payload->set, take(failmsg_incorrect_or_unknown(
316 							 NULL, ld, payload->set->htlcs[0])));
317 		return;
318 	}
319 
320 	log_info(ld->log, "Resolved invoice '%s' with amount %s in %zu htlcs",
321 		 payload->label->s,
322 		 type_to_string(tmpctx, struct amount_msat, &payload->msat),
323 		 tal_count(payload->set->htlcs));
324 	htlc_set_fulfill(payload->set, &payload->preimage);
325 
326 	notify_invoice_payment(ld, payload->msat, payload->preimage,
327 			       payload->label);
328 }
329 
330 static bool
invoice_payment_deserialize(struct invoice_payment_hook_payload * payload,const char * buffer,const jsmntok_t * toks)331 invoice_payment_deserialize(struct invoice_payment_hook_payload *payload,
332 			    const char *buffer,
333 			    const jsmntok_t *toks)
334 {
335 	struct lightningd *ld = payload->ld;
336 	const u8 *failmsg;
337 
338 	/* If peer dies or something, this can happen. */
339 	if (!payload->set) {
340 		log_debug(ld->log, "invoice '%s' paying htlc_in has gone!",
341 			  payload->label->s);
342 		return false;
343 	}
344 
345 	/* Did we have a hook result? */
346 	failmsg = hook_gives_failmsg(NULL, ld,
347 				     payload->set->htlcs[0], buffer, toks);
348 	if (failmsg) {
349 		htlc_set_fail(payload->set, take(failmsg));
350 		return false;
351 	}
352 	return true;
353 }
354 
355 REGISTER_PLUGIN_HOOK(invoice_payment,
356 		     invoice_payment_deserialize,
357 		     invoice_payment_hooks_done,
358 		     invoice_payment_serialize,
359 		     struct invoice_payment_hook_payload *);
360 
361 const struct invoice_details *
invoice_check_payment(const tal_t * ctx,struct lightningd * ld,const struct sha256 * payment_hash,const struct amount_msat msat,const struct secret * payment_secret)362 invoice_check_payment(const tal_t *ctx,
363 		      struct lightningd *ld,
364 		      const struct sha256 *payment_hash,
365 		      const struct amount_msat msat,
366 		      const struct secret *payment_secret)
367 {
368 	struct invoice invoice;
369 	const struct invoice_details *details;
370 
371 	/* BOLT #4:
372 	 *  - if the payment hash has already been paid:
373 	 *    - MAY treat the payment hash as unknown.
374 	 *    - MAY succeed in accepting the HTLC.
375 	 *...
376 	 *  - if the payment hash is unknown:
377 	 *    - MUST fail the HTLC.
378 	 *    - MUST return an `incorrect_or_unknown_payment_details` error.
379 	 */
380 	if (!wallet_invoice_find_unpaid(ld->wallet, &invoice, payment_hash)) {
381 		log_debug(ld->log, "Unknown paid invoice %s",
382 			  type_to_string(tmpctx, struct sha256, payment_hash));
383 		if (wallet_invoice_find_by_rhash(ld->wallet, &invoice, payment_hash)) {
384 			log_debug(ld->log, "ALREADY paid invoice %s",
385 				  type_to_string(tmpctx, struct sha256, payment_hash));
386 		}
387 		return NULL;
388 	}
389 
390 	details = wallet_invoice_details(ctx, ld->wallet, invoice);
391 
392 	/* BOLT #4:
393 	 *  - if the `payment_secret` doesn't match the expected value for that
394 	 *     `payment_hash`, or the `payment_secret` is required and is not
395 	 *     present:
396 	 *    - MUST fail the HTLC.
397 	 */
398 	if (feature_is_set(details->features, COMPULSORY_FEATURE(OPT_VAR_ONION))
399 	    && !payment_secret) {
400 		log_debug(ld->log, "Attept to pay %s without secret",
401 			  type_to_string(tmpctx, struct sha256, &details->rhash));
402 		return tal_free(details);
403 	}
404 
405 	if (payment_secret) {
406 		struct secret expected;
407 
408 		if (details->invstring && strstarts(details->invstring, "lni1"))
409 			invoice_secret_bolt12(ld, details->invstring, &expected);
410 		else
411 			invoice_secret(&details->r, &expected);
412 		if (!secret_eq_consttime(payment_secret, &expected)) {
413 			log_debug(ld->log, "Attept to pay %s with wrong secret",
414 				  type_to_string(tmpctx, struct sha256,
415 						 &details->rhash));
416 			return tal_free(details);
417 		}
418 	}
419 
420 	/* BOLT #4:
421 	 *
422 	 * An _intermediate hop_ MUST NOT, but the _final node_:
423 	 *...
424 	 *   - if the amount paid is less than the amount expected:
425 	 *     - MUST fail the HTLC.
426 	 */
427 	if (details->msat != NULL) {
428 		struct amount_msat twice;
429 
430 		if (amount_msat_less(msat, *details->msat)) {
431 			log_debug(ld->log, "Attept to pay %s with amount %s < %s",
432 				  type_to_string(tmpctx, struct sha256,
433 						 &details->rhash),
434 				  type_to_string(tmpctx, struct amount_msat, &msat),
435 				  type_to_string(tmpctx, struct amount_msat, details->msat));
436 			return tal_free(details);
437 		}
438 
439 		if (amount_msat_add(&twice, *details->msat, *details->msat)
440 		    && amount_msat_greater(msat, twice)) {
441 			log_debug(ld->log, "Attept to pay %s with amount %s > %s",
442 				  type_to_string(tmpctx, struct sha256,
443 						 &details->rhash),
444 				  type_to_string(tmpctx, struct amount_msat, &msat),
445 				  type_to_string(tmpctx, struct amount_msat, &twice));
446 			/* BOLT #4:
447 			 *
448 			 * - if the amount paid is more than twice the amount
449 			 *   expected:
450 			 *   - SHOULD fail the HTLC.
451 			 */
452 			return tal_free(details);
453 		}
454 	}
455 	return details;
456 }
457 
invoice_try_pay(struct lightningd * ld,struct htlc_set * set,const struct invoice_details * details)458 void invoice_try_pay(struct lightningd *ld,
459 		     struct htlc_set *set,
460 		     const struct invoice_details *details)
461 {
462 	struct invoice_payment_hook_payload *payload;
463 
464 	payload = tal(NULL, struct invoice_payment_hook_payload);
465 	payload->ld = ld;
466 	payload->label = tal_steal(payload, details->label);
467 	payload->msat = set->so_far;
468 	payload->preimage = details->r;
469 	payload->set = set;
470 	tal_add_destructor2(set, invoice_payload_remove_set, payload);
471 
472 	plugin_hook_call_invoice_payment(ld, payload);
473 }
474 
hsm_sign_b11(const u5 * u5bytes,const u8 * hrpu8,secp256k1_ecdsa_recoverable_signature * rsig,struct lightningd * ld)475 static bool hsm_sign_b11(const u5 *u5bytes,
476 			 const u8 *hrpu8,
477 			 secp256k1_ecdsa_recoverable_signature *rsig,
478 			 struct lightningd *ld)
479 {
480 	u8 *msg = towire_hsmd_sign_invoice(NULL, u5bytes, hrpu8);
481 
482 	if (!wire_sync_write(ld->hsm_fd, take(msg)))
483 		fatal("Could not write to HSM: %s", strerror(errno));
484 
485 	msg = wire_sync_read(tmpctx, ld->hsm_fd);
486         if (!fromwire_hsmd_sign_invoice_reply(msg, rsig))
487 		fatal("HSM gave bad sign_invoice_reply %s",
488 		      tal_hex(msg, msg));
489 
490 	return true;
491 }
492 
hsm_sign_b12_invoice(struct lightningd * ld,struct tlv_invoice * invoice)493 static void hsm_sign_b12_invoice(struct lightningd *ld,
494 				 struct tlv_invoice *invoice)
495 {
496 	struct sha256 merkle;
497 	u8 *msg;
498 
499 	assert(!invoice->signature);
500 
501  	merkle_tlv(invoice->fields, &merkle);
502 	msg = towire_hsmd_sign_bolt12(NULL, "invoice", "signature", &merkle, NULL);
503 
504 	if (!wire_sync_write(ld->hsm_fd, take(msg)))
505 		fatal("Could not write to HSM: %s", strerror(errno));
506 
507 	msg = wire_sync_read(tmpctx, ld->hsm_fd);
508 	invoice->signature = tal(invoice, struct bip340sig);
509         if (!fromwire_hsmd_sign_bolt12_reply(msg, invoice->signature))
510 		fatal("HSM gave bad sign_invoice_reply %s",
511 		      tal_hex(msg, msg));
512 }
513 
parse_fallback(struct command * cmd,const char * buffer,const jsmntok_t * fallback,const u8 ** fallback_script)514 static struct command_result *parse_fallback(struct command *cmd,
515 					     const char *buffer,
516 					     const jsmntok_t *fallback,
517 					     const u8 **fallback_script)
518 
519 {
520 	enum address_parse_result fallback_parse;
521 
522 	fallback_parse
523 		= json_to_address_scriptpubkey(cmd,
524 					       chainparams,
525 					       buffer, fallback,
526 					       fallback_script);
527 	if (fallback_parse == ADDRESS_PARSE_UNRECOGNIZED) {
528 		return command_fail(cmd, LIGHTNINGD,
529 				    "Fallback address not valid");
530 	} else if (fallback_parse == ADDRESS_PARSE_WRONG_NETWORK) {
531 		return command_fail(cmd, LIGHTNINGD,
532 				    "Fallback address does not match our network %s",
533 				    chainparams->network_name);
534 	}
535 	return NULL;
536 }
537 
538 /*
539  * From array of incoming channels [inchan], find suitable ones for
540  * a payment-to-us of [amount_needed], using criteria:
541  * 1. Channel's peer is known, in state CHANNELD_NORMAL and is online.
542  * 2. Channel's peer capacity to pay us is sufficient.
543  *
544  * Then use weighted reservoir sampling, which makes probing channel balances
545  * harder, to choose one channel from the set of suitable channels. It favors
546  * channels that have less balance on our side as fraction of their capacity.
547  */
select_inchan(const tal_t * ctx,struct lightningd * ld,struct amount_msat amount_needed,const struct routehint_candidate * candidates)548 static struct route_info **select_inchan(const tal_t *ctx,
549 					 struct lightningd *ld,
550 					 struct amount_msat amount_needed,
551 					 const struct routehint_candidate
552 					 *candidates)
553 {
554 	/* BOLT11 struct wants an array of arrays (can provide multiple routes) */
555 	struct route_info **r = NULL;
556 	double total_weight = 0.0;
557 
558 	/* Collect suitable channels and assign each a weight.  */
559 	for (size_t i = 0; i < tal_count(candidates); i++) {
560 		struct amount_msat excess, capacity;
561 		struct amount_sat cumulative_reserve;
562 		double excess_frac;
563 
564 		/* Does the peer have sufficient balance to pay us,
565 		 * even after having taken into account their reserve? */
566 		if (!amount_msat_sub(&excess, candidates[i].capacity,
567 				     amount_needed))
568 			continue;
569 
570 		/* Channel balance as seen by our node:
571 
572 		        |<----------------- capacity ----------------->|
573 		        .                                              .
574 		        .             |<------------------ their_msat -------------------->|
575 		        .             |                                .                   |
576 		        .             |<----- capacity_to_pay_us ----->|<- their_reserve ->|
577 		        .             |                                |                   |
578 		        .             |<- amount_needed --><- excess ->|                   |
579 		        .             |                                |                   |
580 		|-------|-------------|--------------------------------|-------------------|
581 		0       ^             ^                                ^                funding
582 		   our_reserve     our_msat	*/
583 
584 		/* Find capacity and calculate its excess fraction */
585 		if (!amount_sat_add(&cumulative_reserve,
586 				    candidates[i].c->our_config.channel_reserve,
587 				    candidates[i].c->channel_info.their_config.channel_reserve)
588 			|| !amount_sat_to_msat(&capacity, candidates[i].c->funding_sats)
589 			|| !amount_msat_sub_sat(&capacity, capacity, cumulative_reserve)) {
590 			log_broken(ld->log, "Channel %s capacity overflow!",
591 					type_to_string(tmpctx, struct short_channel_id, candidates[i].c->scid));
592 			continue;
593 		}
594 
595 		/* We don't want a 0 probability if 0 excess; it might be the
596 		 * only one!  So bump it by 1 msat */
597 		if (!amount_msat_add(&excess, excess, AMOUNT_MSAT(1))) {
598 			log_broken(ld->log, "Channel %s excess overflow!",
599 				   type_to_string(tmpctx,
600 						  struct short_channel_id,
601 						  candidates[i].c->scid));
602 			continue;
603 		}
604 		excess_frac = amount_msat_ratio(excess, capacity);
605 
606 		if (random_select(excess_frac, &total_weight)) {
607 			tal_free(r);
608 			r = tal_arr(ctx, struct route_info *, 1);
609 			r[0] = tal_dup(r, struct route_info, candidates[i].r);
610 		}
611 	}
612 
613 	return r;
614 }
615 
cmp_rr_number(const struct routehint_candidate * a,const struct routehint_candidate * b,void * unused)616 static int cmp_rr_number(const struct routehint_candidate *a,
617 			 const struct routehint_candidate *b,
618 			 void *unused)
619 {
620 	/* They're unique, so can't be equal */
621 	if (a->c->rr_number > b->c->rr_number)
622 		return 1;
623 	assert(a->c->rr_number < b->c->rr_number);
624 	return -1;
625 }
626 
627 /** select_inchan_mpp
628  *
629  * @brief fallback in case select_inchan cannot find a *single*
630  * channel capable of accepting the payment as a whole.
631  * Also the main routehint-selector if we are completely unpublished
632  * (i.e. all our channels are unpublished), since if we are completely
633  * unpublished then the payer cannot fall back to just directly routing
634  * to us.
635  */
select_inchan_mpp(const tal_t * ctx,struct lightningd * ld,struct amount_msat amount_needed,struct routehint_candidate * candidates)636 static struct route_info **select_inchan_mpp(const tal_t *ctx,
637 					     struct lightningd *ld,
638 					     struct amount_msat amount_needed,
639 					     struct routehint_candidate
640 					     *candidates)
641 {
642 	/* The total amount we have gathered for incoming channels.  */
643 	struct amount_msat gathered;
644 	/* Routehint array.  */
645 	struct route_info **routehints;
646 
647 	gathered = AMOUNT_MSAT(0);
648 	routehints = tal_arr(ctx, struct route_info *, 0);
649 
650 	/* Sort by rr_number, so we get fresh channels. */
651 	asort(candidates, tal_count(candidates), cmp_rr_number, NULL);
652 	for (size_t i = 0; i < tal_count(candidates); i++) {
653 		if (amount_msat_greater_eq(gathered, amount_needed))
654 			break;
655 
656 		/* Add to current routehints set.  */
657 		if (!amount_msat_add(&gathered, gathered, candidates[i].capacity)) {
658 			log_broken(ld->log,
659 				   "Gathered channel capacity overflow: "
660 				   "%s + %s",
661 				   type_to_string(tmpctx, struct amount_msat, &gathered),
662 				   type_to_string(tmpctx, struct amount_msat,
663 						  &candidates[i].capacity));
664 			continue;
665 		}
666 		tal_arr_expand(&routehints,
667 			       tal_dup(routehints, struct route_info,
668 				       candidates[i].r));
669 		/* Put to the back of the round-robin list */
670 		candidates[i].c->rr_number = ld->rr_counter++;
671 	}
672 
673 	return routehints;
674 }
675 
676 /* Encapsulating struct while we wait for gossipd to give us incoming channels */
677 struct chanhints {
678 	bool expose_all_private;
679 	struct short_channel_id *hints;
680 };
681 
682 struct invoice_info {
683 	struct command *cmd;
684 	struct preimage payment_preimage;
685 	struct bolt11 *b11;
686 	struct json_escape *label;
687 	struct chanhints *chanhints;
688 };
689 
690 /* Add routehints based on listincoming results: NULL means success. */
691 static struct command_result *
add_routehints(struct invoice_info * info,const char * buffer,const jsmntok_t * toks,bool * warning_mpp,bool * warning_capacity,bool * warning_deadends,bool * warning_offline,bool * warning_private_unused)692 add_routehints(struct invoice_info *info,
693 	       const char *buffer,
694 	       const jsmntok_t *toks,
695 	       bool *warning_mpp,
696 	       bool *warning_capacity,
697 	       bool *warning_deadends,
698 	       bool *warning_offline,
699 	       bool *warning_private_unused)
700 {
701 	const struct chanhints *chanhints = info->chanhints;
702 	bool node_unpublished;
703 	struct amount_msat avail_capacity, deadend_capacity, offline_capacity,
704 		private_capacity;
705 	struct routehint_candidate *candidates;
706 	struct amount_msat total, needed;
707 
708 	/* Dev code can force routes. */
709 	if (tal_count(info->b11->routes) != 0) {
710 	       *warning_mpp = *warning_capacity = *warning_deadends
711 		       = *warning_offline = *warning_private_unused
712 		       = false;
713 		return NULL;
714 	}
715 
716 	candidates = routehint_candidates(tmpctx, info->cmd->ld,
717 					  buffer, toks,
718 					  chanhints ? &chanhints->expose_all_private : NULL,
719 					  chanhints ? chanhints->hints : NULL,
720 					  &node_unpublished,
721 					  &avail_capacity,
722 					  &private_capacity,
723 					  &deadend_capacity,
724 					  &offline_capacity);
725 
726 	/* If they told us to use scids and we couldn't, fail. */
727 	if (tal_count(candidates) == 0
728 	    && chanhints && tal_count(chanhints->hints) != 0) {
729 		return command_fail(info->cmd,
730 				    INVOICE_HINTS_GAVE_NO_ROUTES,
731 				    "None of those hints were suitable local channels");
732 	}
733 
734 	needed = info->b11->msat ? *info->b11->msat : AMOUNT_MSAT(1);
735 
736 	/* If we are not completely unpublished, try with reservoir
737 	 * sampling first.
738 	 *
739 	 * Why do we not do this if we are completely unpublished?
740 	 * Because it is possible that multiple invoices will, by
741 	 * chance, select the same channel as routehint.
742 	 * This single channel might not be able to accept all the
743 	 * incoming payments on all the invoices generated.
744 	 * If we were published, that is fine because the payer can
745 	 * fall back to just attempting to route directly.
746 	 * But if we were unpublished, the only way for the payer to
747 	 * reach us would be via the routehints we provide, so we
748 	 * should make an effort to avoid overlapping incoming
749 	 * channels, which is done by select_inchan_mpp.
750 	 */
751 	if (!node_unpublished)
752 		info->b11->routes = select_inchan(info->b11,
753 						  info->cmd->ld,
754 						  needed,
755 						  candidates);
756 
757 	/* If we are completely unpublished, or if the above reservoir
758 	 * sampling fails, select channels by round-robin.  */
759 	if (tal_count(info->b11->routes) == 0) {
760 		info->b11->routes = select_inchan_mpp(info->b11,
761 						      info->cmd->ld,
762 						      needed,
763 						      candidates);
764 		*warning_mpp = (tal_count(info->b11->routes) > 1);
765 	} else {
766 		*warning_mpp = false;
767 	}
768 
769 	log_debug(info->cmd->ld->log, "needed = %s, avail_capacity = %s, private_capacity = %s, offline_capacity = %s, deadend_capacity = %s",
770 		  type_to_string(tmpctx, struct amount_msat, &needed),
771 		  type_to_string(tmpctx, struct amount_msat, &avail_capacity),
772 		  type_to_string(tmpctx, struct amount_msat, &private_capacity),
773 		  type_to_string(tmpctx, struct amount_msat, &offline_capacity),
774 		  type_to_string(tmpctx, struct amount_msat, &deadend_capacity));
775 
776 	if (!amount_msat_add(&total, avail_capacity, offline_capacity)
777 	    || !amount_msat_add(&total, total, deadend_capacity)
778 	    || !amount_msat_add(&total, total, private_capacity))
779 		fatal("Cannot add %s + %s + %s + %s",
780 		      type_to_string(tmpctx, struct amount_msat,
781 				     &avail_capacity),
782 		      type_to_string(tmpctx, struct amount_msat,
783 				     &offline_capacity),
784 		      type_to_string(tmpctx, struct amount_msat,
785 				     &deadend_capacity),
786 		      type_to_string(tmpctx, struct amount_msat,
787 				     &private_capacity));
788 
789 	/* If we literally didn't have capacity at all, warn. */
790 	*warning_capacity = amount_msat_greater_eq(needed, total);
791 
792 	/* We only warn about these if we didn't have capacity and
793 	 * they would have helped. */
794 	*warning_offline = false;
795 	*warning_deadends = false;
796 	*warning_private_unused = false;
797 	if (amount_msat_greater(needed, avail_capacity)) {
798 		struct amount_msat tot;
799 
800 		/* We didn't get enough: would offline have helped? */
801 		if (!amount_msat_add(&tot, avail_capacity, offline_capacity))
802 			abort();
803 		if (amount_msat_greater_eq(tot, needed)) {
804 			*warning_offline = true;
805 			goto done;
806 		}
807 
808 		/* Hmm, what about deadends? */
809 		if (!amount_msat_add(&tot, tot, deadend_capacity))
810 			abort();
811 		if (amount_msat_greater_eq(tot, needed)) {
812 			*warning_deadends = true;
813 			goto done;
814 		}
815 
816 		/* What about private channels? */
817 		if (!amount_msat_add(&tot, tot, private_capacity))
818 			abort();
819 		if (amount_msat_greater_eq(tot, needed)) {
820 			*warning_private_unused = true;
821 			goto done;
822 		}
823 	}
824 
825 done:
826 	return NULL;
827 }
828 
829 static struct command_result *
invoice_complete(struct invoice_info * info,bool warning_no_listincoming,bool warning_mpp,bool warning_capacity,bool warning_deadends,bool warning_offline,bool warning_private_unused)830 invoice_complete(struct invoice_info *info,
831 		 bool warning_no_listincoming,
832 		 bool warning_mpp,
833 		 bool warning_capacity,
834 		 bool warning_deadends,
835 		 bool warning_offline,
836 		 bool warning_private_unused)
837 {
838 	struct json_stream *response;
839 	struct invoice invoice;
840 	char *b11enc;
841 	const struct invoice_details *details;
842 	struct secret payment_secret;
843 	struct wallet *wallet = info->cmd->ld->wallet;
844 
845 	b11enc = bolt11_encode(info, info->b11, false,
846 			       hsm_sign_b11, info->cmd->ld);
847 
848 	/* Check duplicate preimage (unlikely unless they specified it!) */
849 	if (wallet_invoice_find_by_rhash(wallet,
850 					 &invoice, &info->b11->payment_hash)) {
851 		return command_fail(info->cmd,
852 				    INVOICE_PREIMAGE_ALREADY_EXISTS,
853 				    "preimage already used");
854 	}
855 
856 	if (!wallet_invoice_create(wallet,
857 				   &invoice,
858 				   info->b11->msat,
859 				   info->label,
860 				   info->b11->expiry,
861 				   b11enc,
862 				   info->b11->description,
863 				   info->b11->features,
864 				   &info->payment_preimage,
865 				   &info->b11->payment_hash,
866 				   NULL)) {
867 		return command_fail(info->cmd, INVOICE_LABEL_ALREADY_EXISTS,
868 				    "Duplicate label '%s'",
869 				    info->label->s);
870 	}
871 
872 	/* Get details */
873 	details = wallet_invoice_details(info, wallet, invoice);
874 
875 	response = json_stream_success(info->cmd);
876 	json_add_sha256(response, "payment_hash", &details->rhash);
877 	json_add_u64(response, "expires_at", details->expiry_time);
878 	json_add_string(response, "bolt11", details->invstring);
879 	invoice_secret(&details->r, &payment_secret);
880 	json_add_secret(response, "payment_secret", &payment_secret);
881 
882 	notify_invoice_creation(info->cmd->ld, info->b11->msat,
883 				info->payment_preimage, info->label);
884 
885 	if (warning_no_listincoming)
886 		json_add_string(response, "warning_listincoming",
887 				"No listincoming command available, cannot add routehints to invoice");
888 	if (warning_mpp)
889 		json_add_string(response, "warning_mpp",
890 				"The invoice is only payable by MPP-capable payers.");
891 	if (warning_capacity)
892 		json_add_string(response, "warning_capacity",
893 				"Insufficient incoming channel capacity to pay invoice");
894 
895 	if (warning_deadends)
896 		json_add_string(response, "warning_deadends",
897 				"Insufficient incoming capacity, once dead-end peers were excluded");
898 
899 	if (warning_offline)
900 		json_add_string(response, "warning_offline",
901 				"Insufficient incoming capacity, once offline peers were excluded");
902 
903 	if (warning_private_unused)
904 		json_add_string(response, "warning_private_unused",
905 				"Insufficient incoming capacity, once private channels were excluded (try exposeprivatechannels=true?)");
906 
907 	return command_success(info->cmd, response);
908 }
909 
910 /* Return from "listincoming". */
listincoming_done(const char * buffer,const jsmntok_t * toks,const jsmntok_t * idtok UNUSED,struct invoice_info * info)911 static void listincoming_done(const char *buffer,
912 			      const jsmntok_t *toks,
913 			      const jsmntok_t *idtok UNUSED,
914 			      struct invoice_info *info)
915 {
916 	struct lightningd *ld = info->cmd->ld;
917 	struct command_result *ret;
918 	bool warning_mpp, warning_capacity, warning_deadends, warning_offline, warning_private_unused;
919 
920 	ret = add_routehints(info, buffer, toks,
921 			     &warning_mpp,
922 			     &warning_capacity,
923 			     &warning_deadends,
924 			     &warning_offline,
925 			     &warning_private_unused);
926 	if (ret)
927 		return;
928 
929 	/* We're actually outside a db transaction here: spooky! */
930 	db_begin_transaction(ld->wallet->db);
931 	invoice_complete(info,
932 			 false,
933 			 warning_mpp,
934 			 warning_capacity,
935 			 warning_deadends,
936 			 warning_offline,
937 			 warning_private_unused);
938 	db_commit_transaction(ld->wallet->db);
939 }
940 
941 #if DEVELOPER
942 /* Since this is a dev-only option, we will crash if dev-routes is not
943  * an array-of-arrays-of-correct-items. */
unpack_route(const tal_t * ctx,const char * buffer,const jsmntok_t * routetok)944 static struct route_info *unpack_route(const tal_t *ctx,
945 				       const char *buffer,
946 				       const jsmntok_t *routetok)
947 {
948 	const jsmntok_t *t;
949 	size_t i;
950 	struct route_info *route = tal_arr(ctx, struct route_info, routetok->size);
951 
952 	json_for_each_arr(i, t, routetok) {
953 		const jsmntok_t *pubkey, *fee_base, *fee_prop, *scid, *cltv;
954 		struct route_info *r = &route[i];
955 		u32 cltv_u32;
956 
957 		pubkey = json_get_member(buffer, t, "id");
958 		scid = json_get_member(buffer, t, "short_channel_id");
959 		fee_base = json_get_member(buffer, t, "fee_base_msat");
960 		fee_prop = json_get_member(buffer, t,
961 					   "fee_proportional_millionths");
962 		cltv = json_get_member(buffer, t, "cltv_expiry_delta");
963 
964 		if (!json_to_node_id(buffer, pubkey, &r->pubkey)
965 		    || !json_to_short_channel_id(buffer, scid,
966 						 &r->short_channel_id)
967 		    || !json_to_number(buffer, fee_base, &r->fee_base_msat)
968 		    || !json_to_number(buffer, fee_prop,
969 				       &r->fee_proportional_millionths)
970 		    || !json_to_number(buffer, cltv, &cltv_u32))
971 			abort();
972 		/* We don't have a json_to_u16 */
973 		r->cltv_expiry_delta = cltv_u32;
974 	}
975 	return route;
976 }
977 
unpack_routes(const tal_t * ctx,const char * buffer,const jsmntok_t * routestok)978 static struct route_info **unpack_routes(const tal_t *ctx,
979 					 const char *buffer,
980 					 const jsmntok_t *routestok)
981 {
982 	struct route_info **routes;
983 	const jsmntok_t *t;
984 	size_t i;
985 
986 	if (!routestok)
987 		return NULL;
988 
989 	routes = tal_arr(ctx, struct route_info *, routestok->size);
990 	json_for_each_arr(i, t, routestok)
991 		routes[i] = unpack_route(routes, buffer, t);
992 
993 	return routes;
994 }
995 #endif /* DEVELOPER */
996 
param_positive_msat_or_any(struct command * cmd,const char * name,const char * buffer,const jsmntok_t * tok,struct amount_msat ** msat)997 static struct command_result *param_positive_msat_or_any(struct command *cmd,
998 							 const char *name,
999 							 const char *buffer,
1000 							 const jsmntok_t *tok,
1001 							 struct amount_msat **msat)
1002 {
1003 	if (json_tok_streq(buffer, tok, "any")) {
1004 		*msat = NULL;
1005 		return NULL;
1006 	}
1007 	*msat = tal(cmd, struct amount_msat);
1008 	if (parse_amount_msat(*msat, buffer + tok->start, tok->end - tok->start)
1009 	    && !amount_msat_eq(**msat, AMOUNT_MSAT(0)))
1010 		return NULL;
1011 
1012 	return command_fail_badparam(cmd, name, buffer, tok,
1013 				     "should be positive msat or 'any'");
1014 }
1015 
1016 /* Parse time with optional suffix, return seconds */
param_time(struct command * cmd,const char * name,const char * buffer,const jsmntok_t * tok,uint64_t ** secs)1017 static struct command_result *param_time(struct command *cmd, const char *name,
1018 					 const char *buffer,
1019 					 const jsmntok_t *tok,
1020 					 uint64_t **secs)
1021 {
1022 	/* We need to manipulate this, so make copy */
1023 	jsmntok_t timetok = *tok;
1024 	u64 mul;
1025 	char s;
1026 	struct {
1027 		char suffix;
1028 		u64 mul;
1029 	} suffixes[] = {
1030 		{ 's', 1 },
1031 		{ 'm', 60 },
1032 		{ 'h', 60*60 },
1033 		{ 'd', 24*60*60 },
1034 		{ 'w', 7*24*60*60 } };
1035 
1036 	mul = 1;
1037 	if (timetok.end == timetok.start)
1038 		s = '\0';
1039 	else
1040 		s = buffer[timetok.end - 1];
1041 	for (size_t i = 0; i < ARRAY_SIZE(suffixes); i++) {
1042 		if (s == suffixes[i].suffix) {
1043 			mul = suffixes[i].mul;
1044 			timetok.end--;
1045 			break;
1046 		}
1047 	}
1048 
1049 	*secs = tal(cmd, uint64_t);
1050 	if (json_to_u64(buffer, &timetok, *secs)) {
1051 		if (mul_overflows_u64(**secs, mul)) {
1052 			return command_fail_badparam(cmd, name, buffer, tok,
1053 						     "value too large");
1054 		}
1055 		**secs *= mul;
1056 		return NULL;
1057 	}
1058 
1059 	return command_fail_badparam(cmd, name, buffer, tok,
1060 				     "should be a number with optional {s,m,h,d,w} suffix");
1061 }
1062 
param_chanhints(struct command * cmd,const char * name,const char * buffer,const jsmntok_t * tok,struct chanhints ** chanhints)1063 static struct command_result *param_chanhints(struct command *cmd,
1064 					      const char *name,
1065 					      const char *buffer,
1066 					      const jsmntok_t *tok,
1067 					      struct chanhints **chanhints)
1068 {
1069 	bool boolhint;
1070 
1071 	*chanhints = tal(cmd, struct chanhints);
1072 
1073 	/* Could be simply "true" or "false" */
1074 	if (json_to_bool(buffer, tok, &boolhint)) {
1075 		(*chanhints)->expose_all_private = boolhint;
1076 		(*chanhints)->hints = NULL;
1077 		return NULL;
1078 	}
1079 
1080 	(*chanhints)->expose_all_private = true;
1081 	/* Could be a single short_channel_id or an array */
1082 	if (tok->type == JSMN_ARRAY) {
1083 		size_t i;
1084 		const jsmntok_t *t;
1085 
1086 		(*chanhints)->hints
1087 			= tal_arr(*chanhints, struct short_channel_id,
1088 				  tok->size);
1089 		json_for_each_arr(i, t, tok) {
1090 			if (!json_to_short_channel_id(buffer, t,
1091 						      &(*chanhints)->hints[i])) {
1092 				return command_fail_badparam(cmd, name, buffer, t,
1093 						    "should be a short channel id");
1094 			}
1095 		}
1096 		return NULL;
1097 	}
1098 
1099 	/* Otherwise should be a short_channel_id */
1100 	return param_short_channel_id(cmd, name, buffer, tok,
1101 				      &(*chanhints)->hints);
1102 }
1103 
param_preimage(struct command * cmd,const char * name,const char * buffer,const jsmntok_t * tok,struct preimage ** preimage)1104 static struct command_result *param_preimage(struct command *cmd,
1105 					     const char *name,
1106 					     const char *buffer,
1107 					     const jsmntok_t *tok,
1108 					     struct preimage **preimage)
1109 {
1110 	*preimage = tal(cmd, struct preimage);
1111 	if (!hex_decode(buffer + tok->start, tok->end - tok->start,
1112 			*preimage, sizeof(**preimage)))
1113 		return command_fail_badparam(cmd, "preimage",
1114 					     buffer, tok,
1115 					     "should be 64 hex digits");
1116 	return NULL;
1117 }
1118 
json_invoice(struct command * cmd,const char * buffer,const jsmntok_t * obj UNNEEDED,const jsmntok_t * params)1119 static struct command_result *json_invoice(struct command *cmd,
1120 					   const char *buffer,
1121 					   const jsmntok_t *obj UNNEEDED,
1122 					   const jsmntok_t *params)
1123 {
1124 	const jsmntok_t *fallbacks;
1125 	struct amount_msat *msatoshi_val;
1126 	struct invoice_info *info;
1127 	const char *desc_val;
1128 	const u8 **fallback_scripts = NULL;
1129 	u64 *expiry;
1130 	struct sha256 rhash;
1131 	struct secret payment_secret;
1132 	struct preimage *preimage;
1133 	u32 *cltv;
1134 	struct jsonrpc_request *req;
1135 	struct plugin *plugin;
1136 #if DEVELOPER
1137 	const jsmntok_t *routes;
1138 #endif
1139 
1140 	info = tal(cmd, struct invoice_info);
1141 	info->cmd = cmd;
1142 
1143 	if (!param(cmd, buffer, params,
1144 		   p_req("msatoshi", param_positive_msat_or_any, &msatoshi_val),
1145 		   p_req("label", param_label, &info->label),
1146 		   p_req("description", param_escaped_string, &desc_val),
1147 		   p_opt_def("expiry", param_time, &expiry, 3600*24*7),
1148 		   p_opt("fallbacks", param_array, &fallbacks),
1149 		   p_opt("preimage", param_preimage, &preimage),
1150 		   p_opt("exposeprivatechannels", param_chanhints,
1151 			 &info->chanhints),
1152 		   p_opt_def("cltv", param_number, &cltv,
1153 			     cmd->ld->config.cltv_final),
1154 #if DEVELOPER
1155 		   p_opt("dev-routes", param_array, &routes),
1156 #endif
1157 		   NULL))
1158 		return command_param_failed();
1159 
1160 	if (strlen(info->label->s) > INVOICE_MAX_LABEL_LEN) {
1161 		return command_fail(cmd, JSONRPC2_INVALID_PARAMS,
1162 				    "Label '%s' over %u bytes", info->label->s,
1163 				    INVOICE_MAX_LABEL_LEN);
1164 	}
1165 
1166 	if (strlen(desc_val) > BOLT11_FIELD_BYTE_LIMIT) {
1167 		return command_fail(cmd, JSONRPC2_INVALID_PARAMS,
1168 				    "Descriptions greater than %d bytes "
1169 				    "not yet supported "
1170 				    "(description length %zu)",
1171 				    BOLT11_FIELD_BYTE_LIMIT,
1172 				    strlen(desc_val));
1173 	}
1174 
1175 	if (fallbacks) {
1176 		size_t i;
1177 		const jsmntok_t *t;
1178 
1179 		fallback_scripts = tal_arr(cmd, const u8 *, fallbacks->size);
1180 		json_for_each_arr(i, t, fallbacks) {
1181 			struct command_result *r;
1182 
1183 			r = parse_fallback(cmd, buffer, t, &fallback_scripts[i]);
1184 			if (r)
1185 				return r;
1186 		}
1187 	}
1188 
1189 	if (preimage)
1190 		info->payment_preimage = *preimage;
1191 	else
1192 		/* Generate random secret preimage. */
1193 		randombytes_buf(&info->payment_preimage,
1194 				sizeof(info->payment_preimage));
1195 	/* Generate preimage hash. */
1196 	sha256(&rhash, &info->payment_preimage, sizeof(info->payment_preimage));
1197 	/* Generate payment secret. */
1198 	invoice_secret(&info->payment_preimage, &payment_secret);
1199 
1200 	info->b11 = new_bolt11(info, msatoshi_val);
1201 	info->b11->chain = chainparams;
1202 	info->b11->timestamp = time_now().ts.tv_sec;
1203 	info->b11->payment_hash = rhash;
1204 	info->b11->receiver_id = cmd->ld->id;
1205 	info->b11->min_final_cltv_expiry = *cltv;
1206 	info->b11->expiry = *expiry;
1207 	info->b11->description = tal_steal(info->b11, desc_val);
1208 	info->b11->description_hash = NULL;
1209 	info->b11->payment_secret = tal_dup(info->b11, struct secret,
1210 					    &payment_secret);
1211 	info->b11->features = tal_dup_talarr(info->b11, u8,
1212 					     cmd->ld->our_features
1213 					     ->bits[BOLT11_FEATURE]);
1214 
1215 #if DEVELOPER
1216 	info->b11->routes = unpack_routes(info->b11, buffer, routes);
1217 #else
1218 	info->b11->routes = NULL;
1219 #endif
1220 	if (fallback_scripts)
1221 		info->b11->fallbacks = tal_steal(info->b11, fallback_scripts);
1222 
1223 	req = jsonrpc_request_start(info, "listincoming",
1224 				    cmd->ld->log,
1225 				    NULL, listincoming_done,
1226 				    info);
1227 	jsonrpc_request_end(req);
1228 
1229 	plugin = find_plugin_for_command(cmd->ld, "listincoming");
1230 	if (plugin) {
1231 		plugin_request_send(plugin, req);
1232 		return command_still_pending(cmd);
1233 	}
1234 
1235 	/* We can't generate routehints without listincoming. */
1236 	return invoice_complete(info, true,
1237 				false, false, false, false, false);
1238 }
1239 
1240 static const struct json_command invoice_command = {
1241 	"invoice",
1242 	"payment",
1243 	json_invoice,
1244 	"Create an invoice for {msatoshi} with {label} "
1245 	"and {description} with optional {expiry} seconds "
1246 	"(default 1 week), optional {fallbacks} address list"
1247 	"(default empty list) and optional {preimage} "
1248 	"(default autogenerated)"};
1249 AUTODATA(json_command, &invoice_command);
1250 
json_add_invoices(struct json_stream * response,struct wallet * wallet,const struct json_escape * label,const struct sha256 * payment_hash,const struct sha256 * local_offer_id)1251 static void json_add_invoices(struct json_stream *response,
1252 			      struct wallet *wallet,
1253 			      const struct json_escape *label,
1254 			      const struct sha256 *payment_hash,
1255 			      const struct sha256 *local_offer_id)
1256 {
1257 	struct invoice_iterator it;
1258 	const struct invoice_details *details;
1259 	struct invoice invoice;
1260 
1261 	/* Don't iterate entire db if we're just after one. */
1262 	if (label) {
1263 		if (wallet_invoice_find_by_label(wallet, &invoice, label)) {
1264 			details =
1265 			    wallet_invoice_details(response, wallet, invoice);
1266 			json_object_start(response, NULL);
1267 			json_add_invoice(response, details);
1268 			json_object_end(response);
1269 		}
1270 	} else if (payment_hash != NULL) {
1271 		if (wallet_invoice_find_by_rhash(wallet, &invoice,
1272 						 payment_hash)) {
1273 			json_object_start(response, NULL);
1274 			json_add_invoice(
1275 			    response,
1276 			    wallet_invoice_details(response, wallet, invoice));
1277 			json_object_end(response);
1278 		}
1279 
1280 	} else {
1281 		memset(&it, 0, sizeof(it));
1282 		while (wallet_invoice_iterate(wallet, &it)) {
1283 			details = wallet_invoice_iterator_deref(response,
1284 								wallet, &it);
1285 			/* FIXME: db can filter this better! */
1286 			if (local_offer_id) {
1287 				if (!details->local_offer_id
1288 				    || !sha256_eq(local_offer_id,
1289 						  details->local_offer_id))
1290 					continue;
1291 			}
1292 			json_object_start(response, NULL);
1293 			json_add_invoice(response, details);
1294 			json_object_end(response);
1295 		}
1296 	}
1297 }
1298 
json_listinvoices(struct command * cmd,const char * buffer,const jsmntok_t * obj UNNEEDED,const jsmntok_t * params)1299 static struct command_result *json_listinvoices(struct command *cmd,
1300 						const char *buffer,
1301 						const jsmntok_t *obj UNNEEDED,
1302 						const jsmntok_t *params)
1303 {
1304 	struct json_escape *label;
1305 	struct json_stream *response;
1306 	struct wallet *wallet = cmd->ld->wallet;
1307 	const char *invstring;
1308 	struct sha256 *payment_hash, *offer_id;
1309 	char *fail;
1310 
1311 	if (!param(cmd, buffer, params,
1312 		   p_opt("label", param_label, &label),
1313 		   p_opt("invstring", param_string, &invstring),
1314 		   p_opt("payment_hash", param_sha256, &payment_hash),
1315 		   p_opt("offer_id", param_sha256, &offer_id),
1316 		   NULL))
1317 		return command_param_failed();
1318 
1319 	/* Yeah, I wasn't sure about this style either.  It's curt though! */
1320 	if (!!label + !!invstring + !!payment_hash + !!offer_id > 1) {
1321 		return command_fail(cmd, JSONRPC2_INVALID_PARAMS,
1322 				    "Can only specify one of"
1323 				    " {label}, {invstring}, {payment_hash}"
1324 				    " or {offer_id}");
1325 	}
1326 
1327 	/* Extract the payment_hash from the invoice. */
1328 	if (invstring != NULL) {
1329 		struct bolt11 *b11;
1330 		b11 = bolt11_decode(cmd, invstring, cmd->ld->our_features, NULL,
1331 				    NULL, &fail);
1332 		if (b11)
1333 			payment_hash = &b11->payment_hash;
1334 		else {
1335 			struct tlv_invoice *b12
1336 				= invoice_decode(tmpctx, invstring,
1337 						 strlen(invstring),
1338 						 cmd->ld->our_features, NULL,
1339 						 &fail);
1340 			if (!b12 || !b12->payment_hash) {
1341 				return command_fail(cmd, JSONRPC2_INVALID_PARAMS,
1342 						    "Invalid invstring");
1343 			}
1344 			payment_hash = b12->payment_hash;
1345 		}
1346 	}
1347 
1348 	response = json_stream_success(cmd);
1349 	json_array_start(response, "invoices");
1350 	json_add_invoices(response, wallet, label, payment_hash, offer_id);
1351 	json_array_end(response);
1352 	return command_success(cmd, response);
1353 }
1354 
1355 static const struct json_command listinvoices_command = {
1356 	"listinvoices",
1357 	"payment",
1358 	json_listinvoices,
1359 	"Show invoice matching {label}, {invstring}, {payment_hash} or {offerid} (or all, if "
1360 	"no query parameter specified)"
1361 };
1362 AUTODATA(json_command, &listinvoices_command);
1363 
json_delinvoice(struct command * cmd,const char * buffer,const jsmntok_t * obj UNNEEDED,const jsmntok_t * params)1364 static struct command_result *json_delinvoice(struct command *cmd,
1365 					      const char *buffer,
1366 					      const jsmntok_t *obj UNNEEDED,
1367 					      const jsmntok_t *params)
1368 {
1369 	struct invoice i;
1370 	const struct invoice_details *details;
1371 	struct json_stream *response;
1372 	const char *status, *actual_status;
1373 	struct json_escape *label;
1374 	struct wallet *wallet = cmd->ld->wallet;
1375 
1376 	if (!param(cmd, buffer, params,
1377 		   p_req("label", param_label, &label),
1378 		   p_req("status", param_string, &status),
1379 		   NULL))
1380 		return command_param_failed();
1381 
1382 	if (!wallet_invoice_find_by_label(wallet, &i, label)) {
1383 		return command_fail(cmd, INVOICE_NOT_FOUND, "Unknown invoice");
1384 	}
1385 
1386 	details = wallet_invoice_details(cmd, cmd->ld->wallet, i);
1387 
1388 	/* This is time-sensitive, so only call once; otherwise error msg
1389 	 * might not make sense if it changed! */
1390 	actual_status = invoice_status_str(details);
1391 	if (!streq(actual_status, status)) {
1392 		struct json_stream *js;
1393 		js = json_stream_fail(cmd, INVOICE_STATUS_UNEXPECTED,
1394 				      tal_fmt(tmpctx,
1395 					      "Invoice status is %s not %s",
1396 					      actual_status, status));
1397 		json_add_string(js, "current_status", actual_status);
1398 		json_add_string(js, "expected_status", status);
1399 		json_object_end(js);
1400 		return command_failed(cmd, js);
1401 	}
1402 
1403 	if (!wallet_invoice_delete(wallet, i)) {
1404 		log_broken(cmd->ld->log,
1405 			   "Error attempting to remove invoice %"PRIu64,
1406 			   i.id);
1407 		/* FIXME: allocate a generic DATABASE_ERROR code.  */
1408 		return command_fail(cmd, LIGHTNINGD, "Database error");
1409 	}
1410 
1411 	response = json_stream_success(cmd);
1412 	json_add_invoice(response, details);
1413 	return command_success(cmd, response);
1414 }
1415 
1416 static const struct json_command delinvoice_command = {
1417 	"delinvoice",
1418 	"payment",
1419 	json_delinvoice,
1420 	"Delete unpaid invoice {label} with {status}",
1421 };
1422 AUTODATA(json_command, &delinvoice_command);
1423 
json_delexpiredinvoice(struct command * cmd,const char * buffer,const jsmntok_t * obj UNNEEDED,const jsmntok_t * params)1424 static struct command_result *json_delexpiredinvoice(struct command *cmd,
1425 						     const char *buffer,
1426 						     const jsmntok_t *obj UNNEEDED,
1427 						     const jsmntok_t *params)
1428 {
1429 	u64 *maxexpirytime;
1430 
1431 	if (!param(cmd, buffer, params,
1432 		   p_opt_def("maxexpirytime", param_u64, &maxexpirytime,
1433 				 time_now().ts.tv_sec),
1434 		   NULL))
1435 		return command_param_failed();
1436 
1437 	wallet_invoice_delete_expired(cmd->ld->wallet, *maxexpirytime);
1438 
1439 	return command_success(cmd, json_stream_success(cmd));
1440 }
1441 static const struct json_command delexpiredinvoice_command = {
1442 	"delexpiredinvoice",
1443 	"payment",
1444 	json_delexpiredinvoice,
1445 	"Delete all expired invoices that expired as of given {maxexpirytime} (a UNIX epoch time), or all expired invoices if not specified"
1446 };
1447 AUTODATA(json_command, &delexpiredinvoice_command);
1448 
json_waitanyinvoice(struct command * cmd,const char * buffer,const jsmntok_t * obj UNNEEDED,const jsmntok_t * params)1449 static struct command_result *json_waitanyinvoice(struct command *cmd,
1450 						  const char *buffer,
1451 						  const jsmntok_t *obj UNNEEDED,
1452 						  const jsmntok_t *params)
1453 {
1454 	u64 *pay_index;
1455 	u64 *timeout;
1456 	struct wallet *wallet = cmd->ld->wallet;
1457 
1458 	if (!param(cmd, buffer, params,
1459 		   p_opt_def("lastpay_index", param_u64, &pay_index, 0),
1460 		   p_opt("timeout", &param_u64, &timeout),
1461 		   NULL))
1462 		return command_param_failed();
1463 
1464 	/*~ We allocate the timeout and the wallet-waitanyinvoice
1465 	 * in the cmd context, so whichever one manages to complete
1466 	 * the command first (and destroy the cmd context)
1467 	 * auto-cancels the other, is not tal amazing?
1468 	 */
1469 	if (timeout)
1470 		(void) new_reltimer(cmd->ld->timers, cmd,
1471 				    time_from_sec(*timeout),
1472 				    &wait_timed_out, cmd);
1473 
1474 	/* Set command as pending. We do not know if
1475 	 * wallet_invoice_waitany will return immediately
1476 	 * or not, so indicating pending is safest.  */
1477 	fixme_ignore(command_still_pending(cmd));
1478 
1479 	/* Find next paid invoice. */
1480 	wallet_invoice_waitany(cmd, wallet, *pay_index,
1481 			       &wait_on_invoice, (void*) cmd);
1482 
1483 	return command_its_complicated("wallet_invoice_waitany might complete"
1484 				       " immediately, but we also call it as a"
1485 				       " callback so plumbing through the return"
1486 				       " is non-trivial.");
1487 }
1488 
1489 
1490 static const struct json_command waitanyinvoice_command = {
1491 	"waitanyinvoice",
1492 	"payment",
1493 	json_waitanyinvoice,
1494 	"Wait for the next invoice to be paid, after {lastpay_index} (if supplied).  "
1495 	"If {timeout} seconds is reached while waiting, fail with an error."
1496 };
1497 AUTODATA(json_command, &waitanyinvoice_command);
1498 
1499 /* Wait for an incoming payment matching the `label` in the JSON
1500  * command.  This will either return immediately if the payment has
1501  * already been received or it may add the `cmd` to the list of
1502  * waiters, if the payment is still pending.
1503  */
json_waitinvoice(struct command * cmd,const char * buffer,const jsmntok_t * obj UNNEEDED,const jsmntok_t * params)1504 static struct command_result *json_waitinvoice(struct command *cmd,
1505 					       const char *buffer,
1506 					       const jsmntok_t *obj UNNEEDED,
1507 					       const jsmntok_t *params)
1508 {
1509 	struct invoice i;
1510 	const struct invoice_details *details;
1511 	struct wallet *wallet = cmd->ld->wallet;
1512 	struct json_escape *label;
1513 
1514 	if (!param(cmd, buffer, params,
1515 		   p_req("label", param_label, &label),
1516 		   NULL))
1517 		return command_param_failed();
1518 
1519 	if (!wallet_invoice_find_by_label(wallet, &i, label)) {
1520 		return command_fail(cmd, LIGHTNINGD, "Label not found");
1521 	}
1522 	details = wallet_invoice_details(cmd, cmd->ld->wallet, i);
1523 
1524 	/* If paid or expired return immediately */
1525 	if (details->state == PAID || details->state == EXPIRED) {
1526 		return tell_waiter(cmd, &i);
1527 	} else {
1528 		/* There is an unpaid one matching, let's wait... */
1529 		fixme_ignore(command_still_pending(cmd));
1530 		wallet_invoice_waitone(cmd, wallet, i,
1531 				       &wait_on_invoice, (void *) cmd);
1532 		return command_its_complicated("wallet_invoice_waitone might"
1533 					       " complete immediately");
1534 	}
1535 }
1536 
1537 static const struct json_command waitinvoice_command = {
1538 	"waitinvoice",
1539 	"payment",
1540 	json_waitinvoice,
1541 	"Wait for an incoming payment matching the invoice with {label}, or if the invoice expires"
1542 };
1543 AUTODATA(json_command, &waitinvoice_command);
1544 
json_decodepay(struct command * cmd,const char * buffer,const jsmntok_t * obj UNNEEDED,const jsmntok_t * params)1545 static struct command_result *json_decodepay(struct command *cmd,
1546 					     const char *buffer,
1547 					     const jsmntok_t *obj UNNEEDED,
1548 					     const jsmntok_t *params)
1549 {
1550 	struct bolt11 *b11;
1551 	struct json_stream *response;
1552 	const char *str, *desc;
1553 	char *fail;
1554 
1555 	if (!param(cmd, buffer, params,
1556 		   p_req("bolt11", param_string, &str),
1557 		   p_opt("description", param_string, &desc),
1558 		   NULL))
1559 		return command_param_failed();
1560 
1561 	b11 = bolt11_decode(cmd, str, cmd->ld->our_features, desc, NULL,
1562 			    &fail);
1563 
1564 	if (!b11) {
1565 		return command_fail(cmd, LIGHTNINGD, "Invalid bolt11: %s", fail);
1566 	}
1567 
1568 	response = json_stream_success(cmd);
1569 	json_add_bolt11(response, b11);
1570 	return command_success(cmd, response);
1571 }
1572 
1573 static const struct json_command decodepay_command = {
1574 	"decodepay",
1575 	"payment",
1576 	json_decodepay,
1577 	"Decode {bolt11}, using {description} if necessary"
1578 };
1579 AUTODATA(json_command, &decodepay_command);
1580 
1581 /* If we fail because it exists, we also return the clashing invoice */
fail_exists(struct command * cmd,const struct json_escape * label)1582 static struct command_result *fail_exists(struct command *cmd,
1583 					  const struct json_escape *label)
1584 {
1585 	struct json_stream *data;
1586 	struct invoice invoice;
1587 	struct wallet *wallet = cmd->ld->wallet;
1588 
1589 	data = json_stream_fail(cmd, INVOICE_LABEL_ALREADY_EXISTS,
1590 				"Duplicate label");
1591 	if (!wallet_invoice_find_by_label(wallet, &invoice, label))
1592 		fatal("Duplicate invoice %s not found any more?",
1593 		      label->s);
1594 
1595 	json_add_invoice(data, wallet_invoice_details(cmd, wallet, invoice));
1596 	json_object_end(data);
1597 
1598 	return command_failed(cmd, data);
1599 }
1600 
json_createinvoice(struct command * cmd,const char * buffer,const jsmntok_t * obj UNNEEDED,const jsmntok_t * params)1601 static struct command_result *json_createinvoice(struct command *cmd,
1602 						 const char *buffer,
1603 						 const jsmntok_t *obj UNNEEDED,
1604 						 const jsmntok_t *params)
1605 {
1606 	const char *invstring;
1607 	struct json_escape *label;
1608 	struct preimage *preimage;
1609 	struct invoice invoice;
1610 	struct sha256 payment_hash;
1611 	struct json_stream *response;
1612 	struct bolt11 *b11;
1613 	struct sha256 hash;
1614 	u5 *sig;
1615 	bool have_n;
1616 	char *fail;
1617 
1618 	if (!param(cmd, buffer, params,
1619 		   p_req("invstring", param_string, &invstring),
1620 		   p_req("label", param_label, &label),
1621 		   p_req("preimage", param_preimage, &preimage),
1622 		   NULL))
1623 		return command_param_failed();
1624 
1625 	sha256(&payment_hash, preimage, sizeof(*preimage));
1626 	b11 = bolt11_decode_nosig(cmd, invstring, cmd->ld->our_features,
1627 				  NULL, chainparams, &hash, &sig, &have_n,
1628 				  &fail);
1629 	if (b11) {
1630 		/* This adds the signature */
1631 		char *b11enc = bolt11_encode(cmd, b11, have_n,
1632 					     hsm_sign_b11, cmd->ld);
1633 
1634 		if (!b11->description)
1635 			return command_fail(cmd, JSONRPC2_INVALID_PARAMS,
1636 					    "Missing description in invoice");
1637 
1638 		if (!b11->expiry)
1639 			return command_fail(cmd, JSONRPC2_INVALID_PARAMS,
1640 					    "Missing expiry in invoice");
1641 
1642 		if (!sha256_eq(&payment_hash, &b11->payment_hash))
1643 			return command_fail(cmd, JSONRPC2_INVALID_PARAMS,
1644 					    "Incorrect preimage");
1645 
1646 		if (!wallet_invoice_create(cmd->ld->wallet,
1647 					   &invoice,
1648 					   b11->msat,
1649 					   label,
1650 					   b11->expiry,
1651 					   b11enc,
1652 					   b11->description,
1653 					   b11->features,
1654 					   preimage,
1655 					   &payment_hash,
1656 					   NULL))
1657 			return fail_exists(cmd, label);
1658 
1659 		notify_invoice_creation(cmd->ld, b11->msat, *preimage, label);
1660 	} else {
1661 		struct tlv_invoice *inv;
1662 		struct sha256 *local_offer_id;
1663 
1664 		inv = invoice_decode_nosig(cmd, invstring, strlen(invstring),
1665 					   cmd->ld->our_features, chainparams,
1666 					   &fail);
1667 		if (inv) {
1668 			char *b12enc;
1669 			struct amount_msat msat;
1670 			const char *desc;
1671 			u32 expiry;
1672 			enum offer_status status;
1673 
1674 			if (inv->signature)
1675 				return command_fail(cmd, JSONRPC2_INVALID_PARAMS,
1676 						    "invoice already signed");
1677 			hsm_sign_b12_invoice(cmd->ld, inv);
1678 			b12enc = invoice_encode(cmd, inv);
1679 
1680 			if (inv->offer_id
1681 			    && wallet_offer_find(tmpctx, cmd->ld->wallet,
1682 						 inv->offer_id, NULL, &status)) {
1683 				if (!offer_status_active(status))
1684 					return command_fail(cmd, INVOICE_OFFER_INACTIVE,
1685 							    "offer not active");
1686 				local_offer_id = inv->offer_id;
1687 			} else
1688 				local_offer_id = NULL;
1689 
1690 			if (inv->amount)
1691 				msat = amount_msat(*inv->amount);
1692 
1693 			if (inv->relative_expiry)
1694 				expiry = *inv->relative_expiry;
1695 			else
1696 				expiry = BOLT12_DEFAULT_REL_EXPIRY;
1697 
1698 			if (!inv->payment_hash)
1699 				return command_fail(cmd, JSONRPC2_INVALID_PARAMS,
1700 						    "Missing payment_hash in invoice");
1701 			if (!sha256_eq(&payment_hash, inv->payment_hash))
1702 				return command_fail(cmd, JSONRPC2_INVALID_PARAMS,
1703 					    "Incorrect preimage");
1704 
1705 			if (!inv->description)
1706 				return command_fail(cmd, JSONRPC2_INVALID_PARAMS,
1707 						    "Missing description in invoice");
1708 			desc = tal_strndup(cmd,
1709 					   cast_signed(char *, inv->description),
1710 					   tal_bytelen(inv->description));
1711 
1712 			if (!wallet_invoice_create(cmd->ld->wallet,
1713 						   &invoice,
1714 						   inv->amount ? &msat : NULL,
1715 						   label,
1716 						   expiry,
1717 						   b12enc,
1718 						   desc,
1719 						   inv->features,
1720 						   preimage,
1721 						   &payment_hash,
1722 						   local_offer_id))
1723 				return fail_exists(cmd, label);
1724 
1725 			notify_invoice_creation(cmd->ld,
1726 						inv->amount ? &msat : NULL,
1727 						*preimage, label);
1728 		} else
1729 			return command_fail(cmd, JSONRPC2_INVALID_PARAMS,
1730 					    "Unparsable invoice '%s': %s",
1731 					    invstring, fail);
1732 	}
1733 
1734 	response = json_stream_success(cmd);
1735 	json_add_invoice(response,
1736 			 wallet_invoice_details(cmd, cmd->ld->wallet, invoice));
1737 	return command_success(cmd, response);
1738 }
1739 
1740 static const struct json_command createinvoice_command = {
1741 	"createinvoice",
1742 	"payment",
1743 	json_createinvoice,
1744 	"Lowlevel command to sign and create invoice {invstring}, resolved with {preimage}, using unique {label}."
1745 };
1746 
1747 AUTODATA(json_command, &createinvoice_command);
1748