1 #include <bitcoin/chainparams.h>
2 #include <ccan/array_size/array_size.h>
3 #include <ccan/cast/cast.h>
4 #include <ccan/json_out/json_out.h>
5 #include <ccan/mem/mem.h>
6 #include <ccan/str/hex/hex.h>
7 #include <ccan/tal/str/str.h>
8 #include <common/blindedpath.h>
9 #include <common/bolt12_merkle.h>
10 #include <common/dijkstra.h>
11 #include <common/gossmap.h>
12 #include <common/json_stream.h>
13 #include <common/json_tok.h>
14 #include <common/memleak.h>
15 #include <common/overflows.h>
16 #include <common/route.h>
17 #include <common/type_to_string.h>
18 #include <errno.h>
19 #include <plugins/libplugin.h>
20 #include <secp256k1_schnorrsig.h>
21 #include <sodium.h>
22
23 static struct gossmap *global_gossmap;
24 static struct pubkey local_id;
25 static bool disable_connect = false;
26 static LIST_HEAD(sent_list);
27
28 struct sent {
29 /* We're in sent_invreqs, awaiting reply. */
30 struct list_node list;
31 /* The blinding factor used by reply (obsolete only) */
32 struct pubkey *reply_blinding;
33 /* The alias used by reply (modern only) */
34 struct pubkey *reply_alias;
35 /* The command which sent us. */
36 struct command *cmd;
37 /* The offer we are trying to get an invoice/payment for. */
38 struct tlv_offer *offer;
39 /* Path to use (including self) */
40 struct pubkey *path;
41
42 /* The invreq we sent, OR the invoice we sent */
43 struct tlv_invoice_request *invreq;
44
45 struct tlv_invoice *inv;
46 struct preimage inv_preimage;
47 struct json_escape *inv_label;
48 /* How long to wait for response before giving up. */
49 u32 wait_timeout;
50 };
51
find_sent_by_blinding(const struct pubkey * blinding)52 static struct sent *find_sent_by_blinding(const struct pubkey *blinding)
53 {
54 struct sent *i;
55
56 list_for_each(&sent_list, i, list) {
57 if (i->reply_blinding && pubkey_eq(i->reply_blinding, blinding))
58 return i;
59 }
60 return NULL;
61 }
62
find_sent_by_alias(const struct pubkey * alias)63 static struct sent *find_sent_by_alias(const struct pubkey *alias)
64 {
65 struct sent *i;
66
67 list_for_each(&sent_list, i, list) {
68 if (i->reply_alias && pubkey_eq(i->reply_alias, alias))
69 return i;
70 }
71 return NULL;
72 }
73
field_diff_(struct plugin * plugin,const tal_t * a,const tal_t * b,const char * fieldname)74 static const char *field_diff_(struct plugin *plugin,
75 const tal_t *a, const tal_t *b,
76 const char *fieldname)
77 {
78 /* One is set and the other isn't? */
79 if ((a == NULL) != (b == NULL)) {
80 plugin_log(plugin, LOG_DBG, "field_diff %s: a is %s, b is %s",
81 fieldname, a ? "set": "unset", b ? "set": "unset");
82 return fieldname;
83 }
84 if (!memeq(a, tal_bytelen(a), b, tal_bytelen(b))) {
85 plugin_log(plugin, LOG_DBG, "field_diff %s: a=%s, b=%s",
86 fieldname, tal_hex(tmpctx, a), tal_hex(tmpctx, b));
87 return fieldname;
88 }
89 return NULL;
90 }
91
92 #define field_diff(a, b, fieldname) \
93 field_diff_((cmd)->plugin, a->fieldname, b->fieldname, #fieldname)
94
95 /* Returns true if b is a with something appended. */
description_is_appended(const char * a,const char * b)96 static bool description_is_appended(const char *a, const char *b)
97 {
98 if (!a || !b)
99 return false;
100 if (tal_bytelen(b) < tal_bytelen(a))
101 return false;
102 return memeq(a, tal_bytelen(a), b, tal_bytelen(a));
103 }
104
105 /* Hack to suppress warnings when we finish a different command */
discard_result(struct command_result * ret)106 static void discard_result(struct command_result *ret)
107 {
108 }
109
110 /* Returns NULL if it wasn't an error. */
handle_error(struct command * cmd,struct sent * sent,const char * buf,const jsmntok_t * om)111 static struct command_result *handle_error(struct command *cmd,
112 struct sent *sent,
113 const char *buf,
114 const jsmntok_t *om)
115 {
116 const u8 *data;
117 size_t dlen;
118 struct tlv_invoice_error *err;
119 struct json_out *details;
120 const jsmntok_t *errtok;
121
122 errtok = json_get_member(buf, om, "invoice_error");
123 if (!errtok)
124 return NULL;
125
126 data = json_tok_bin_from_hex(cmd, buf, errtok);
127 dlen = tal_bytelen(data);
128 err = tlv_invoice_error_new(cmd);
129 details = json_out_new(cmd);
130
131 plugin_log(cmd->plugin, LOG_DBG, "errtok = %.*s",
132 json_tok_full_len(errtok),
133 json_tok_full(buf, errtok));
134 json_out_start(details, NULL, '{');
135 if (!fromwire_invoice_error(&data, &dlen, err)) {
136 plugin_log(cmd->plugin, LOG_DBG,
137 "Invalid invoice_error %.*s",
138 json_tok_full_len(errtok),
139 json_tok_full(buf, errtok));
140 json_out_addstr(details, "invoice_error_hex",
141 tal_strndup(tmpctx,
142 buf + errtok->start,
143 errtok->end - errtok->start));
144 } else {
145 char *failstr;
146
147 /* FIXME: with a bit more generate-wire.py support,
148 * we could have fieldnames and even types. */
149 if (err->erroneous_field)
150 json_out_add(details, "erroneous_field", false,
151 "%"PRIu64, *err->erroneous_field);
152 if (err->suggested_value)
153 json_out_addstr(details, "suggested_value",
154 tal_hex(tmpctx,
155 err->suggested_value));
156 /* If they don't include this, it'll be empty */
157 failstr = tal_strndup(tmpctx,
158 err->error,
159 tal_bytelen(err->error));
160 json_out_addstr(details, "error", failstr);
161 }
162 json_out_end(details, '}');
163 discard_result(command_done_err(sent->cmd,
164 OFFER_BAD_INVREQ_REPLY,
165 "Remote node sent failure message",
166 details));
167 return command_hook_success(cmd);
168 }
169
handle_invreq_response(struct command * cmd,struct sent * sent,const char * buf,const jsmntok_t * om)170 static struct command_result *handle_invreq_response(struct command *cmd,
171 struct sent *sent,
172 const char *buf,
173 const jsmntok_t *om)
174 {
175 const u8 *invbin;
176 const jsmntok_t *invtok;
177 size_t len;
178 struct tlv_invoice *inv;
179 struct sha256 merkle, sighash;
180 struct json_stream *out;
181 const char *badfield;
182 u64 *expected_amount;
183
184 invtok = json_get_member(buf, om, "invoice");
185 if (!invtok) {
186 plugin_log(cmd->plugin, LOG_UNUSUAL,
187 "Neither invoice nor invoice_request_failed in reply %.*s",
188 json_tok_full_len(om),
189 json_tok_full(buf, om));
190 discard_result(command_fail(sent->cmd,
191 OFFER_BAD_INVREQ_REPLY,
192 "Neither invoice nor invoice_request_failed in reply %.*s",
193 json_tok_full_len(om),
194 json_tok_full(buf, om)));
195 return command_hook_success(cmd);
196 }
197
198 invbin = json_tok_bin_from_hex(cmd, buf, invtok);
199 len = tal_bytelen(invbin);
200 inv = tlv_invoice_new(cmd);
201 if (!fromwire_invoice(&invbin, &len, inv)) {
202 badfield = "invoice";
203 goto badinv;
204 }
205
206 #if DEVELOPER
207 /* Raw send? Just fwd reply. */
208 if (!sent->offer) {
209 out = jsonrpc_stream_success(sent->cmd);
210 json_add_string(out, "invoice", invoice_encode(tmpctx, inv));
211 discard_result(command_finished(sent->cmd, out));
212 return command_hook_success(cmd);
213 }
214 #endif /* DEVELOPER */
215
216 /* BOLT-offers #12:
217 * - MUST reject the invoice unless `node_id` is equal to the offer.
218 */
219 if (!point32_eq(sent->offer->node_id, inv->node_id)) {
220 badfield = "node_id";
221 goto badinv;
222 }
223
224 /* BOLT-offers #12:
225 * - MUST reject the invoice if `signature` is not a valid signature
226 * using `node_id` as described in [Signature Calculation]
227 */
228 merkle_tlv(inv->fields, &merkle);
229 sighash_from_merkle("invoice", "signature", &merkle, &sighash);
230
231 if (!inv->signature
232 || secp256k1_schnorrsig_verify(secp256k1_ctx, inv->signature->u8,
233 sighash.u.u8, &inv->node_id->pubkey) != 1) {
234 badfield = "signature";
235 goto badinv;
236 }
237
238 /* BOLT-offers #12:
239 * - MUST reject the invoice if `msat` is not present.
240 */
241 if (!inv->amount) {
242 badfield = "amount";
243 goto badinv;
244 }
245
246 /* BOLT-offers #12:
247 * - MUST reject the invoice unless `offer_id` is equal to the id of the
248 * offer.
249 */
250 if ((badfield = field_diff(sent->invreq, inv, offer_id)))
251 goto badinv;
252
253 /* BOLT-offers #12:
254 * - if the invoice is a reply to an `invoice_request`:
255 *...
256 * - MUST reject the invoice unless the following fields are equal or
257 * unset exactly as they are in the `invoice_request:`
258 * - `quantity`
259 * - `recurrence_counter`
260 * - `recurrence_start`
261 * - `payer_key`
262 * - `payer_info`
263 */
264 if ((badfield = field_diff(sent->invreq, inv, quantity)))
265 goto badinv;
266 if ((badfield = field_diff(sent->invreq, inv, recurrence_counter)))
267 goto badinv;
268 if ((badfield = field_diff(sent->invreq, inv, recurrence_start)))
269 goto badinv;
270 if ((badfield = field_diff(sent->invreq, inv, payer_key)))
271 goto badinv;
272 if ((badfield = field_diff(sent->invreq, inv, payer_info)))
273 goto badinv;
274
275 /* Get the amount we expected: firstly, if that's what we sent,
276 * secondly, if specified in the invoice. */
277 if (sent->invreq->amount) {
278 expected_amount = tal_dup(tmpctx, u64, sent->invreq->amount);
279 } else if (sent->offer->amount && !sent->offer->currency) {
280 expected_amount = tal(tmpctx, u64);
281
282 *expected_amount = *sent->offer->amount;
283 if (sent->invreq->quantity) {
284 /* We should never have sent this! */
285 if (mul_overflows_u64(*expected_amount,
286 *sent->invreq->quantity)) {
287 badfield = "quantity overflow";
288 goto badinv;
289 }
290 *expected_amount *= *sent->invreq->quantity;
291 }
292 } else
293 expected_amount = NULL;
294
295 /* BOLT-offers #12:
296 * - if the offer contained `recurrence`:
297 * - MUST reject the invoice if `recurrence_basetime` is not set.
298 */
299 if (sent->invreq->recurrence_counter && !inv->recurrence_basetime) {
300 badfield = "recurrence_basetime";
301 goto badinv;
302 }
303
304 /* BOLT-offers #12:
305 * - SHOULD confirm authorization if the `description` does not exactly
306 * match the `offer`
307 * - MAY highlight if `description` has simply had a change appended.
308 */
309 /* We highlight these changes to the caller, for them to handle */
310 out = jsonrpc_stream_success(sent->cmd);
311 json_add_string(out, "invoice", invoice_encode(tmpctx, inv));
312 json_object_start(out, "changes");
313 if (field_diff(sent->offer, inv, description)) {
314 /* Did they simply append? */
315 if (description_is_appended(sent->offer->description,
316 inv->description)) {
317 size_t off = tal_bytelen(sent->offer->description);
318 json_add_stringn(out, "description_appended",
319 inv->description + off,
320 tal_bytelen(inv->description) - off);
321 } else if (!inv->description)
322 json_add_stringn(out, "description_removed",
323 sent->offer->description,
324 tal_bytelen(sent->offer->description));
325 else
326 json_add_stringn(out, "description",
327 inv->description,
328 tal_bytelen(inv->description));
329 }
330
331 /* BOLT-offers #12:
332 * - SHOULD confirm authorization if `issuer` does not exactly
333 * match the `offer`
334 */
335 if (field_diff(sent->offer, inv, issuer)) {
336 if (!inv->issuer)
337 json_add_stringn(out, "issuer_removed",
338 sent->offer->issuer,
339 tal_bytelen(sent->offer->issuer));
340 else
341 json_add_stringn(out, "issuer",
342 inv->issuer,
343 tal_bytelen(inv->issuer));
344 }
345 /* BOLT-offers #12:
346 * - SHOULD confirm authorization if `msat` is not within the amount
347 * range authorized.
348 */
349 /* We always tell them this unless it's trivial to calc and
350 * exactly as expected. */
351 if (!expected_amount || *inv->amount != *expected_amount)
352 json_add_amount_msat_only(out, "msat",
353 amount_msat(*inv->amount));
354 json_object_end(out);
355
356 /* We tell them about next period at this point, if any. */
357 if (sent->offer->recurrence) {
358 u64 next_counter, next_period_idx;
359 u64 paywindow_start, paywindow_end;
360
361 next_counter = *sent->invreq->recurrence_counter + 1;
362 if (sent->invreq->recurrence_start)
363 next_period_idx = *sent->invreq->recurrence_start
364 + next_counter;
365 else
366 next_period_idx = next_counter;
367
368 /* If this was the last, don't tell them about a next! */
369 if (!sent->offer->recurrence_limit
370 || next_period_idx <= *sent->offer->recurrence_limit) {
371 json_object_start(out, "next_period");
372 json_add_u64(out, "counter", next_counter);
373 json_add_u64(out, "starttime",
374 offer_period_start(*inv->recurrence_basetime,
375 next_period_idx,
376 sent->offer->recurrence));
377 json_add_u64(out, "endtime",
378 offer_period_start(*inv->recurrence_basetime,
379 next_period_idx + 1,
380 sent->offer->recurrence) - 1);
381
382 offer_period_paywindow(sent->offer->recurrence,
383 sent->offer->recurrence_paywindow,
384 sent->offer->recurrence_base,
385 *inv->recurrence_basetime,
386 next_period_idx,
387 &paywindow_start, &paywindow_end);
388 json_add_u64(out, "paywindow_start", paywindow_start);
389 json_add_u64(out, "paywindow_end", paywindow_end);
390 json_object_end(out);
391 }
392 }
393
394 discard_result(command_finished(sent->cmd, out));
395 return command_hook_success(cmd);
396
397 badinv:
398 plugin_log(cmd->plugin, LOG_DBG, "Failed invoice due to %s", badfield);
399 discard_result(command_fail(sent->cmd,
400 OFFER_BAD_INVREQ_REPLY,
401 "Incorrect %s field in %.*s",
402 badfield,
403 json_tok_full_len(invtok),
404 json_tok_full(buf, invtok)));
405 return command_hook_success(cmd);
406 }
407
recv_modern_onion_message(struct command * cmd,const char * buf,const jsmntok_t * params)408 static struct command_result *recv_modern_onion_message(struct command *cmd,
409 const char *buf,
410 const jsmntok_t *params)
411 {
412 const jsmntok_t *om, *aliastok;
413 struct sent *sent;
414 struct pubkey alias;
415 struct command_result *err;
416
417 om = json_get_member(buf, params, "onion_message");
418
419 aliastok = json_get_member(buf, om, "our_alias");
420 if (!aliastok || !json_to_pubkey(buf, aliastok, &alias))
421 return command_hook_success(cmd);
422
423 sent = find_sent_by_alias(&alias);
424 if (!sent) {
425 plugin_log(cmd->plugin, LOG_DBG,
426 "No match for modern onion %.*s",
427 json_tok_full_len(om),
428 json_tok_full(buf, om));
429 return command_hook_success(cmd);
430 }
431
432 plugin_log(cmd->plugin, LOG_DBG, "Received modern onion message: %.*s",
433 json_tok_full_len(params),
434 json_tok_full(buf, params));
435
436 err = handle_error(cmd, sent, buf, om);
437 if (err)
438 return err;
439
440 if (sent->invreq)
441 return handle_invreq_response(cmd, sent, buf, om);
442
443 return command_hook_success(cmd);
444 }
445
recv_obs_onion_message(struct command * cmd,const char * buf,const jsmntok_t * params)446 static struct command_result *recv_obs_onion_message(struct command *cmd,
447 const char *buf,
448 const jsmntok_t *params)
449 {
450 const jsmntok_t *om, *blindingtok;
451 bool obsolete;
452 struct sent *sent;
453 struct pubkey blinding;
454 struct command_result *err;
455
456 om = json_get_member(buf, params, "onion_message");
457 json_to_bool(buf, json_get_member(buf, om, "obsolete"), &obsolete);
458 if (!obsolete)
459 return command_hook_success(cmd);
460
461 blindingtok = json_get_member(buf, om, "blinding_in");
462 if (!blindingtok || !json_to_pubkey(buf, blindingtok, &blinding))
463 return command_hook_success(cmd);
464
465 sent = find_sent_by_blinding(&blinding);
466 if (!sent) {
467 plugin_log(cmd->plugin, LOG_DBG,
468 "No match for obsolete onion %.*s",
469 json_tok_full_len(om),
470 json_tok_full(buf, om));
471 return command_hook_success(cmd);
472 }
473
474 plugin_log(cmd->plugin, LOG_DBG, "Received onion message: %.*s",
475 json_tok_full_len(params),
476 json_tok_full(buf, params));
477
478 err = handle_error(cmd, sent, buf, om);
479 if (err)
480 return err;
481
482 if (sent->invreq)
483 return handle_invreq_response(cmd, sent, buf, om);
484
485 return command_hook_success(cmd);
486 }
487
destroy_sent(struct sent * sent)488 static void destroy_sent(struct sent *sent)
489 {
490 list_del(&sent->list);
491 }
492
493 /* We've received neither a reply nor a payment; return failure. */
timeout_sent_invreq(struct sent * sent)494 static void timeout_sent_invreq(struct sent *sent)
495 {
496 /* This will free sent! */
497 discard_result(command_fail(sent->cmd, OFFER_TIMEOUT,
498 "Timeout waiting for response"));
499 }
500
sendonionmsg_done(struct command * cmd,const char * buf UNUSED,const jsmntok_t * result UNUSED,struct sent * sent)501 static struct command_result *sendonionmsg_done(struct command *cmd,
502 const char *buf UNUSED,
503 const jsmntok_t *result UNUSED,
504 struct sent *sent)
505 {
506 tal_steal(cmd, plugin_timer(cmd->plugin,
507 time_from_sec(sent->wait_timeout),
508 timeout_sent_invreq, sent));
509 sent->cmd = cmd;
510 list_add_tail(&sent_list, &sent->list);
511 tal_add_destructor(sent, destroy_sent);
512 return command_still_pending(cmd);
513 }
514
init_gossmap(struct plugin * plugin)515 static void init_gossmap(struct plugin *plugin)
516 {
517 size_t num_cupdates_rejected;
518 global_gossmap
519 = notleak_with_children(gossmap_load(NULL,
520 GOSSIP_STORE_FILENAME,
521 &num_cupdates_rejected));
522 if (!global_gossmap)
523 plugin_err(plugin, "Could not load gossmap %s: %s",
524 GOSSIP_STORE_FILENAME, strerror(errno));
525 if (num_cupdates_rejected)
526 plugin_log(plugin, LOG_DBG,
527 "gossmap ignored %zu channel updates",
528 num_cupdates_rejected);
529 }
530
get_gossmap(struct plugin * plugin)531 static struct gossmap *get_gossmap(struct plugin *plugin)
532 {
533 if (!global_gossmap)
534 init_gossmap(plugin);
535 else
536 gossmap_refresh(global_gossmap, NULL);
537 return global_gossmap;
538 }
539
param_offer(struct command * cmd,const char * name,const char * buffer,const jsmntok_t * tok,struct tlv_offer ** offer)540 static struct command_result *param_offer(struct command *cmd,
541 const char *name,
542 const char *buffer,
543 const jsmntok_t *tok,
544 struct tlv_offer **offer)
545 {
546 char *fail;
547
548 /* BOLT-offers #12:
549 * - if `features` contains unknown _odd_ bits that are non-zero:
550 * - MUST ignore the bit.
551 * - if `features` contains unknown _even_ bits that are non-zero:
552 * - MUST NOT respond to the offer.
553 * - SHOULD indicate the unknown bit to the user.
554 */
555 /* BOLT-offers #12:
556 * - MUST NOT set or imply any `chain_hash` not set or implied by
557 * the offer.
558 */
559 *offer = offer_decode(cmd, buffer + tok->start, tok->end - tok->start,
560 plugin_feature_set(cmd->plugin), chainparams,
561 &fail);
562 if (!*offer)
563 return command_fail_badparam(cmd, name, buffer, tok,
564 tal_fmt(cmd,
565 "Unparsable offer: %s",
566 fail));
567
568 /* BOLT-offers #12:
569 *
570 * - if `node_id` or `description` is not set:
571 * - MUST NOT respond to the offer.
572 */
573 if (!(*offer)->node_id)
574 return command_fail_badparam(cmd, name, buffer, tok,
575 "Offer does not contain a node_id");
576
577 if (!(*offer)->description)
578 return command_fail_badparam(cmd, name, buffer, tok,
579 "Offer does not contain a description");
580 return NULL;
581 }
582
can_carry_onionmsg(const struct gossmap * map,const struct gossmap_chan * c,int dir,struct amount_msat amount UNUSED,void * arg UNUSED)583 static bool can_carry_onionmsg(const struct gossmap *map,
584 const struct gossmap_chan *c,
585 int dir,
586 struct amount_msat amount UNUSED,
587 void *arg UNUSED)
588 {
589 const struct gossmap_node *n;
590 /* Don't use it if either side says it's disabled */
591 if (!c->half[dir].enabled || !c->half[!dir].enabled)
592 return false;
593
594 /* Check features of recipient */
595 n = gossmap_nth_node(map, c, !dir);
596 /* 102/103 was the old EXPERIMENTAL feature bit: remove soon! */
597 return gossmap_node_get_feature(map, n, OPT_ONION_MESSAGES) != -1
598 || gossmap_node_get_feature(map, n, 102) != -1;
599 }
600
601 enum nodeid_parity {
602 nodeid_parity_even = SECP256K1_TAG_PUBKEY_EVEN,
603 nodeid_parity_odd = SECP256K1_TAG_PUBKEY_ODD,
604 nodeid_parity_unknown = 1,
605 };
606
node_parity(const struct gossmap * gossmap,const struct gossmap_node * node)607 static enum nodeid_parity node_parity(const struct gossmap *gossmap,
608 const struct gossmap_node *node)
609
610 {
611 struct node_id id;
612 gossmap_node_get_id(gossmap, node, &id);
613 return id.k[0];
614 }
615
node_id_from_point32(struct node_id * nid,const struct point32 * node32_id,enum nodeid_parity parity)616 static void node_id_from_point32(struct node_id *nid,
617 const struct point32 *node32_id,
618 enum nodeid_parity parity)
619 {
620 assert(parity == SECP256K1_TAG_PUBKEY_EVEN
621 || parity == SECP256K1_TAG_PUBKEY_ODD);
622 nid->k[0] = parity;
623 secp256k1_xonly_pubkey_serialize(secp256k1_ctx, nid->k+1,
624 &node32_id->pubkey);
625 }
626
627 /* Create path to node which can carry onion messages (including
628 * self); if it can't find one, returns NULL. Fills in nodeid_parity
629 * for 33rd nodeid byte. */
path_to_node(const tal_t * ctx,struct plugin * plugin,const struct point32 * node32_id,enum nodeid_parity * parity)630 static struct pubkey *path_to_node(const tal_t *ctx,
631 struct plugin *plugin,
632 const struct point32 *node32_id,
633 enum nodeid_parity *parity)
634 {
635 struct route_hop *r;
636 const struct dijkstra *dij;
637 const struct gossmap_node *src;
638 const struct gossmap_node *dst;
639 struct node_id dstid, local_nodeid;
640 struct pubkey *nodes;
641 struct gossmap *gossmap = get_gossmap(plugin);
642
643 /* We try both parities. */
644 *parity = nodeid_parity_even;
645 node_id_from_point32(&dstid, node32_id, *parity);
646 dst = gossmap_find_node(gossmap, &dstid);
647 if (!dst) {
648 *parity = nodeid_parity_odd;
649 node_id_from_point32(&dstid, node32_id, *parity);
650 dst = gossmap_find_node(gossmap, &dstid);
651 if (!dst) {
652 *parity = nodeid_parity_unknown;
653 return NULL;
654 }
655 }
656
657 *parity = node_parity(gossmap, dst);
658
659 /* If we don't exist in gossip, routing can't happen. */
660 node_id_from_pubkey(&local_nodeid, &local_id);
661 src = gossmap_find_node(gossmap, &local_nodeid);
662 if (!src)
663 return NULL;
664
665 dij = dijkstra(tmpctx, gossmap, dst, AMOUNT_MSAT(0), 0,
666 can_carry_onionmsg, route_score_shorter, NULL);
667
668 r = route_from_dijkstra(tmpctx, gossmap, dij, src, AMOUNT_MSAT(0), 0);
669 if (!r)
670 return NULL;
671
672 nodes = tal_arr(ctx, struct pubkey, tal_count(r) + 1);
673 nodes[0] = local_id;
674 for (size_t i = 0; i < tal_count(r); i++) {
675 if (!pubkey_from_node_id(&nodes[i+1], &r[i].node_id)) {
676 plugin_err(plugin, "Could not convert nodeid %s",
677 type_to_string(tmpctx, struct node_id,
678 &r[i].node_id));
679 }
680 }
681 return nodes;
682 }
683
684 /* Marshal arguments for sending obsolete and modern onion messages */
685 struct sending {
686 struct sent *sent;
687 const char *msgfield;
688 const u8 *msgval;
689 struct command_result *(*done)(struct command *cmd,
690 const char *buf UNUSED,
691 const jsmntok_t *result UNUSED,
692 struct sent *sent);
693 };
694
695 /* Send this message down this path, with blinded reply path */
send_obs_message(struct command * cmd,const char * buf UNUSED,const jsmntok_t * result UNUSED,struct sending * sending)696 static struct command_result *send_obs_message(struct command *cmd,
697 const char *buf UNUSED,
698 const jsmntok_t *result UNUSED,
699 struct sending *sending)
700 {
701 struct pubkey *backwards;
702 struct onionmsg_path **path;
703 struct pubkey blinding;
704 struct out_req *req;
705 struct sent *sent = sending->sent;
706
707 /* FIXME: Maybe we should allow this? */
708 if (tal_count(sent->path) == 1)
709 return command_fail(cmd, PAY_ROUTE_NOT_FOUND,
710 "Refusing to talk to ourselves");
711
712 /* Reverse path is offset by one. */
713 backwards = tal_arr(tmpctx, struct pubkey, tal_count(sent->path) - 1);
714 for (size_t i = 0; i < tal_count(backwards); i++)
715 backwards[tal_count(backwards)-1-i] = sent->path[i];
716
717 /* Ok, now make reply for onion_message */
718 sent->reply_blinding = tal(sent, struct pubkey);
719 path = make_blindedpath(tmpctx, backwards, &blinding,
720 sent->reply_blinding);
721
722 req = jsonrpc_request_start(cmd->plugin, cmd, "sendobsonionmessage",
723 sending->done,
724 forward_error,
725 sent);
726 json_array_start(req->js, "hops");
727 for (size_t i = 1; i < tal_count(sent->path); i++) {
728 json_object_start(req->js, NULL);
729 json_add_pubkey(req->js, "id", &sent->path[i]);
730 if (i == tal_count(sent->path) - 1)
731 json_add_hex_talarr(req->js,
732 sending->msgfield, sending->msgval);
733 json_object_end(req->js);
734 }
735 json_array_end(req->js);
736
737 json_object_start(req->js, "reply_path");
738 json_add_pubkey(req->js, "blinding", &blinding);
739 json_array_start(req->js, "path");
740 for (size_t i = 0; i < tal_count(path); i++) {
741 json_object_start(req->js, NULL);
742 json_add_pubkey(req->js, "id", &path[i]->node_id);
743 if (path[i]->enctlv)
744 json_add_hex_talarr(req->js, "enctlv", path[i]->enctlv);
745 json_object_end(req->js);
746 }
747 json_array_end(req->js);
748 json_object_end(req->js);
749 return send_outreq(cmd->plugin, req);
750 }
751
752 static struct command_result *
send_modern_message(struct command * cmd,struct tlv_onionmsg_payload_reply_path * reply_path,struct sending * sending)753 send_modern_message(struct command *cmd,
754 struct tlv_onionmsg_payload_reply_path *reply_path,
755 struct sending *sending)
756 {
757 struct sent *sent = sending->sent;
758 struct privkey blinding_iter;
759 struct pubkey fwd_blinding, *node_alias;
760 size_t nhops = tal_count(sent->path);
761 struct tlv_onionmsg_payload **payloads;
762 struct out_req *req;
763
764 /* Now create enctlvs for *forward* path. */
765 randombytes_buf(&blinding_iter, sizeof(blinding_iter));
766 if (!pubkey_from_privkey(&blinding_iter, &fwd_blinding))
767 return command_fail(cmd, LIGHTNINGD,
768 "Could not convert blinding %s to pubkey!",
769 type_to_string(tmpctx, struct privkey,
770 &blinding_iter));
771
772 /* We overallocate: this node (0) doesn't have payload or alias */
773 payloads = tal_arr(cmd, struct tlv_onionmsg_payload *, nhops);
774 node_alias = tal_arr(cmd, struct pubkey, nhops);
775
776 for (size_t i = 1; i < nhops - 1; i++) {
777 payloads[i] = tlv_onionmsg_payload_new(payloads);
778 payloads[i]->enctlv = create_enctlv(payloads[i],
779 &blinding_iter,
780 &sent->path[i],
781 &sent->path[i+1],
782 /* FIXME: Pad? */
783 0,
784 NULL,
785 &blinding_iter,
786 &node_alias[i]);
787 }
788 /* Final payload contains the actual data. */
789 payloads[nhops-1] = tlv_onionmsg_payload_new(payloads);
790
791 /* We don't include enctlv in final, but it gives us final alias */
792 if (!create_final_enctlv(tmpctx, &blinding_iter, &sent->path[nhops-1],
793 /* FIXME: Pad? */ 0,
794 NULL,
795 &node_alias[nhops-1])) {
796 /* Should not happen! */
797 return command_fail(cmd, LIGHTNINGD,
798 "Could create final enctlv");
799 }
800
801 /* FIXME: This interface is a string for sendobsonionmessage! */
802 if (streq(sending->msgfield, "invoice_request")) {
803 payloads[nhops-1]->invoice_request
804 = cast_const(u8 *, sending->msgval);
805 } else {
806 assert(streq(sending->msgfield, "invoice"));
807 payloads[nhops-1]->invoice
808 = cast_const(u8 *, sending->msgval);
809 }
810 payloads[nhops-1]->reply_path = reply_path;
811
812 req = jsonrpc_request_start(cmd->plugin, cmd, "sendonionmessage",
813 /* We try obsolete msg next */
814 send_obs_message,
815 forward_error,
816 sending);
817 json_add_pubkey(req->js, "first_id", &sent->path[1]);
818 json_add_pubkey(req->js, "blinding", &fwd_blinding);
819 json_array_start(req->js, "hops");
820 for (size_t i = 1; i < nhops; i++) {
821 u8 *tlv;
822 json_object_start(req->js, NULL);
823 json_add_pubkey(req->js, "id", &node_alias[i]);
824 tlv = tal_arr(tmpctx, u8, 0);
825 towire_onionmsg_payload(&tlv, payloads[i]);
826 json_add_hex_talarr(req->js, "tlv", tlv);
827 json_object_end(req->js);
828 }
829 json_array_end(req->js);
830 return send_outreq(cmd->plugin, req);
831 }
832
833 /* Lightningd gives us reply path, since we don't know secret to put
834 * in final so it will recognize it. */
use_reply_path(struct command * cmd,const char * buf,const jsmntok_t * result,struct sending * sending)835 static struct command_result *use_reply_path(struct command *cmd,
836 const char *buf,
837 const jsmntok_t *result,
838 struct sending *sending)
839 {
840 struct tlv_onionmsg_payload_reply_path *rpath;
841
842 rpath = json_to_reply_path(cmd, buf,
843 json_get_member(buf, result, "blindedpath"));
844 if (!rpath)
845 plugin_err(cmd->plugin,
846 "could not parse reply path %.*s?",
847 json_tok_full_len(result),
848 json_tok_full(buf, result));
849
850 /* Remember our alias we used so we can recognize reply */
851 sending->sent->reply_alias
852 = tal_dup(sending->sent, struct pubkey,
853 &rpath->path[tal_count(rpath->path)-1]->node_id);
854
855 return send_modern_message(cmd, rpath, sending);
856 }
857
make_reply_path(struct command * cmd,struct sending * sending)858 static struct command_result *make_reply_path(struct command *cmd,
859 struct sending *sending)
860 {
861 struct out_req *req;
862 size_t nhops = tal_count(sending->sent->path);
863
864 /* FIXME: Maybe we should allow this? */
865 if (tal_count(sending->sent->path) == 1)
866 return command_fail(cmd, PAY_ROUTE_NOT_FOUND,
867 "Refusing to talk to ourselves");
868
869 req = jsonrpc_request_start(cmd->plugin, cmd, "blindedpath",
870 use_reply_path,
871 forward_error,
872 sending);
873
874 /* FIXME: Could create an independent reply path, not just
875 * reverse existing. */
876 json_array_start(req->js, "ids");
877 for (int i = nhops - 2; i >= 0; i--)
878 json_add_pubkey(req->js, NULL, &sending->sent->path[i]);
879 json_array_end(req->js);
880 return send_outreq(cmd->plugin, req);
881 }
882
send_message(struct command * cmd,struct sent * sent,const char * msgfield TAKES,const u8 * msgval TAKES,struct command_result * (* done)(struct command * cmd,const char * buf UNUSED,const jsmntok_t * result UNUSED,struct sent * sent))883 static struct command_result *send_message(struct command *cmd,
884 struct sent *sent,
885 const char *msgfield TAKES,
886 const u8 *msgval TAKES,
887 struct command_result *(*done)
888 (struct command *cmd,
889 const char *buf UNUSED,
890 const jsmntok_t *result UNUSED,
891 struct sent *sent))
892 {
893 struct sending *sending = tal(cmd, struct sending);
894 sending->sent = sent;
895 sending->msgfield = tal_strdup(sending, msgfield);
896 sending->msgval = tal_dup_talarr(sending, u8, msgval);
897 sending->done = done;
898
899 return make_reply_path(cmd, sending);
900 }
901
902 /* We've received neither a reply nor a payment; return failure. */
timeout_sent_inv(struct sent * sent)903 static void timeout_sent_inv(struct sent *sent)
904 {
905 struct json_out *details = json_out_new(sent);
906
907 json_out_start(details, NULL, '{');
908 json_out_addstr(details, "invstring", invoice_encode(tmpctx, sent->inv));
909 json_out_end(details, '}');
910
911 /* This will free sent! */
912 discard_result(command_done_err(sent->cmd, OFFER_TIMEOUT,
913 "Failed: timeout waiting for response",
914 details));
915 }
916
prepare_inv_timeout(struct command * cmd,const char * buf UNUSED,const jsmntok_t * result UNUSED,struct sent * sent)917 static struct command_result *prepare_inv_timeout(struct command *cmd,
918 const char *buf UNUSED,
919 const jsmntok_t *result UNUSED,
920 struct sent *sent)
921 {
922 tal_steal(cmd, plugin_timer(cmd->plugin,
923 time_from_sec(sent->wait_timeout),
924 timeout_sent_inv, sent));
925 return sendonionmsg_done(cmd, buf, result, sent);
926 }
927
928 /* We've connected (if we tried), so send the invreq. */
929 static struct command_result *
sendinvreq_after_connect(struct command * cmd,const char * buf UNUSED,const jsmntok_t * result UNUSED,struct sent * sent)930 sendinvreq_after_connect(struct command *cmd,
931 const char *buf UNUSED,
932 const jsmntok_t *result UNUSED,
933 struct sent *sent)
934 {
935 u8 *rawinvreq = tal_arr(tmpctx, u8, 0);
936 towire_invoice_request(&rawinvreq, sent->invreq);
937
938 return send_message(cmd, sent, "invoice_request", rawinvreq,
939 sendonionmsg_done);
940 }
941
942 struct connect_attempt {
943 struct node_id node_id;
944 struct command_result *(*cb)(struct command *command,
945 const char *buf,
946 const jsmntok_t *result,
947 struct sent *sent);
948 struct sent *sent;
949 };
950
connected(struct command * command,const char * buf,const jsmntok_t * result,struct connect_attempt * ca)951 static struct command_result *connected(struct command *command,
952 const char *buf,
953 const jsmntok_t *result,
954 struct connect_attempt *ca)
955 {
956 return ca->cb(command, buf, result, ca->sent);
957 }
958
connect_failed(struct command * command,const char * buf,const jsmntok_t * result,struct connect_attempt * ca)959 static struct command_result *connect_failed(struct command *command,
960 const char *buf,
961 const jsmntok_t *result,
962 struct connect_attempt *ca)
963 {
964 return command_done_err(command, OFFER_ROUTE_NOT_FOUND,
965 "Failed: could not route, could not connect",
966 NULL);
967 }
968
969 /* Offers contain only a 32-byte id. If we can't find the address, we
970 * don't know if it's 02 or 03, so we try both. If we're here, we
971 * failed 02. */
try_other_parity(struct command * cmd,const char * buf,const jsmntok_t * result,struct connect_attempt * ca)972 static struct command_result *try_other_parity(struct command *cmd,
973 const char *buf,
974 const jsmntok_t *result,
975 struct connect_attempt *ca)
976 {
977 struct out_req *req;
978
979 /* Flip parity */
980 ca->node_id.k[0] = SECP256K1_TAG_PUBKEY_ODD;
981 /* Path is us -> them, so they're second entry */
982 if (!pubkey_from_node_id(&ca->sent->path[1], &ca->node_id)) {
983 /* Should not happen!
984 * Pieter Wuille points out:
985 * y^2 = x^3 + 7 mod p
986 * negating y doesn’t change the left hand side
987 */
988 return command_done_err(cmd, LIGHTNINGD,
989 "Failed: could not convert inverted pubkey?",
990 NULL);
991 }
992 req = jsonrpc_request_start(cmd->plugin, cmd, "connect", connected,
993 connect_failed, ca);
994 json_add_node_id(req->js, "id", &ca->node_id);
995 return send_outreq(cmd->plugin, req);
996 }
997
998 /* We can't find a route, so we're going to try to connect, then just blast it
999 * to them. */
1000 static struct command_result *
connect_direct(struct command * cmd,const struct point32 * dst,enum nodeid_parity parity,struct command_result * (* cb)(struct command * command,const char * buf,const jsmntok_t * result,struct sent * sent),struct sent * sent)1001 connect_direct(struct command *cmd,
1002 const struct point32 *dst,
1003 enum nodeid_parity parity,
1004 struct command_result *(*cb)(struct command *command,
1005 const char *buf,
1006 const jsmntok_t *result,
1007 struct sent *sent),
1008 struct sent *sent)
1009 {
1010 struct out_req *req;
1011 struct connect_attempt *ca = tal(cmd, struct connect_attempt);
1012
1013 ca->cb = cb;
1014 ca->sent = sent;
1015
1016 if (parity == nodeid_parity_unknown) {
1017 plugin_notify_message(cmd, LOG_INFORM,
1018 "Cannot find route, trying connect to 02/03%s directly",
1019 type_to_string(tmpctx, struct point32, dst));
1020 /* Try even first. */
1021 node_id_from_point32(&ca->node_id, dst, SECP256K1_TAG_PUBKEY_EVEN);
1022 } else {
1023 plugin_notify_message(cmd, LOG_INFORM,
1024 "Cannot find route, trying connect to %02x%s directly",
1025 parity,
1026 type_to_string(tmpctx, struct point32, dst));
1027 node_id_from_point32(&ca->node_id, dst, parity);
1028 }
1029
1030 /* Make a direct path -> dst. */
1031 sent->path = tal_arr(sent, struct pubkey, 2);
1032 sent->path[0] = local_id;
1033 if (!pubkey_from_node_id(&sent->path[1], &ca->node_id)) {
1034 /* Should not happen! */
1035 return command_done_err(cmd, LIGHTNINGD,
1036 "Failed: could not convert to pubkey?",
1037 NULL);
1038 }
1039
1040 if (disable_connect) {
1041 /* FIXME: This means we will fail if parity is wrong! */
1042 plugin_notify_message(cmd, LOG_UNUSUAL,
1043 "Cannot find route, but"
1044 " fetchplugin-noconnect set:"
1045 " trying direct anyway to %s",
1046 type_to_string(tmpctx, struct point32,
1047 dst));
1048 return cb(cmd, NULL, NULL, sent);
1049 }
1050
1051 req = jsonrpc_request_start(cmd->plugin, cmd, "connect", connected,
1052 parity == nodeid_parity_unknown ?
1053 try_other_parity : connect_failed, ca);
1054 json_add_node_id(req->js, "id", &ca->node_id);
1055 return send_outreq(cmd->plugin, req);
1056 }
1057
invreq_done(struct command * cmd,const char * buf,const jsmntok_t * result,struct sent * sent)1058 static struct command_result *invreq_done(struct command *cmd,
1059 const char *buf,
1060 const jsmntok_t *result,
1061 struct sent *sent)
1062 {
1063 const jsmntok_t *t;
1064 char *fail;
1065 enum nodeid_parity parity;
1066
1067 /* Get invoice request */
1068 t = json_get_member(buf, result, "bolt12");
1069 if (!t)
1070 return command_fail(cmd, LIGHTNINGD,
1071 "Missing bolt12 %.*s",
1072 json_tok_full_len(result),
1073 json_tok_full(buf, result));
1074
1075 plugin_log(cmd->plugin, LOG_DBG,
1076 "invoice_request: %.*s",
1077 json_tok_full_len(t),
1078 json_tok_full(buf, t));
1079
1080 sent->inv = NULL;
1081 sent->invreq = invrequest_decode(sent,
1082 buf + t->start,
1083 t->end - t->start,
1084 plugin_feature_set(cmd->plugin),
1085 chainparams,
1086 &fail);
1087 if (!sent->invreq)
1088 return command_fail(cmd, LIGHTNINGD,
1089 "Invalid invoice_request %.*s: %s",
1090 json_tok_full_len(t),
1091 json_tok_full(buf, t),
1092 fail);
1093
1094 /* Now that's given us the previous base, check this is an OK time
1095 * to request an invoice. */
1096 if (sent->invreq->recurrence_counter) {
1097 u64 *base;
1098 const jsmntok_t *pbtok;
1099 u64 period_idx = *sent->invreq->recurrence_counter;
1100
1101 if (sent->invreq->recurrence_start)
1102 period_idx += *sent->invreq->recurrence_start;
1103
1104 /* BOLT-offers #12:
1105 * - if the offer contained `recurrence_limit`:
1106 * - MUST NOT send an `invoice_request` for a period greater
1107 * than `max_period`
1108 */
1109 if (sent->offer->recurrence_limit
1110 && period_idx > *sent->offer->recurrence_limit)
1111 return command_fail(cmd, LIGHTNINGD,
1112 "Can't send invreq for period %"
1113 PRIu64" (limit %u)",
1114 period_idx,
1115 *sent->offer->recurrence_limit);
1116
1117 /* BOLT-offers #12:
1118 * - SHOULD NOT send an `invoice_request` for a period which has
1119 * already passed.
1120 */
1121 /* If there's no recurrence_base, we need a previous payment
1122 * for this: fortunately createinvoicerequest does that
1123 * lookup. */
1124 pbtok = json_get_member(buf, result, "previous_basetime");
1125 if (pbtok) {
1126 base = tal(tmpctx, u64);
1127 json_to_u64(buf, pbtok, base);
1128 } else if (sent->offer->recurrence_base)
1129 base = &sent->offer->recurrence_base->basetime;
1130 else {
1131 /* happens with *recurrence_base == 0 */
1132 assert(*sent->invreq->recurrence_counter == 0);
1133 base = NULL;
1134 }
1135
1136 if (base) {
1137 u64 period_start, period_end, now = time_now().ts.tv_sec;
1138 offer_period_paywindow(sent->offer->recurrence,
1139 sent->offer->recurrence_paywindow,
1140 sent->offer->recurrence_base,
1141 *base, period_idx,
1142 &period_start, &period_end);
1143 if (now < period_start)
1144 return command_fail(cmd, LIGHTNINGD,
1145 "Too early: can't send until time %"
1146 PRIu64" (in %"PRIu64" secs)",
1147 period_start,
1148 period_start - now);
1149 if (now > period_end)
1150 return command_fail(cmd, LIGHTNINGD,
1151 "Too late: expired time %"
1152 PRIu64" (%"PRIu64" secs ago)",
1153 period_end,
1154 now - period_end);
1155 }
1156 }
1157
1158 sent->path = path_to_node(sent, cmd->plugin,
1159 sent->offer->node_id,
1160 &parity);
1161 if (!sent->path)
1162 return connect_direct(cmd, sent->offer->node_id, parity,
1163 sendinvreq_after_connect, sent);
1164
1165 return sendinvreq_after_connect(cmd, NULL, NULL, sent);
1166 }
1167
1168 /* If they hand us the payer secret, we sign it directly, bypassing checks
1169 * about periods etc. */
1170 static struct command_result *
force_payer_secret(struct command * cmd,struct sent * sent,struct tlv_invoice_request * invreq,const struct secret * payer_secret)1171 force_payer_secret(struct command *cmd,
1172 struct sent *sent,
1173 struct tlv_invoice_request *invreq,
1174 const struct secret *payer_secret)
1175 {
1176 struct sha256 merkle, sha;
1177 enum nodeid_parity parity;
1178 secp256k1_keypair kp;
1179 u8 *msg;
1180 const u8 *p;
1181 size_t len;
1182
1183 if (secp256k1_keypair_create(secp256k1_ctx, &kp, payer_secret->data) != 1)
1184 return command_fail(cmd, LIGHTNINGD, "Bad payer_secret");
1185
1186 invreq->payer_key = tal(invreq, struct point32);
1187 /* Docs say this only happens if arguments are invalid! */
1188 if (secp256k1_keypair_xonly_pub(secp256k1_ctx,
1189 &invreq->payer_key->pubkey, NULL,
1190 &kp) != 1)
1191 plugin_err(cmd->plugin,
1192 "secp256k1_keypair_pub failed on %s?",
1193 type_to_string(tmpctx, struct secret, payer_secret));
1194
1195 /* Linearize populates ->fields */
1196 msg = tal_arr(tmpctx, u8, 0);
1197 towire_invoice_request(&msg, invreq);
1198 p = msg;
1199 len = tal_bytelen(msg);
1200 sent->invreq = tlv_invoice_request_new(cmd);
1201 if (!fromwire_invoice_request(&p, &len, sent->invreq))
1202 plugin_err(cmd->plugin,
1203 "Could not remarshall invreq %s", tal_hex(tmpctx, msg));
1204
1205 merkle_tlv(sent->invreq->fields, &merkle);
1206 sighash_from_merkle("invoice_request", "payer_signature", &merkle, &sha);
1207
1208 sent->invreq->payer_signature = tal(invreq, struct bip340sig);
1209 if (!secp256k1_schnorrsig_sign(secp256k1_ctx,
1210 sent->invreq->payer_signature->u8,
1211 sha.u.u8,
1212 &kp,
1213 NULL, NULL)) {
1214 return command_fail(cmd, LIGHTNINGD,
1215 "Failed to sign with payer_secret");
1216 }
1217
1218 sent->path = path_to_node(sent, cmd->plugin,
1219 sent->offer->node_id,
1220 &parity);
1221 if (!sent->path)
1222 return connect_direct(cmd, sent->offer->node_id, parity,
1223 sendinvreq_after_connect, sent);
1224
1225 return sendinvreq_after_connect(cmd, NULL, NULL, sent);
1226 }
1227
1228 /* Fetches an invoice for this offer, and makes sure it corresponds. */
json_fetchinvoice(struct command * cmd,const char * buffer,const jsmntok_t * params)1229 static struct command_result *json_fetchinvoice(struct command *cmd,
1230 const char *buffer,
1231 const jsmntok_t *params)
1232 {
1233 struct amount_msat *msat;
1234 const char *rec_label, *payer_note;
1235 struct out_req *req;
1236 struct tlv_invoice_request *invreq;
1237 struct sent *sent = tal(cmd, struct sent);
1238 struct secret *payer_secret = NULL;
1239 u32 *timeout;
1240
1241 invreq = tlv_invoice_request_new(sent);
1242 if (!param(cmd, buffer, params,
1243 p_req("offer", param_offer, &sent->offer),
1244 p_opt("msatoshi", param_msat, &msat),
1245 p_opt("quantity", param_u64, &invreq->quantity),
1246 p_opt("recurrence_counter", param_number,
1247 &invreq->recurrence_counter),
1248 p_opt("recurrence_start", param_number,
1249 &invreq->recurrence_start),
1250 p_opt("recurrence_label", param_string, &rec_label),
1251 p_opt_def("timeout", param_number, &timeout, 60),
1252 p_opt("payer_note", param_string, &payer_note),
1253 #if DEVELOPER
1254 p_opt("payer_secret", param_secret, &payer_secret),
1255 #endif
1256 NULL))
1257 return command_param_failed();
1258
1259 sent->wait_timeout = *timeout;
1260
1261 /* BOLT-offers #12:
1262 * - MUST set `offer_id` to the Merkle root of the offer as described
1263 * in [Signature Calculation](#signature-calculation).
1264 */
1265 invreq->offer_id = tal(invreq, struct sha256);
1266 merkle_tlv(sent->offer->fields, invreq->offer_id);
1267
1268 /* Check if they are trying to send us money. */
1269 if (sent->offer->send_invoice)
1270 return command_fail(cmd, JSONRPC2_INVALID_PARAMS,
1271 "Offer wants an invoice, not invoice_request");
1272
1273 /* BOLT-offers #12:
1274 * - SHOULD not respond to an offer if the current time is after
1275 * `absolute_expiry`.
1276 */
1277 if (sent->offer->absolute_expiry
1278 && time_now().ts.tv_sec > *sent->offer->absolute_expiry)
1279 return command_fail(cmd, OFFER_EXPIRED, "Offer expired");
1280
1281 /* BOLT-offers #12:
1282 * - if the offer did not specify `amount`:
1283 * - MUST specify `amount`.`msat` in multiples of the minimum
1284 * lightning-payable unit (e.g. milli-satoshis for bitcoin) for the
1285 * first `chains` entry.
1286 * - otherwise:
1287 * - MAY omit `amount`.
1288 * - if it sets `amount`:
1289 * - MUST specify `amount`.`msat` as greater or equal to amount
1290 * expected by the offer (before any proportional period amount).
1291 */
1292 if (sent->offer->amount) {
1293 /* FIXME: Check after quantity? */
1294 if (msat) {
1295 invreq->amount = tal_dup(invreq, u64,
1296 &msat->millisatoshis); /* Raw: tu64 */
1297 }
1298 } else {
1299 if (!msat)
1300 return command_fail(cmd, JSONRPC2_INVALID_PARAMS,
1301 "msatoshi parameter required");
1302 invreq->amount = tal_dup(invreq, u64,
1303 &msat->millisatoshis); /* Raw: tu64 */
1304 }
1305
1306 /* BOLT-offers #12:
1307 * - if the offer had a `quantity_min` or `quantity_max` field:
1308 * - MUST set `quantity`
1309 * - MUST set it within that (inclusive) range.
1310 * - otherwise:
1311 * - MUST NOT set `quantity`
1312 */
1313 if (sent->offer->quantity_min || sent->offer->quantity_max) {
1314 if (!invreq->quantity)
1315 return command_fail(cmd, JSONRPC2_INVALID_PARAMS,
1316 "quantity parameter required");
1317 if (sent->offer->quantity_min
1318 && *invreq->quantity < *sent->offer->quantity_min)
1319 return command_fail(cmd, JSONRPC2_INVALID_PARAMS,
1320 "quantity must be >= %"PRIu64,
1321 *sent->offer->quantity_min);
1322 if (sent->offer->quantity_max
1323 && *invreq->quantity > *sent->offer->quantity_max)
1324 return command_fail(cmd, JSONRPC2_INVALID_PARAMS,
1325 "quantity must be <= %"PRIu64,
1326 *sent->offer->quantity_max);
1327 } else {
1328 if (invreq->quantity)
1329 return command_fail(cmd, JSONRPC2_INVALID_PARAMS,
1330 "quantity parameter unnecessary");
1331 }
1332
1333 /* BOLT-offers #12:
1334 * - if the offer contained `recurrence`:
1335 */
1336 if (sent->offer->recurrence) {
1337 /* BOLT-offers #12:
1338 * - for the initial request:
1339 *...
1340 * - MUST set `recurrence_counter` `counter` to 0.
1341 */
1342 /* BOLT-offers #12:
1343 * - for any successive requests:
1344 *...
1345 * - MUST set `recurrence_counter` `counter` to one greater
1346 * than the highest-paid invoice.
1347 */
1348 if (!invreq->recurrence_counter)
1349 return command_fail(cmd, JSONRPC2_INVALID_PARAMS,
1350 "needs recurrence_counter");
1351
1352 /* BOLT-offers #12:
1353 * - if the offer contained `recurrence_base` with
1354 * `start_any_period` non-zero:
1355 * - MUST include `recurrence_start`
1356 *...
1357 * - otherwise:
1358 * - MUST NOT include `recurrence_start`
1359 */
1360 if (sent->offer->recurrence_base
1361 && sent->offer->recurrence_base->start_any_period) {
1362 if (!invreq->recurrence_start)
1363 return command_fail(cmd, JSONRPC2_INVALID_PARAMS,
1364 "needs recurrence_start");
1365 } else {
1366 if (invreq->recurrence_start)
1367 return command_fail(cmd, JSONRPC2_INVALID_PARAMS,
1368 "unnecessary recurrence_start");
1369 }
1370
1371 /* recurrence_label uniquely identifies this series of
1372 * payments (unless they supply secret themselves)! */
1373 if (!rec_label && !payer_secret)
1374 return command_fail(cmd, JSONRPC2_INVALID_PARAMS,
1375 "needs recurrence_label");
1376 } else {
1377 /* BOLT-offers #12:
1378 * - otherwise:
1379 * - MUST NOT set `recurrence_counter`.
1380 * - MUST NOT set `recurrence_start`
1381 */
1382 if (invreq->recurrence_counter)
1383 return command_fail(cmd, JSONRPC2_INVALID_PARAMS,
1384 "unnecessary recurrence_counter");
1385 if (invreq->recurrence_start)
1386 return command_fail(cmd, JSONRPC2_INVALID_PARAMS,
1387 "unnecessary recurrence_start");
1388 }
1389
1390 /* BOLT-offers #12:
1391 *
1392 * - if the chain for the invoice is not solely bitcoin:
1393 * - MUST specify `chains` the offer is valid for.
1394 * - otherwise:
1395 * - the bitcoin chain is implied as the first and only entry.
1396 */
1397 if (!streq(chainparams->network_name, "bitcoin")) {
1398 if (deprecated_apis) {
1399 invreq->chains = tal_arr(invreq, struct bitcoin_blkid, 1);
1400 invreq->chains[0] = chainparams->genesis_blockhash;
1401 }
1402 invreq->chain = tal_dup(invreq, struct bitcoin_blkid,
1403 &chainparams->genesis_blockhash);
1404 }
1405
1406 invreq->features
1407 = plugin_feature_set(cmd->plugin)->bits[BOLT11_FEATURE];
1408
1409 /* invreq->payer_note is not a nul-terminated string! */
1410 if (payer_note)
1411 invreq->payer_note = tal_dup_arr(invreq, utf8,
1412 payer_note, strlen(payer_note),
1413 0);
1414
1415 /* They can provide a secret, and we don't assume it's our job
1416 * to pay. */
1417 if (payer_secret)
1418 return force_payer_secret(cmd, sent, invreq, payer_secret);
1419
1420 /* Make the invoice request (fills in payer_key and payer_info) */
1421 req = jsonrpc_request_start(cmd->plugin, cmd, "createinvoicerequest",
1422 &invreq_done,
1423 &forward_error,
1424 sent);
1425 json_add_string(req->js, "bolt12", invrequest_encode(tmpctx, invreq));
1426 if (rec_label)
1427 json_add_string(req->js, "recurrence_label", rec_label);
1428 return send_outreq(cmd->plugin, req);
1429 }
1430
1431 /* FIXME: Using a hook here is not ideal: technically it doesn't mean
1432 * it's actually hit the db! But using waitinvoice is also suboptimal
1433 * because we don't have libplugin infra to cancel a pending req (and I
1434 * want to rewrite our wait* API anyway) */
invoice_payment(struct command * cmd,const char * buf,const jsmntok_t * params)1435 static struct command_result *invoice_payment(struct command *cmd,
1436 const char *buf,
1437 const jsmntok_t *params)
1438 {
1439 struct sent *i;
1440 const jsmntok_t *ptok, *preimagetok, *msattok;
1441 struct preimage preimage;
1442 struct amount_msat msat;
1443
1444 ptok = json_get_member(buf, params, "payment");
1445 preimagetok = json_get_member(buf, ptok, "preimage");
1446 msattok = json_get_member(buf, ptok, "msat");
1447 if (!preimagetok || !msattok)
1448 plugin_err(cmd->plugin,
1449 "Invalid invoice_payment %.*s",
1450 json_tok_full_len(params),
1451 json_tok_full(buf, params));
1452
1453 hex_decode(buf + preimagetok->start,
1454 preimagetok->end - preimagetok->start,
1455 &preimage, sizeof(preimage));
1456 json_to_msat(buf, msattok, &msat);
1457
1458 list_for_each(&sent_list, i, list) {
1459 struct out_req *req;
1460
1461 if (!i->inv)
1462 continue;
1463 if (!preimage_eq(&preimage, &i->inv_preimage))
1464 continue;
1465
1466 /* It was paid! Success. Return as per waitinvoice. */
1467 req = jsonrpc_request_start(cmd->plugin, i->cmd, "waitinvoice",
1468 &forward_result,
1469 &forward_error,
1470 i);
1471 json_add_escaped_string(req->js, "label", i->inv_label);
1472 discard_result(send_outreq(cmd->plugin, req));
1473 break;
1474 }
1475 return command_hook_success(cmd);
1476 }
1477
1478 /* We've connected (if we tried), so send the invoice. */
1479 static struct command_result *
sendinvoice_after_connect(struct command * cmd,const char * buf UNUSED,const jsmntok_t * result UNUSED,struct sent * sent)1480 sendinvoice_after_connect(struct command *cmd,
1481 const char *buf UNUSED,
1482 const jsmntok_t *result UNUSED,
1483 struct sent *sent)
1484 {
1485 u8 *rawinv = tal_arr(tmpctx, u8, 0);
1486 towire_invoice(&rawinv, sent->inv);
1487 return send_message(cmd, sent, "invoice", rawinv, prepare_inv_timeout);
1488 }
1489
createinvoice_done(struct command * cmd,const char * buf,const jsmntok_t * result,struct sent * sent)1490 static struct command_result *createinvoice_done(struct command *cmd,
1491 const char *buf,
1492 const jsmntok_t *result,
1493 struct sent *sent)
1494 {
1495 const jsmntok_t *invtok = json_get_member(buf, result, "bolt12");
1496 char *fail;
1497 enum nodeid_parity parity;
1498
1499 /* Replace invoice with signed one */
1500 tal_free(sent->inv);
1501 sent->inv = invoice_decode(sent,
1502 buf + invtok->start,
1503 invtok->end - invtok->start,
1504 plugin_feature_set(cmd->plugin),
1505 chainparams,
1506 &fail);
1507 if (!sent->inv) {
1508 plugin_log(cmd->plugin, LOG_BROKEN,
1509 "Bad createinvoice %.*s: %s",
1510 json_tok_full_len(invtok),
1511 json_tok_full(buf, invtok),
1512 fail);
1513 return command_fail(cmd, JSONRPC2_INVALID_PARAMS,
1514 "Bad createinvoice response %s", fail);
1515 }
1516
1517 sent->path = path_to_node(sent, cmd->plugin,
1518 sent->offer->node_id,
1519 &parity);
1520 if (!sent->path)
1521 return connect_direct(cmd, sent->offer->node_id, parity,
1522 sendinvoice_after_connect, sent);
1523
1524 return sendinvoice_after_connect(cmd, NULL, NULL, sent);
1525 }
1526
sign_invoice(struct command * cmd,struct sent * sent)1527 static struct command_result *sign_invoice(struct command *cmd,
1528 struct sent *sent)
1529 {
1530 struct out_req *req;
1531
1532 /* Get invoice signature and put in db so we can receive payment */
1533 req = jsonrpc_request_start(cmd->plugin, cmd, "createinvoice",
1534 &createinvoice_done,
1535 &forward_error,
1536 sent);
1537 json_add_string(req->js, "invstring", invoice_encode(tmpctx, sent->inv));
1538 json_add_preimage(req->js, "preimage", &sent->inv_preimage);
1539 json_add_escaped_string(req->js, "label", sent->inv_label);
1540 return send_outreq(cmd->plugin, req);
1541 }
1542
json_to_bip340sig(const char * buffer,const jsmntok_t * tok,struct bip340sig * sig)1543 static bool json_to_bip340sig(const char *buffer, const jsmntok_t *tok,
1544 struct bip340sig *sig)
1545 {
1546 return hex_decode(buffer + tok->start, tok->end - tok->start,
1547 sig->u8, sizeof(sig->u8));
1548 }
1549
payersign_done(struct command * cmd,const char * buf,const jsmntok_t * result,struct sent * sent)1550 static struct command_result *payersign_done(struct command *cmd,
1551 const char *buf,
1552 const jsmntok_t *result,
1553 struct sent *sent)
1554 {
1555 const jsmntok_t *sig;
1556
1557 sent->inv->refund_signature = tal(sent->inv, struct bip340sig);
1558 sig = json_get_member(buf, result, "signature");
1559 json_to_bip340sig(buf, sig, sent->inv->refund_signature);
1560
1561 return sign_invoice(cmd, sent);
1562 }
1563
1564 /* They're offering a refund, so we need to sign with same key as used
1565 * in initial payment. */
listsendpays_done(struct command * cmd,const char * buf,const jsmntok_t * result,struct sent * sent)1566 static struct command_result *listsendpays_done(struct command *cmd,
1567 const char *buf,
1568 const jsmntok_t *result,
1569 struct sent *sent)
1570 {
1571 const jsmntok_t *t, *arr = json_get_member(buf, result, "payments");
1572 size_t i;
1573 const u8 *public_tweak = NULL, *p;
1574 u8 *msg;
1575 size_t len;
1576 struct sha256 merkle;
1577 struct out_req *req;
1578
1579 /* Linearize populates ->fields */
1580 msg = tal_arr(tmpctx, u8, 0);
1581 towire_invoice(&msg, sent->inv);
1582 p = msg;
1583 len = tal_bytelen(msg);
1584 sent->inv = tlv_invoice_new(cmd);
1585 if (!fromwire_invoice(&p, &len, sent->inv))
1586 plugin_err(cmd->plugin,
1587 "Could not remarshall %s", tal_hex(tmpctx, msg));
1588
1589 merkle_tlv(sent->inv->fields, &merkle);
1590
1591 json_for_each_arr(i, t, arr) {
1592 const jsmntok_t *b12tok;
1593 struct tlv_invoice *inv;
1594 char *fail;
1595
1596 b12tok = json_get_member(buf, t, "bolt12");
1597 if (!b12tok) {
1598 /* This could happen if they try to refund a bolt11 */
1599 plugin_log(cmd->plugin, LOG_UNUSUAL,
1600 "Not bolt12 string in %.*s?",
1601 json_tok_full_len(t),
1602 json_tok_full(buf, t));
1603 continue;
1604 }
1605
1606 inv = invoice_decode(tmpctx, buf + b12tok->start,
1607 b12tok->end - b12tok->start,
1608 plugin_feature_set(cmd->plugin),
1609 chainparams,
1610 &fail);
1611 if (!inv) {
1612 plugin_log(cmd->plugin, LOG_BROKEN,
1613 "Bad bolt12 string in %.*s?",
1614 json_tok_full_len(t),
1615 json_tok_full(buf, t));
1616 continue;
1617 }
1618
1619 public_tweak = inv->payer_info;
1620 break;
1621 }
1622
1623 if (!public_tweak)
1624 return command_fail(cmd, JSONRPC2_INVALID_PARAMS,
1625 "Cannot find invoice %s for refund",
1626 type_to_string(tmpctx, struct sha256,
1627 sent->offer->refund_for));
1628
1629 /* BOLT-offers #12:
1630 * - MUST set `refund_signature` to the signature of the
1631 * `refunded_payment_hash` using prefix `refund_signature` and the
1632 * `payer_key` from the to-be-refunded invoice.
1633 */
1634 req = jsonrpc_request_start(cmd->plugin, cmd, "payersign",
1635 &payersign_done,
1636 &forward_error,
1637 sent);
1638 json_add_string(req->js, "messagename", "invoice");
1639 json_add_string(req->js, "fieldname", "refund_signature");
1640 json_add_sha256(req->js, "merkle", &merkle);
1641 json_add_hex_talarr(req->js, "tweak", public_tweak);
1642 return send_outreq(cmd->plugin, req);
1643 }
1644
json_sendinvoice(struct command * cmd,const char * buffer,const jsmntok_t * params)1645 static struct command_result *json_sendinvoice(struct command *cmd,
1646 const char *buffer,
1647 const jsmntok_t *params)
1648 {
1649 struct amount_msat *msat;
1650 struct out_req *req;
1651 u32 *timeout;
1652 struct sent *sent = tal(cmd, struct sent);
1653
1654 sent->inv = tlv_invoice_new(cmd);
1655 sent->invreq = NULL;
1656 sent->cmd = cmd;
1657
1658 /* FIXME: Support recurring send_invoice offers? */
1659 if (!param(cmd, buffer, params,
1660 p_req("offer", param_offer, &sent->offer),
1661 p_req("label", param_label, &sent->inv_label),
1662 p_opt("msatoshi", param_msat, &msat),
1663 p_opt_def("timeout", param_number, &timeout, 90),
1664 p_opt("quantity", param_u64, &sent->inv->quantity),
1665 NULL))
1666 return command_param_failed();
1667
1668 /* This is how long we'll wait for a reply for. */
1669 sent->wait_timeout = *timeout;
1670
1671 /* Check they are really trying to send us money. */
1672 if (!sent->offer->send_invoice)
1673 return command_fail(cmd, JSONRPC2_INVALID_PARAMS,
1674 "Offer wants an invoice_request, not invoice");
1675
1676 /* If they don't tell us how much, base it on offer. */
1677 if (!msat) {
1678 if (sent->offer->currency)
1679 return command_fail(cmd, JSONRPC2_INVALID_PARAMS,
1680 "Offer in different currency: need amount");
1681 if (!sent->offer->amount)
1682 return command_fail(cmd, JSONRPC2_INVALID_PARAMS,
1683 "Offer did not specify: need amount");
1684 sent->inv->amount = tal_dup(sent->inv, u64, sent->offer->amount);
1685 if (sent->inv->quantity)
1686 *sent->inv->amount *= *sent->inv->quantity;
1687 } else
1688 sent->inv->amount = tal_dup(sent->inv, u64,
1689 &msat->millisatoshis); /* Raw: tlv */
1690
1691 /* FIXME: Support blinded paths, in which case use fake nodeid */
1692
1693 /* BOLT-offers #12:
1694 * - otherwise (responding to a `send_invoice` offer):
1695 * - MUST set `node_id` to the id of the node to send payment to.
1696 * - MUST set `description` the same as the offer.
1697 */
1698 sent->inv->node_id = tal(sent->inv, struct point32);
1699
1700 /* This only fails if pubkey is invalid. */
1701 if (!secp256k1_xonly_pubkey_from_pubkey(secp256k1_ctx,
1702 &sent->inv->node_id->pubkey,
1703 NULL,
1704 &local_id.pubkey))
1705 abort();
1706
1707 sent->inv->description
1708 = tal_dup_talarr(sent->inv, char, sent->offer->description);
1709
1710 /* BOLT-offers #12:
1711 * - MUST set (or not set) `send_invoice` the same as the offer.
1712 */
1713 sent->inv->send_invoice = tal(sent->inv, struct tlv_invoice_send_invoice);
1714
1715 /* BOLT-offers #12:
1716 * - MUST set `offer_id` to the id of the offer.
1717 */
1718 sent->inv->offer_id = tal(sent->inv, struct sha256);
1719 merkle_tlv(sent->offer->fields, sent->inv->offer_id);
1720
1721 /* BOLT-offers #12:
1722 * - SHOULD not respond to an offer if the current time is after
1723 * `absolute_expiry`.
1724 */
1725 if (sent->offer->absolute_expiry
1726 && time_now().ts.tv_sec > *sent->offer->absolute_expiry)
1727 return command_fail(cmd, OFFER_EXPIRED, "Offer expired");
1728
1729 /* BOLT-offers #12:
1730 * - otherwise (responding to a `send_invoice` offer):
1731 *...
1732 * - if the offer had a `quantity_min` or `quantity_max` field:
1733 * - MUST set `quantity`
1734 * - MUST set it within that (inclusive) range.
1735 * - otherwise:
1736 * - MUST NOT set `quantity`
1737 */
1738 if (sent->offer->quantity_min || sent->offer->quantity_max) {
1739 if (!sent->inv->quantity)
1740 return command_fail(cmd, JSONRPC2_INVALID_PARAMS,
1741 "quantity parameter required");
1742 if (sent->offer->quantity_min
1743 && *sent->inv->quantity < *sent->offer->quantity_min)
1744 return command_fail(cmd, JSONRPC2_INVALID_PARAMS,
1745 "quantity must be >= %"PRIu64,
1746 *sent->offer->quantity_min);
1747 if (sent->offer->quantity_max
1748 && *sent->inv->quantity > *sent->offer->quantity_max)
1749 return command_fail(cmd, JSONRPC2_INVALID_PARAMS,
1750 "quantity must be <= %"PRIu64,
1751 *sent->offer->quantity_max);
1752 } else {
1753 if (sent->inv->quantity)
1754 return command_fail(cmd, JSONRPC2_INVALID_PARAMS,
1755 "quantity parameter unnecessary");
1756 }
1757
1758 /* BOLT-offers #12:
1759 * - MUST set `created_at` to the number of seconds since Midnight 1
1760 * January 1970, UTC when the offer was created.
1761 */
1762 sent->inv->created_at = tal(sent->inv, u64);
1763 *sent->inv->created_at = time_now().ts.tv_sec;
1764
1765 /* BOLT-offers #12:
1766 * - if the expiry for accepting payment is not 7200 seconds after
1767 * `created_at`:
1768 * - MUST set `relative_expiry` `seconds_from_creation` to the number
1769 * of seconds after `created_at` that payment of this invoice should
1770 * not be attempted.
1771 */
1772 if (sent->wait_timeout != 7200) {
1773 sent->inv->relative_expiry = tal(sent->inv, u32);
1774 *sent->inv->relative_expiry = sent->wait_timeout;
1775 }
1776
1777 /* BOLT-offers #12:
1778 * - MUST set `payer_key` to the `node_id` of the offer.
1779 */
1780 sent->inv->payer_key = sent->offer->node_id;
1781
1782 /* BOLT-offers #12:
1783 * - FIXME: recurrence!
1784 */
1785 if (sent->offer->recurrence)
1786 return command_fail(cmd, JSONRPC2_INVALID_PARAMS,
1787 "FIXME: handle recurring send_invoice offer!");
1788
1789 /* BOLT-offers #12:
1790 *
1791 * - if the chain for the invoice is not solely bitcoin:
1792 * - MUST specify `chains` the offer is valid for.
1793 * - otherwise:
1794 * - the bitcoin chain is implied as the first and only entry.
1795 */
1796 if (!streq(chainparams->network_name, "bitcoin")) {
1797 if (deprecated_apis) {
1798 sent->inv->chains = tal_arr(sent->inv, struct bitcoin_blkid, 1);
1799 sent->inv->chains[0] = chainparams->genesis_blockhash;
1800 }
1801 sent->inv->chain = tal_dup(sent->inv, struct bitcoin_blkid,
1802 &chainparams->genesis_blockhash);
1803 }
1804
1805 sent->inv->features
1806 = plugin_feature_set(cmd->plugin)->bits[BOLT11_FEATURE];
1807
1808 randombytes_buf(&sent->inv_preimage, sizeof(sent->inv_preimage));
1809 sent->inv->payment_hash = tal(sent->inv, struct sha256);
1810 sha256(sent->inv->payment_hash,
1811 &sent->inv_preimage, sizeof(sent->inv_preimage));
1812
1813 /* BOLT-offers #12:
1814 * - MUST set (or not set) `refund_for` exactly as the offer did.
1815 * - if it sets `refund_for`:
1816 * - MUST set `refund_signature` to the signature of the
1817 * `refunded_payment_hash` using prefix `refund_signature` and
1818 * the `payer_key` from the to-be-refunded invoice.
1819 * - otherwise:
1820 * - MUST NOT set `refund_signature`
1821 */
1822 if (sent->offer->refund_for) {
1823 sent->inv->refund_for = sent->offer->refund_for;
1824 /* Find original payment invoice */
1825 req = jsonrpc_request_start(cmd->plugin, cmd, "listsendpays",
1826 &listsendpays_done,
1827 &forward_error,
1828 sent);
1829 json_add_sha256(req->js, "payment_hash",
1830 sent->offer->refund_for);
1831 return send_outreq(cmd->plugin, req);
1832 }
1833
1834 return sign_invoice(cmd, sent);
1835 }
1836
1837 #if DEVELOPER
param_invreq(struct command * cmd,const char * name,const char * buffer,const jsmntok_t * tok,struct tlv_invoice_request ** invreq)1838 static struct command_result *param_invreq(struct command *cmd,
1839 const char *name,
1840 const char *buffer,
1841 const jsmntok_t *tok,
1842 struct tlv_invoice_request **invreq)
1843 {
1844 char *fail;
1845
1846 *invreq = invrequest_decode(cmd, buffer + tok->start, tok->end - tok->start,
1847 plugin_feature_set(cmd->plugin), chainparams,
1848 &fail);
1849 if (!*invreq)
1850 return command_fail_badparam(cmd, name, buffer, tok,
1851 tal_fmt(cmd,
1852 "Unparsable invreq: %s",
1853 fail));
1854 return NULL;
1855 }
1856
json_rawrequest(struct command * cmd,const char * buffer,const jsmntok_t * params)1857 static struct command_result *json_rawrequest(struct command *cmd,
1858 const char *buffer,
1859 const jsmntok_t *params)
1860 {
1861 struct sent *sent = tal(cmd, struct sent);
1862 u32 *timeout;
1863 struct node_id *node_id;
1864 struct point32 node_id32;
1865 enum nodeid_parity parity;
1866
1867 if (!param(cmd, buffer, params,
1868 p_req("invreq", param_invreq, &sent->invreq),
1869 p_req("nodeid", param_node_id, &node_id),
1870 p_opt_def("timeout", param_number, &timeout, 60),
1871 NULL))
1872 return command_param_failed();
1873
1874 /* Skip over 02/03 in node_id */
1875 if (!secp256k1_xonly_pubkey_parse(secp256k1_ctx,
1876 &node_id32.pubkey,
1877 node_id->k + 1))
1878 return command_fail(cmd, JSONRPC2_INVALID_PARAMS,
1879 "Invalid nodeid");
1880 /* This is how long we'll wait for a reply for. */
1881 sent->wait_timeout = *timeout;
1882 sent->cmd = cmd;
1883 sent->offer = NULL;
1884
1885 sent->path = path_to_node(sent, cmd->plugin,
1886 &node_id32,
1887 &parity);
1888 if (!sent->path) {
1889 /* We *do* know parity: they gave it to us! */
1890 parity = node_id->k[0];
1891 return connect_direct(cmd, &node_id32, parity,
1892 sendinvreq_after_connect, sent);
1893 }
1894
1895 return sendinvreq_after_connect(cmd, NULL, NULL, sent);
1896 }
1897 #endif /* DEVELOPER */
1898
1899 static const struct plugin_command commands[] = {
1900 {
1901 "fetchinvoice",
1902 "payment",
1903 "Request remote node for an invoice for this {offer}, with {amount}, {quanitity}, {recurrence_counter}, {recurrence_start} and {recurrence_label} iff required.",
1904 NULL,
1905 json_fetchinvoice,
1906 },
1907 {
1908 "sendinvoice",
1909 "payment",
1910 "Request remote node for to pay this send_invoice {offer}, with {amount}, {quanitity}, {recurrence_counter}, {recurrence_start} and {recurrence_label} iff required.",
1911 NULL,
1912 json_sendinvoice,
1913 },
1914 #if DEVELOPER
1915 {
1916 "dev-rawrequest",
1917 "util",
1918 "Send {invreq} to {nodeid}, wait {timeout} (60 seconds by default)",
1919 NULL,
1920 json_rawrequest,
1921 },
1922 #endif /* DEVELOPER */
1923 };
1924
init(struct plugin * p,const char * buf UNUSED,const jsmntok_t * config UNUSED)1925 static const char *init(struct plugin *p, const char *buf UNUSED,
1926 const jsmntok_t *config UNUSED)
1927 {
1928 bool exp_offers;
1929
1930 rpc_scan(p, "getinfo",
1931 take(json_out_obj(NULL, NULL, NULL)),
1932 "{id:%}", JSON_SCAN(json_to_pubkey, &local_id));
1933
1934 rpc_scan(p, "listconfigs",
1935 take(json_out_obj(NULL, "config", "experimental-offers")),
1936 "{experimental-offers:%}",
1937 JSON_SCAN(json_to_bool, &exp_offers));
1938
1939 if (!exp_offers)
1940 return "offers not enabled in config";
1941 return NULL;
1942 }
1943
1944 static const struct plugin_hook hooks[] = {
1945 {
1946 "onion_message_blinded",
1947 recv_obs_onion_message
1948 },
1949 {
1950 "onion_message_ourpath",
1951 recv_modern_onion_message
1952 },
1953 {
1954 "invoice_payment",
1955 invoice_payment,
1956 },
1957 };
1958
main(int argc,char * argv[])1959 int main(int argc, char *argv[])
1960 {
1961 setup_locale();
1962 plugin_main(argv, init, PLUGIN_RESTARTABLE, true, NULL,
1963 commands, ARRAY_SIZE(commands),
1964 /* No notifications */
1965 NULL, 0,
1966 hooks, ARRAY_SIZE(hooks),
1967 NULL, 0,
1968 plugin_option("fetchinvoice-noconnect", "flag",
1969 "Don't try to connect directly to fetch an invoice.",
1970 flag_option, &disable_connect),
1971 NULL);
1972 }
1973