1 #include "pay.h"
2 #include <ccan/tal/str/str.h>
3 #include <common/bolt12_merkle.h>
4 #include <common/json_command.h>
5 #include <common/json_helpers.h>
6 #include <common/json_tok.h>
7 #include <common/onion.h>
8 #include <common/onionreply.h>
9 #include <common/param.h>
10 #include <common/route.h>
11 #include <common/timeout.h>
12 #include <common/type_to_string.h>
13 #include <lightningd/chaintopology.h>
14 #include <lightningd/channel.h>
15 #include <lightningd/json.h>
16 #include <lightningd/notification.h>
17 #include <lightningd/peer_control.h>
18
19 /* Routing failure object */
20 struct routing_failure {
21 unsigned int erring_index;
22 enum onion_wire failcode;
23 const struct node_id *erring_node;
24 const struct short_channel_id *erring_channel;
25 int channel_dir;
26 /* If remote sent us a message, this is it. */
27 const u8 *msg;
28 };
29
30 /* sendpay command */
31 struct sendpay_command {
32 struct list_node list;
33
34 struct sha256 payment_hash;
35 u64 partid;
36 u64 groupid;
37 struct command *cmd;
38 };
39
string_to_payment_status(const char * status_str,enum wallet_payment_status * status)40 static bool string_to_payment_status(const char *status_str, enum wallet_payment_status *status)
41 {
42 if (streq(status_str, "complete")) {
43 *status = PAYMENT_COMPLETE;
44 return true;
45 } else if (streq(status_str, "pending")) {
46 *status = PAYMENT_PENDING;
47 return true;
48 } else if (streq(status_str, "failed")) {
49 *status = PAYMENT_FAILED;
50 return true;
51 }
52 return false;
53 }
54
payment_status_to_string(const enum wallet_payment_status status)55 static const char *payment_status_to_string(const enum wallet_payment_status status)
56 {
57 switch (status) {
58 case PAYMENT_COMPLETE:
59 return "complete";
60 case PAYMENT_FAILED:
61 return "failed";
62 case PAYMENT_PENDING:
63 return "pending";
64 }
65 //This should never happen
66 abort();
67 }
68
69
destroy_sendpay_command(struct sendpay_command * pc)70 static void destroy_sendpay_command(struct sendpay_command *pc)
71 {
72 list_del(&pc->list);
73 }
74
75 /* Owned by cmd, if cmd is deleted, then sendpay_success/sendpay_fail will
76 * no longer be called. */
77 static void
add_sendpay_waiter(struct lightningd * ld,struct command * cmd,const struct sha256 * payment_hash,u64 partid,u64 groupid)78 add_sendpay_waiter(struct lightningd *ld,
79 struct command *cmd,
80 const struct sha256 *payment_hash,
81 u64 partid, u64 groupid)
82 {
83 struct sendpay_command *pc = tal(cmd, struct sendpay_command);
84
85 pc->payment_hash = *payment_hash;
86 pc->partid = partid;
87 pc->groupid = groupid;
88 pc->cmd = cmd;
89 list_add(&ld->sendpay_commands, &pc->list);
90 tal_add_destructor(pc, destroy_sendpay_command);
91 }
92
93 /* Owned by cmd, if cmd is deleted, then sendpay_success/sendpay_fail will
94 * no longer be called. */
95 static void
add_waitsendpay_waiter(struct lightningd * ld,struct command * cmd,const struct sha256 * payment_hash,u64 partid,u64 groupid)96 add_waitsendpay_waiter(struct lightningd *ld,
97 struct command *cmd,
98 const struct sha256 *payment_hash,
99 u64 partid, u64 groupid)
100 {
101 struct sendpay_command *pc = tal(cmd, struct sendpay_command);
102
103 pc->payment_hash = *payment_hash;
104 pc->partid = partid;
105 pc->groupid = groupid;
106 pc->cmd = cmd;
107 list_add(&ld->waitsendpay_commands, &pc->list);
108 tal_add_destructor(pc, destroy_sendpay_command);
109 }
110
111 /* Outputs fields, not a separate object*/
json_add_payment_fields(struct json_stream * response,const struct wallet_payment * t)112 void json_add_payment_fields(struct json_stream *response,
113 const struct wallet_payment *t)
114 {
115 json_add_u64(response, "id", t->id);
116 json_add_sha256(response, "payment_hash", &t->payment_hash);
117 json_add_u64(response, "groupid", t->groupid);
118 if (t->partid)
119 json_add_u64(response, "partid", t->partid);
120 if (t->destination != NULL)
121 json_add_node_id(response, "destination", t->destination);
122
123 /* If we have a 0 amount delivered at the remote end we simply don't
124 * know since the onion was generated externally. */
125 if (amount_msat_greater(t->msatoshi, AMOUNT_MSAT(0)))
126 json_add_amount_msat_compat(response, t->msatoshi, "msatoshi",
127 "amount_msat");
128
129 json_add_amount_msat_compat(response, t->msatoshi_sent,
130 "msatoshi_sent", "amount_sent_msat");
131 json_add_u64(response, "created_at", t->timestamp);
132
133 switch (t->status) {
134 case PAYMENT_PENDING:
135 json_add_string(response, "status", "pending");
136 break;
137 case PAYMENT_COMPLETE:
138 json_add_string(response, "status", "complete");
139 break;
140 case PAYMENT_FAILED:
141 json_add_string(response, "status", "failed");
142 break;
143 }
144 if (t->payment_preimage)
145 json_add_preimage(response, "payment_preimage",
146 t->payment_preimage);
147 if (t->label)
148 json_add_string(response, "label", t->label);
149 if (t->invstring) {
150 if (strstarts(t->invstring, "lni"))
151 json_add_string(response, "bolt12", t->invstring);
152 else
153 json_add_string(response, "bolt11", t->invstring);
154 }
155
156 if (t->failonion)
157 json_add_hex(response, "erroronion", t->failonion,
158 tal_count(t->failonion));
159 }
160
sendpay_success(struct command * cmd,const struct wallet_payment * payment)161 static struct command_result *sendpay_success(struct command *cmd,
162 const struct wallet_payment *payment)
163 {
164 struct json_stream *response;
165
166 assert(payment->status == PAYMENT_COMPLETE);
167
168 response = json_stream_success(cmd);
169 json_add_payment_fields(response, payment);
170 return command_success(cmd, response);
171 }
172
173 static void
json_add_routefail_info(struct json_stream * js,unsigned int erring_index,enum onion_wire failcode,const struct node_id * erring_node,const struct short_channel_id * erring_channel,int channel_dir,const u8 * msg)174 json_add_routefail_info(struct json_stream *js,
175 unsigned int erring_index,
176 enum onion_wire failcode,
177 const struct node_id *erring_node,
178 const struct short_channel_id *erring_channel,
179 int channel_dir,
180 const u8 *msg)
181 {
182 const char *failcodename = onion_wire_name(failcode);
183
184 json_add_num(js, "erring_index", erring_index);
185 json_add_num(js, "failcode", failcode);
186 /* FIXME: Better way to detect this? */
187 if (!strstarts(failcodename, "INVALID "))
188 json_add_string(js, "failcodename", failcodename);
189
190 if (erring_node != NULL)
191 json_add_node_id(js, "erring_node", erring_node);
192
193 if (erring_channel != NULL) {
194 json_add_short_channel_id(js, "erring_channel", erring_channel);
195 json_add_num(js, "erring_direction", channel_dir);
196 }
197
198 if (msg)
199 json_add_hex_talarr(js, "raw_message", msg);
200 }
201
json_sendpay_fail_fields(struct json_stream * js,const struct wallet_payment * payment,errcode_t pay_errcode,const struct onionreply * onionreply,const struct routing_failure * fail)202 void json_sendpay_fail_fields(struct json_stream *js,
203 const struct wallet_payment *payment,
204 errcode_t pay_errcode,
205 const struct onionreply *onionreply,
206 const struct routing_failure *fail)
207 {
208 /* "immediate_routing_failure" is before payment creation. */
209 if (payment)
210 json_add_payment_fields(js, payment);
211 if (pay_errcode == PAY_UNPARSEABLE_ONION && onionreply)
212 json_add_hex_talarr(js, "onionreply", onionreply->contents);
213 else
214 json_add_routefail_info(js,
215 fail->erring_index,
216 fail->failcode,
217 fail->erring_node,
218 fail->erring_channel,
219 fail->channel_dir,
220 fail->msg);
221 }
222
sendpay_errmsg_fmt(const tal_t * ctx,errcode_t pay_errcode,const struct routing_failure * fail,const char * details)223 static const char *sendpay_errmsg_fmt(const tal_t *ctx, errcode_t pay_errcode,
224 const struct routing_failure *fail,
225 const char *details)
226 {
227 char *errmsg;
228 if (pay_errcode == PAY_UNPARSEABLE_ONION)
229 errmsg = "Malformed error reply";
230 else {
231 assert(fail);
232 errmsg = tal_fmt(ctx, "failed: %s (%s)",
233 onion_wire_name(fail->failcode), details);
234 }
235 return errmsg;
236 }
237
238 /* onionreply used if pay_errcode == PAY_UNPARSEABLE_ONION */
239 static struct command_result *
sendpay_fail(struct command * cmd,const struct wallet_payment * payment,errcode_t pay_errcode,const struct onionreply * onionreply,const struct routing_failure * fail,const char * errmsg)240 sendpay_fail(struct command *cmd,
241 const struct wallet_payment *payment,
242 errcode_t pay_errcode,
243 const struct onionreply *onionreply,
244 const struct routing_failure *fail,
245 const char *errmsg)
246 {
247 struct json_stream *data;
248
249 data = json_stream_fail(cmd, pay_errcode,
250 errmsg);
251 json_sendpay_fail_fields(data,
252 payment,
253 pay_errcode,
254 onionreply,
255 fail);
256 json_object_end(data);
257 return command_failed(cmd, data);
258 }
259
260 /* We defer sendpay "success" until we know it's pending; consumes cmd */
261 static struct command_result *
json_sendpay_in_progress(struct command * cmd,const struct wallet_payment * payment)262 json_sendpay_in_progress(struct command *cmd,
263 const struct wallet_payment *payment)
264 {
265 struct json_stream *response = json_stream_success(cmd);
266 json_add_string(response, "message",
267 "Monitor status with listpays or waitsendpay");
268 json_add_payment_fields(response, payment);
269 return command_success(cmd, response);
270 }
271
tell_waiters_failed(struct lightningd * ld,const struct sha256 * payment_hash,const struct wallet_payment * payment,errcode_t pay_errcode,const struct onionreply * onionreply,const struct routing_failure * fail,const char * details)272 static void tell_waiters_failed(struct lightningd *ld,
273 const struct sha256 *payment_hash,
274 const struct wallet_payment *payment,
275 errcode_t pay_errcode,
276 const struct onionreply *onionreply,
277 const struct routing_failure *fail,
278 const char *details)
279 {
280 struct sendpay_command *pc;
281 struct sendpay_command *next;
282 const char *errmsg =
283 sendpay_errmsg_fmt(tmpctx, pay_errcode, fail, details);
284
285 /* Careful: sendpay_fail deletes cmd */
286 list_for_each_safe(&ld->waitsendpay_commands, pc, next, list) {
287 if (!sha256_eq(payment_hash, &pc->payment_hash))
288 continue;
289 if (payment->partid != pc->partid)
290 continue;
291 if (payment->groupid != pc->groupid)
292 continue;
293
294 sendpay_fail(pc->cmd, payment, pay_errcode, onionreply, fail,
295 errmsg);
296 }
297
298 notify_sendpay_failure(ld,
299 payment,
300 pay_errcode,
301 onionreply,
302 fail,
303 errmsg);
304 }
305
tell_waiters_success(struct lightningd * ld,const struct sha256 * payment_hash,struct wallet_payment * payment)306 static void tell_waiters_success(struct lightningd *ld,
307 const struct sha256 *payment_hash,
308 struct wallet_payment *payment)
309 {
310 struct sendpay_command *pc;
311 struct sendpay_command *next;
312
313 /* Careful: sendpay_success deletes cmd */
314 list_for_each_safe(&ld->waitsendpay_commands, pc, next, list) {
315 if (!sha256_eq(payment_hash, &pc->payment_hash))
316 continue;
317 if (payment->partid != pc->partid)
318 continue;
319 if (payment->groupid != pc->groupid)
320 continue;
321
322 sendpay_success(pc->cmd, payment);
323 }
324 notify_sendpay_success(ld, payment);
325 }
326
payment_succeeded(struct lightningd * ld,struct htlc_out * hout,const struct preimage * rval)327 void payment_succeeded(struct lightningd *ld, struct htlc_out *hout,
328 const struct preimage *rval)
329 {
330 struct wallet_payment *payment;
331
332 wallet_payment_set_status(ld->wallet, &hout->payment_hash,
333 hout->partid, hout->groupid,
334 PAYMENT_COMPLETE, rval);
335 payment = wallet_payment_by_hash(tmpctx, ld->wallet,
336 &hout->payment_hash,
337 hout->partid, hout->groupid);
338 assert(payment);
339
340 if (payment->local_offer_id)
341 wallet_offer_mark_used(ld->wallet->db, payment->local_offer_id);
342 tell_waiters_success(ld, &hout->payment_hash, payment);
343 }
344
345 /* Return a struct routing_failure for an immediate failure
346 * (returned directly from send_htlc_out). The returned
347 * failure is allocated from the given context. */
348 static struct routing_failure*
immediate_routing_failure(const tal_t * ctx,const struct lightningd * ld,enum onion_wire failcode,const struct short_channel_id * channel0,const struct node_id * dstid)349 immediate_routing_failure(const tal_t *ctx,
350 const struct lightningd *ld,
351 enum onion_wire failcode,
352 const struct short_channel_id *channel0,
353 const struct node_id *dstid)
354 {
355 struct routing_failure *routing_failure;
356
357 assert(failcode);
358
359 routing_failure = tal(ctx, struct routing_failure);
360 routing_failure->erring_index = 0;
361 routing_failure->failcode = failcode;
362 routing_failure->erring_node =
363 tal_dup(routing_failure, struct node_id, &ld->id);
364 routing_failure->erring_channel =
365 tal_dup(routing_failure, struct short_channel_id, channel0);
366 routing_failure->channel_dir = node_id_idx(&ld->id, dstid);
367 routing_failure->msg = NULL;
368
369 return routing_failure;
370 }
371
372 /* Return a struct routing_failure for a local failure allocated
373 * from the given context. */
374 static struct routing_failure*
local_routing_failure(const tal_t * ctx,const struct lightningd * ld,const struct htlc_out * hout,enum onion_wire failcode,const struct wallet_payment * payment)375 local_routing_failure(const tal_t *ctx,
376 const struct lightningd *ld,
377 const struct htlc_out *hout,
378 enum onion_wire failcode,
379 const struct wallet_payment *payment)
380 {
381 struct routing_failure *routing_failure;
382
383 routing_failure = tal(ctx, struct routing_failure);
384 routing_failure->erring_index = 0;
385 routing_failure->failcode = failcode;
386
387 routing_failure->erring_node =
388 tal_dup(routing_failure, struct node_id, &ld->id);
389
390 if (payment->route_nodes != NULL && payment->route_channels != NULL) {
391 routing_failure->erring_channel =
392 tal_dup(routing_failure, struct short_channel_id,
393 &payment->route_channels[0]);
394 routing_failure->channel_dir =
395 node_id_idx(&ld->id, &payment->route_nodes[0]);
396 } else {
397 routing_failure->erring_channel = NULL;
398 }
399
400 routing_failure->msg = NULL;
401
402 log_debug(hout->key.channel->log, "local_routing_failure: %u (%s)",
403 routing_failure->failcode,
404 onion_wire_name(routing_failure->failcode));
405 return routing_failure;
406 }
407
408 /* Fills in *pay_errcode with PAY_TRY_OTHER_ROUTE or PAY_DESTINATION_PERM_FAIL */
409 static struct routing_failure*
remote_routing_failure(const tal_t * ctx,struct lightningd * ld,const struct wallet_payment * payment,const u8 * failuremsg,int origin_index,struct log * log,errcode_t * pay_errcode)410 remote_routing_failure(const tal_t *ctx,
411 struct lightningd *ld,
412 const struct wallet_payment *payment,
413 const u8 *failuremsg,
414 int origin_index,
415 struct log *log,
416 errcode_t *pay_errcode)
417 {
418 enum onion_wire failcode = fromwire_peektype(failuremsg);
419 struct routing_failure *routing_failure;
420 const struct node_id *route_nodes;
421 const struct node_id *erring_node;
422 const struct short_channel_id *route_channels;
423 const struct short_channel_id *erring_channel;
424 int dir;
425
426 routing_failure = tal(ctx, struct routing_failure);
427 route_nodes = payment->route_nodes;
428 route_channels = payment->route_channels;
429
430 assert(route_nodes == NULL || origin_index < tal_count(route_nodes));
431
432 /* Either we have both channels and nodes, or neither */
433 assert((route_nodes == NULL) == (route_channels == NULL));
434
435 if (route_nodes == NULL) {
436 /* This means we have the `shared_secrets`, but cannot infer
437 * the erring channel and node since we don't have them. This
438 * can happen if the payment was initialized using `sendonion`
439 * and the `shared_secrets` where specified. */
440 dir = 0;
441 erring_channel = NULL;
442 erring_node = NULL;
443
444 /* We don't know if there's another route, that'd depend on
445 * where the failure occured and whether it was a node
446 * failure. Let's assume it wasn't a terminal one, and have
447 * the sendonion caller deal with the actual decision. */
448 *pay_errcode = PAY_TRY_OTHER_ROUTE;
449 } else if (origin_index == tal_count(route_nodes) - 1) {
450 /* If any channel is to blame, it's the last one. */
451 erring_channel = &route_channels[origin_index];
452 /* Single hop? */
453 if (origin_index == 0)
454 dir = node_id_idx(&ld->id,
455 &route_nodes[origin_index]);
456 else
457 dir = node_id_idx(&route_nodes[origin_index - 1],
458 &route_nodes[origin_index]);
459
460 /* BOLT #4:
461 *
462 * - if the _final node_ is returning the error:
463 * - if the PERM bit is set:
464 * - SHOULD fail the payment.
465 * */
466 if (failcode & BADONION)
467 *pay_errcode = PAY_UNPARSEABLE_ONION;
468 else if (failcode & PERM)
469 *pay_errcode = PAY_DESTINATION_PERM_FAIL;
470 else
471 /* FIXME: not right for WIRE_FINAL_EXPIRY_TOO_SOON */
472 *pay_errcode = PAY_TRY_OTHER_ROUTE;
473 erring_node = &route_nodes[origin_index];
474 } else {
475 *pay_errcode = PAY_TRY_OTHER_ROUTE;
476
477 /* Report the *next* channel as failing. */
478 erring_channel = &route_channels[origin_index + 1];
479
480 dir = node_id_idx(&route_nodes[origin_index],
481 &route_nodes[origin_index+1]);
482
483 /* If the error is a BADONION, then it's on behalf of the
484 * following node. */
485 if (failcode & BADONION) {
486 log_debug(log, "failcode %u from onionreply %s",
487 failcode, tal_hex(tmpctx, failuremsg));
488 erring_node = &route_nodes[origin_index + 1];
489 } else
490 erring_node = &route_nodes[origin_index];
491 }
492
493 routing_failure->erring_index = (unsigned int) (origin_index + 1);
494 routing_failure->failcode = failcode;
495 routing_failure->msg = tal_dup_talarr(routing_failure, u8, failuremsg);
496
497 if (erring_node != NULL)
498 routing_failure->erring_node =
499 tal_dup(routing_failure, struct node_id, erring_node);
500 else
501 routing_failure->erring_node = NULL;
502
503 if (erring_channel != NULL) {
504 routing_failure->erring_channel = tal_dup(
505 routing_failure, struct short_channel_id, erring_channel);
506 routing_failure->channel_dir = dir;
507 } else {
508 routing_failure->erring_channel = NULL;
509 routing_failure->channel_dir = 0;
510 }
511
512 return routing_failure;
513 }
514
payment_store(struct lightningd * ld,struct wallet_payment * payment TAKES)515 void payment_store(struct lightningd *ld, struct wallet_payment *payment TAKES)
516 {
517 struct sendpay_command *pc;
518 struct sendpay_command *next;
519 /* Need to remember here otherwise wallet_payment_store will free us. */
520 bool ptaken = taken(payment);
521
522 wallet_payment_store(ld->wallet, payment);
523
524 /* Trigger any sendpay commands waiting for the store to occur. */
525 list_for_each_safe(&ld->sendpay_commands, pc, next, list) {
526 if (!sha256_eq(&payment->payment_hash, &pc->payment_hash))
527 continue;
528
529 /* Deletes from list, frees pc */
530 json_sendpay_in_progress(pc->cmd, payment);
531 }
532
533 if (ptaken)
534 tal_free(payment);
535 }
536
payment_failed(struct lightningd * ld,const struct htlc_out * hout,const char * localfail,const u8 * failmsg_needs_update)537 void payment_failed(struct lightningd *ld, const struct htlc_out *hout,
538 const char *localfail, const u8 *failmsg_needs_update)
539 {
540 struct wallet_payment *payment;
541 struct routing_failure* fail = NULL;
542 const char *failstr;
543 errcode_t pay_errcode;
544 const u8 *failmsg;
545 int origin_index;
546
547 payment = wallet_payment_by_hash(tmpctx, ld->wallet,
548 &hout->payment_hash,
549 hout->partid, hout->groupid);
550
551 #ifdef COMPAT_V052
552 /* Prior to "pay: delete HTLC when we delete payment." we would
553 * delete a payment on retry, but leave the HTLC. */
554 if (!payment) {
555 log_unusual(hout->key.channel->log,
556 "No payment for %s:"
557 " was this an old database?",
558 type_to_string(tmpctx, struct sha256,
559 &hout->payment_hash));
560 return;
561 }
562 #else
563 assert(payment);
564 #endif
565 assert((payment->route_channels == NULL) == (payment->route_nodes == NULL));
566
567 /* This gives more details than a generic failure message */
568 if (localfail) {
569 /* Use temporary_channel_failure if failmsg has it */
570 enum onion_wire failcode;
571 if (failmsg_needs_update)
572 failcode = fromwire_peektype(failmsg_needs_update);
573 else
574 failcode = fromwire_peektype(hout->failmsg);
575
576 fail = local_routing_failure(tmpctx, ld, hout, failcode,
577 payment);
578 failstr = localfail;
579 pay_errcode = PAY_TRY_OTHER_ROUTE;
580 } else if (payment->path_secrets == NULL) {
581 /* This was a payment initiated with `sendonion`, we therefore
582 * don't have the path secrets and cannot decode the error
583 * onion. Let's store it and hope whatever called `sendonion`
584 * knows how to deal with these. */
585
586 pay_errcode = PAY_UNPARSEABLE_ONION;
587 fail = NULL;
588 failstr = NULL;
589 } else if (hout->failmsg) {
590 /* This can happen when a direct peer told channeld it's a
591 * malformed onion using update_fail_malformed_htlc. */
592 failstr = "local failure";
593 failmsg = hout->failmsg;
594 origin_index = 0;
595 pay_errcode = PAY_TRY_OTHER_ROUTE;
596 goto use_failmsg;
597 } else {
598 /* Must be normal remote fail with an onion-wrapped error. */
599 failstr = "reply from remote";
600 /* Try to parse reply. */
601 struct secret *path_secrets = payment->path_secrets;
602
603 failmsg = unwrap_onionreply(tmpctx, path_secrets,
604 tal_count(path_secrets),
605 hout->failonion, &origin_index);
606 if (!failmsg) {
607 log_info(hout->key.channel->log,
608 "htlc %"PRIu64" failed with bad reply (%s)",
609 hout->key.id,
610 tal_hex(tmpctx, hout->failonion->contents));
611 /* Cannot record failure. */
612 fail = NULL;
613 pay_errcode = PAY_UNPARSEABLE_ONION;
614 } else {
615 enum onion_wire failcode;
616
617 use_failmsg:
618 failcode = fromwire_peektype(failmsg);
619 log_info(hout->key.channel->log,
620 "htlc %"PRIu64" "
621 "failed from %ith node "
622 "with code 0x%04x (%s)",
623 hout->key.id,
624 origin_index,
625 failcode, onion_wire_name(failcode));
626 fail = remote_routing_failure(tmpctx, ld,
627 payment, failmsg,
628 origin_index,
629 hout->key.channel->log,
630 &pay_errcode);
631 }
632 }
633
634 /* Save to DB */
635 payment_store(ld, payment);
636 wallet_payment_set_status(ld->wallet, &hout->payment_hash,
637 hout->partid, hout->groupid,
638 PAYMENT_FAILED, NULL);
639 wallet_payment_set_failinfo(ld->wallet,
640 &hout->payment_hash,
641 hout->partid,
642 fail ? NULL : hout->failonion,
643 pay_errcode == PAY_DESTINATION_PERM_FAIL,
644 fail ? fail->erring_index : -1,
645 fail ? fail->failcode : 0,
646 fail ? fail->erring_node : NULL,
647 fail ? fail->erring_channel : NULL,
648 NULL,
649 failstr,
650 fail ? fail->channel_dir : 0);
651
652 tell_waiters_failed(ld, &hout->payment_hash, payment, pay_errcode,
653 hout->failonion, fail, failstr);
654 }
655
656 /* Wait for a payment. If cmd is deleted, then wait_payment()
657 * no longer be called.
658 * Return callback if we called already, otherwise NULL. */
wait_payment(struct lightningd * ld,struct command * cmd,const struct sha256 * payment_hash,u64 partid,u64 groupid)659 static struct command_result *wait_payment(struct lightningd *ld,
660 struct command *cmd,
661 const struct sha256 *payment_hash,
662 u64 partid, u64 groupid)
663 {
664 struct wallet_payment *payment;
665 struct onionreply *failonionreply;
666 bool faildestperm;
667 int failindex;
668 enum onion_wire failcode;
669 struct node_id *failnode;
670 struct short_channel_id *failchannel;
671 u8 *failupdate;
672 char *faildetail;
673 struct routing_failure *fail;
674 int faildirection;
675 errcode_t rpcerrorcode;
676
677 payment = wallet_payment_by_hash(tmpctx, ld->wallet,
678 payment_hash, partid, groupid);
679 if (!payment) {
680 return command_fail(cmd, PAY_NO_SUCH_PAYMENT,
681 "Never attempted payment part %"PRIu64
682 " for '%s'",
683 partid,
684 type_to_string(tmpctx, struct sha256,
685 payment_hash));
686 }
687
688 log_debug(cmd->ld->log, "Payment part %"PRIu64"/%"PRIu64"/%"PRIu64" status %u",
689 partid, payment->partid, payment->groupid, payment->status);
690
691 switch (payment->status) {
692 case PAYMENT_PENDING:
693 add_waitsendpay_waiter(ld, cmd, payment_hash, partid, groupid);
694 return NULL;
695
696 case PAYMENT_COMPLETE:
697 return sendpay_success(cmd, payment);
698
699 case PAYMENT_FAILED:
700 /* Get error from DB */
701 wallet_payment_get_failinfo(tmpctx, ld->wallet,
702 payment_hash,
703 partid,
704 groupid,
705 &failonionreply,
706 &faildestperm,
707 &failindex,
708 &failcode,
709 &failnode,
710 &failchannel,
711 &failupdate,
712 &faildetail,
713 &faildirection);
714 /* Old DB might not save failure information */
715 if (!failonionreply && !failnode) {
716 return command_fail(cmd, PAY_UNSPECIFIED_ERROR,
717 "Payment failure reason unknown");
718 } else if (failonionreply) {
719 /* failed to parse returned onion error */
720 return sendpay_fail(
721 cmd, payment, PAY_UNPARSEABLE_ONION, failonionreply,
722 NULL,
723 sendpay_errmsg_fmt(tmpctx, PAY_UNPARSEABLE_ONION,
724 NULL, faildetail));
725 } else {
726 /* Parsed onion error, get its details */
727 assert(failnode);
728 fail = tal(tmpctx, struct routing_failure);
729 fail->erring_index = failindex;
730 fail->failcode = failcode;
731 fail->erring_node =
732 tal_dup(fail, struct node_id, failnode);
733
734 if (failchannel) {
735 fail->erring_channel = tal_dup(
736 fail, struct short_channel_id, failchannel);
737 fail->channel_dir = faildirection;
738 } else {
739 fail->erring_channel = NULL;
740 }
741
742 /* FIXME: We don't store this! */
743 fail->msg = NULL;
744
745 rpcerrorcode = faildestperm ? PAY_DESTINATION_PERM_FAIL
746 : PAY_TRY_OTHER_ROUTE;
747
748 return sendpay_fail(
749 cmd, payment, rpcerrorcode, NULL, fail,
750 sendpay_errmsg_fmt(tmpctx, rpcerrorcode, fail,
751 faildetail));
752 }
753 }
754
755 /* Impossible. */
756 abort();
757 }
758
should_use_tlv(enum route_hop_style style)759 static bool should_use_tlv(enum route_hop_style style)
760 {
761 switch (style) {
762 case ROUTE_HOP_TLV:
763 return true;
764 /* Otherwise fall thru */
765 case ROUTE_HOP_LEGACY:
766 return false;
767 }
768 abort();
769 }
770
771 /* Returns failmsg on failure, tallocated off ctx */
send_onion(const tal_t * ctx,struct lightningd * ld,const struct onionpacket * packet,const struct route_hop * first_hop,const struct sha256 * payment_hash,const struct pubkey * blinding,u64 partid,u64 groupid,struct channel * channel,struct htlc_out ** hout)772 static const u8 *send_onion(const tal_t *ctx, struct lightningd *ld,
773 const struct onionpacket *packet,
774 const struct route_hop *first_hop,
775 const struct sha256 *payment_hash,
776 const struct pubkey *blinding,
777 u64 partid,
778 u64 groupid,
779 struct channel *channel,
780 struct htlc_out **hout)
781 {
782 const u8 *onion;
783 unsigned int base_expiry;
784 bool dont_care_about_channel_update;
785 base_expiry = get_block_height(ld->topology) + 1;
786 onion = serialize_onionpacket(tmpctx, packet);
787 return send_htlc_out(ctx, channel, first_hop->amount,
788 base_expiry + first_hop->delay, payment_hash,
789 blinding, partid, groupid, onion, NULL, hout,
790 &dont_care_about_channel_update);
791 }
792
check_offer_usage(struct command * cmd,const struct sha256 * local_offer_id)793 static struct command_result *check_offer_usage(struct command *cmd,
794 const struct sha256 *local_offer_id)
795 {
796 enum offer_status status;
797 const struct wallet_payment **payments;
798
799 if (!local_offer_id)
800 return NULL;
801
802 if (!wallet_offer_find(tmpctx, cmd->ld->wallet, local_offer_id,
803 NULL, &status))
804 return command_fail(cmd, PAY_OFFER_INVALID,
805 "Unknown offer %s",
806 type_to_string(tmpctx, struct sha256,
807 local_offer_id));
808
809 if (!offer_status_active(status))
810 return command_fail(cmd, PAY_OFFER_INVALID,
811 "Inactive offer %s",
812 type_to_string(tmpctx, struct sha256,
813 local_offer_id));
814
815 if (!offer_status_single(status))
816 return NULL;
817
818 /* OK, we must not attempt more than one payment at once for
819 * single_use offer */
820 payments = wallet_payments_by_offer(tmpctx, cmd->ld->wallet, local_offer_id);
821 for (size_t i = 0; i < tal_count(payments); i++) {
822 switch (payments[i]->status) {
823 case PAYMENT_COMPLETE:
824 return command_fail(cmd, PAY_OFFER_INVALID,
825 "Single-use offer already paid"
826 " with %s",
827 type_to_string(tmpctx, struct sha256,
828 &payments[i]
829 ->payment_hash));
830 case PAYMENT_PENDING:
831 return command_fail(cmd, PAY_OFFER_INVALID,
832 "Single-use offer already"
833 " in progress with %s",
834 type_to_string(tmpctx, struct sha256,
835 &payments[i]
836 ->payment_hash));
837 case PAYMENT_FAILED:
838 break;
839 }
840 }
841
842 return NULL;
843 }
844
845 /* destination/route_channels/route_nodes are NULL (and path_secrets may be NULL)
846 * if we're sending a raw onion. */
847 static struct command_result *
send_payment_core(struct lightningd * ld,struct command * cmd,const struct sha256 * rhash,u64 partid,u64 group,const struct route_hop * first_hop,struct amount_msat msat,struct amount_msat total_msat,const char * label TAKES,const char * invstring TAKES,const struct onionpacket * packet,const struct node_id * destination,struct node_id * route_nodes TAKES,struct short_channel_id * route_channels TAKES,struct secret * path_secrets,const struct sha256 * local_offer_id)848 send_payment_core(struct lightningd *ld,
849 struct command *cmd,
850 const struct sha256 *rhash,
851 u64 partid,
852 u64 group,
853 const struct route_hop *first_hop,
854 struct amount_msat msat,
855 struct amount_msat total_msat,
856 const char *label TAKES,
857 const char *invstring TAKES,
858 const struct onionpacket *packet,
859 const struct node_id *destination,
860 struct node_id *route_nodes TAKES,
861 struct short_channel_id *route_channels TAKES,
862 struct secret *path_secrets,
863 const struct sha256 *local_offer_id)
864 {
865 const struct wallet_payment **payments, *old_payment = NULL;
866 struct channel *channel;
867 const u8 *failmsg;
868 struct htlc_out *hout;
869 struct routing_failure *fail;
870 struct amount_msat msat_already_pending = AMOUNT_MSAT(0);
871 bool have_complete = false;
872
873 /* Now, do we already have one or more payments? */
874 payments = wallet_payment_list(tmpctx, ld->wallet, rhash, NULL);
875 for (size_t i = 0; i < tal_count(payments); i++) {
876 log_debug(ld->log, "Payment %zu/%zu: %s %s",
877 i, tal_count(payments),
878 type_to_string(tmpctx, struct amount_msat,
879 &payments[i]->msatoshi),
880 payments[i]->status == PAYMENT_COMPLETE ? "COMPLETE"
881 : payments[i]->status == PAYMENT_PENDING ? "PENDING"
882 : "FAILED");
883
884 switch (payments[i]->status) {
885 case PAYMENT_COMPLETE:
886 have_complete = true;
887 if (payments[i]->partid != partid)
888 continue;
889
890 /* Must match successful payment parameters. */
891 if (!amount_msat_eq(payments[i]->msatoshi, msat)) {
892 return command_fail(cmd, PAY_RHASH_ALREADY_USED,
893 "Already succeeded "
894 "with amount %s (not %s)",
895 type_to_string(tmpctx,
896 struct amount_msat,
897 &payments[i]->msatoshi),
898 type_to_string(tmpctx,
899 struct amount_msat, &msat));
900 }
901 if (payments[i]->destination && destination
902 && !node_id_eq(payments[i]->destination,
903 destination)) {
904 return command_fail(cmd, PAY_RHASH_ALREADY_USED,
905 "Already succeeded to %s",
906 type_to_string(tmpctx,
907 struct node_id,
908 payments[i]->destination));
909 }
910 return sendpay_success(cmd, payments[i]);
911
912 case PAYMENT_PENDING:
913 /* At most one payment group can be in-flight at any
914 * time. */
915 if (payments[i]->groupid != group) {
916 return command_fail(
917 cmd, PAY_IN_PROGRESS,
918 "Payment with groupid=%" PRIu64
919 " still in progress, cannot retry before "
920 "that completes.",
921 payments[i]->groupid);
922 }
923
924 /* Can't mix non-parallel and parallel payments! */
925 if (!payments[i]->partid != !partid) {
926 return command_fail(cmd, PAY_IN_PROGRESS,
927 "Already have %s payment in progress",
928 payments[i]->partid ? "parallel" : "non-parallel");
929 }
930
931 if (payments[i]->partid == partid) {
932 /* You can't change details while it's pending */
933 if (!amount_msat_eq(payments[i]->msatoshi, msat)) {
934 return command_fail(cmd, PAY_RHASH_ALREADY_USED,
935 "Already pending "
936 "with amount %s (not %s)",
937 type_to_string(tmpctx,
938 struct amount_msat,
939 &payments[i]->msatoshi),
940 type_to_string(tmpctx,
941 struct amount_msat, &msat));
942 }
943 if (payments[i]->destination && destination
944 && !node_id_eq(payments[i]->destination,
945 destination)) {
946 return command_fail(cmd, PAY_RHASH_ALREADY_USED,
947 "Already pending to %s",
948 type_to_string(tmpctx,
949 struct node_id,
950 payments[i]->destination));
951 }
952 return json_sendpay_in_progress(cmd, payments[i]);
953 }
954 /* You shouldn't change your mind about amount being
955 * sent, since we'll use it in onion! */
956 else if (!amount_msat_eq(payments[i]->total_msat,
957 total_msat))
958 return command_fail(cmd, JSONRPC2_INVALID_PARAMS,
959 "msatoshi was previously %s, now %s",
960 type_to_string(tmpctx,
961 struct amount_msat,
962 &payments[i]->total_msat),
963 type_to_string(tmpctx,
964 struct amount_msat,
965 &total_msat));
966
967
968 if (!amount_msat_add(&msat_already_pending,
969 msat_already_pending,
970 payments[i]->msatoshi)) {
971 return command_fail(cmd, LIGHTNINGD,
972 "Internal amount overflow!"
973 " %s + %s in %zu/%zu",
974 type_to_string(tmpctx,
975 struct amount_msat,
976 &msat_already_pending),
977 type_to_string(tmpctx,
978 struct amount_msat,
979 &payments[i]->msatoshi),
980 i, tal_count(payments));
981 }
982 break;
983
984 case PAYMENT_FAILED:
985 if (payments[i]->partid == partid)
986 old_payment = payments[i];
987 }
988 /* There is no way for us to add a payment with the
989 * same (payment_hash, partid, groupid) tuple since
990 * it'd collide with the database primary key. So
991 * report this as soon as possible. */
992
993 if (payments[i]->partid == partid && payments[i]->groupid == group) {
994 return command_fail(
995 cmd, PAY_RHASH_ALREADY_USED,
996 "There already is a payment with payment_hash=%s, "
997 "groupid=%" PRIu64 ", partid=%" PRIu64
998 ". Either change the partid, or wait for the "
999 "payment to complete and start a new group.",
1000 type_to_string(tmpctx, struct sha256, rhash), group,
1001 partid);
1002 }
1003
1004 }
1005
1006 /* If any part has succeeded, you can't start a new one! */
1007 if (have_complete) {
1008 return command_fail(cmd, PAY_RHASH_ALREADY_USED,
1009 "Already succeeded other parts");
1010 }
1011
1012 /* BOLT #4:
1013 *
1014 * - MUST NOT send another HTLC if the total `amount_msat` of the HTLC
1015 * set is already greater or equal to `total_msat`.
1016 */
1017 /* We don't do this for single 0-value payments (sendonion does this) */
1018 if (!amount_msat_eq(total_msat, AMOUNT_MSAT(0))
1019 && amount_msat_greater_eq(msat_already_pending, total_msat)) {
1020 return command_fail(cmd, PAY_IN_PROGRESS,
1021 "Already have %s of %s payments in progress",
1022 type_to_string(tmpctx, struct amount_msat,
1023 &msat_already_pending),
1024 type_to_string(tmpctx, struct amount_msat,
1025 &total_msat));
1026 }
1027
1028 struct command_result *offer_err;
1029 offer_err = check_offer_usage(cmd, local_offer_id);
1030 if (offer_err)
1031 return offer_err;
1032
1033 channel = active_channel_by_id(ld, &first_hop->node_id, NULL);
1034 if (!channel || !channel_can_add_htlc(channel)) {
1035 struct json_stream *data
1036 = json_stream_fail(cmd, PAY_TRY_OTHER_ROUTE,
1037 "No connection to first "
1038 "peer found");
1039
1040 json_add_routefail_info(data, 0, WIRE_UNKNOWN_NEXT_PEER,
1041 &ld->id, NULL,
1042 node_id_idx(&ld->id,
1043 &first_hop->node_id),
1044 NULL);
1045 json_object_end(data);
1046 return command_failed(cmd, data);
1047 }
1048
1049 failmsg = send_onion(tmpctx, ld, packet, first_hop, rhash, NULL, partid,
1050 group, channel, &hout);
1051
1052 if (failmsg) {
1053 fail = immediate_routing_failure(cmd, ld,
1054 fromwire_peektype(failmsg),
1055 channel->scid,
1056 &channel->peer->id);
1057
1058 return sendpay_fail(
1059 cmd, old_payment, PAY_TRY_OTHER_ROUTE, NULL, fail,
1060 sendpay_errmsg_fmt(tmpctx, PAY_TRY_OTHER_ROUTE, fail,
1061 "First peer not ready"));
1062 }
1063
1064 /* If we're retrying we delete outgoing HTLC otherwise it gets
1065 * reported to onchaind as a possibility, and we end up in
1066 * handle_missing_htlc_output -> onchain_failed_our_htlc ->
1067 * payment_failed with no payment.
1068 */
1069 if (old_payment) {
1070 wallet_local_htlc_out_delete(ld->wallet, channel, rhash,
1071 partid);
1072 }
1073
1074 /* If hout fails, payment should be freed too. */
1075 struct wallet_payment *payment = tal(hout, struct wallet_payment);
1076 payment->id = 0;
1077 payment->payment_hash = *rhash;
1078 payment->partid = partid;
1079 payment->groupid = group;
1080 if (destination)
1081 payment->destination = tal_dup(payment, struct node_id, destination);
1082 else
1083 payment->destination = NULL;
1084 payment->status = PAYMENT_PENDING;
1085 payment->msatoshi = msat;
1086 payment->msatoshi_sent = first_hop->amount;
1087 payment->total_msat = total_msat;
1088 payment->timestamp = time_now().ts.tv_sec;
1089 payment->payment_preimage = NULL;
1090 payment->path_secrets = tal_steal(payment, path_secrets);
1091 if (route_nodes)
1092 payment->route_nodes = tal_steal(payment, route_nodes);
1093 else
1094 payment->route_nodes = NULL;
1095 if (route_channels)
1096 payment->route_channels = tal_steal(payment, route_channels);
1097 else
1098 payment->route_channels = NULL;
1099 payment->failonion = NULL;
1100 if (label != NULL)
1101 payment->label = tal_strdup(payment, label);
1102 else
1103 payment->label = NULL;
1104 if (invstring != NULL)
1105 payment->invstring = tal_strdup(payment, invstring);
1106 else
1107 payment->invstring = NULL;
1108 if (local_offer_id)
1109 payment->local_offer_id = tal_dup(payment, struct sha256, local_offer_id);
1110 else
1111 payment->local_offer_id = NULL;
1112
1113 /* We write this into db when HTLC is actually sent. */
1114 wallet_payment_setup(ld->wallet, payment);
1115
1116 add_sendpay_waiter(ld, cmd, rhash, partid, group);
1117 return command_still_pending(cmd);
1118 }
1119
1120 static struct command_result *
send_payment(struct lightningd * ld,struct command * cmd,const struct sha256 * rhash,u64 partid,u64 group,const struct route_hop * route,struct amount_msat msat,struct amount_msat total_msat,const char * label TAKES,const char * invstring TAKES,const struct sha256 * local_offer_id,const struct secret * payment_secret)1121 send_payment(struct lightningd *ld,
1122 struct command *cmd,
1123 const struct sha256 *rhash,
1124 u64 partid,
1125 u64 group,
1126 const struct route_hop *route,
1127 struct amount_msat msat,
1128 struct amount_msat total_msat,
1129 const char *label TAKES,
1130 const char *invstring TAKES,
1131 const struct sha256 *local_offer_id,
1132 const struct secret *payment_secret)
1133 {
1134 unsigned int base_expiry;
1135 struct onionpacket *packet;
1136 struct secret *path_secrets;
1137 size_t i, n_hops = tal_count(route);
1138 struct node_id *ids = tal_arr(tmpctx, struct node_id, n_hops);
1139 struct short_channel_id *channels;
1140 struct sphinx_path *path;
1141 struct pubkey pubkey;
1142 bool final_tlv, ret;
1143 u8 *onion;
1144
1145 /* Expiry for HTLCs is absolute. And add one to give some margin. */
1146 base_expiry = get_block_height(ld->topology) + 1;
1147
1148 path = sphinx_path_new(tmpctx, rhash->u.u8);
1149 /* Extract IDs for each hop: create_onionpacket wants array. */
1150 for (i = 0; i < n_hops; i++)
1151 ids[i] = route[i].node_id;
1152
1153 /* Create sphinx path */
1154 for (i = 0; i < n_hops - 1; i++) {
1155 ret = pubkey_from_node_id(&pubkey, &ids[i]);
1156 assert(ret);
1157
1158 sphinx_add_hop(path, &pubkey,
1159 take(onion_nonfinal_hop(NULL,
1160 should_use_tlv(route[i].style),
1161 &route[i + 1].scid,
1162 route[i + 1].amount,
1163 base_expiry + route[i + 1].delay,
1164 route[i].blinding,
1165 route[i].enctlv)));
1166 }
1167
1168 /* And finally set the final hop to the special values in
1169 * BOLT04 */
1170 ret = pubkey_from_node_id(&pubkey, &ids[i]);
1171 assert(ret);
1172
1173 final_tlv = should_use_tlv(route[i].style);
1174 /* BOLT #4:
1175 * - Unless `node_announcement`, `init` message or the
1176 * [BOLT #11](11-payment-encoding.md#tagged-fields) offers feature
1177 * `var_onion_optin`:
1178 * - MUST use the legacy payload format instead.
1179 */
1180 /* In our case, we don't use it unless we also have a payment_secret;
1181 * everyone should support this eventually */
1182 if (!final_tlv && payment_secret)
1183 final_tlv = true;
1184
1185 /* Parallel payments are invalid for legacy. */
1186 if (partid && !final_tlv)
1187 return command_fail(cmd, PAY_DESTINATION_PERM_FAIL,
1188 "Cannot do parallel payments to legacy node");
1189
1190 onion = onion_final_hop(cmd,
1191 final_tlv,
1192 route[i].amount,
1193 base_expiry + route[i].delay,
1194 total_msat, route[i].blinding, route[i].enctlv,
1195 payment_secret);
1196 if (!onion) {
1197 return command_fail(cmd, PAY_DESTINATION_PERM_FAIL,
1198 "Destination does not support"
1199 " payment_secret");
1200 }
1201 sphinx_add_hop(path, &pubkey, onion);
1202
1203 /* Copy channels used along the route. */
1204 channels = tal_arr(tmpctx, struct short_channel_id, n_hops);
1205 for (i = 0; i < n_hops; ++i)
1206 channels[i] = route[i].scid;
1207
1208 log_info(ld->log, "Sending %s over %zu hops to deliver %s",
1209 type_to_string(tmpctx, struct amount_msat, &route[0].amount),
1210 n_hops, type_to_string(tmpctx, struct amount_msat, &msat));
1211 packet = create_onionpacket(tmpctx, path, ROUTING_INFO_SIZE, &path_secrets);
1212 return send_payment_core(ld, cmd, rhash, partid, group, &route[0],
1213 msat, total_msat, label, invstring,
1214 packet, &ids[n_hops - 1], ids,
1215 channels, path_secrets, local_offer_id);
1216 }
1217
1218 static struct command_result *
param_route_hop(struct command * cmd,const char * name,const char * buffer,const jsmntok_t * tok,struct route_hop ** hop)1219 param_route_hop(struct command *cmd, const char *name, const char *buffer,
1220 const jsmntok_t *tok, struct route_hop **hop)
1221 {
1222 const jsmntok_t *idtok, *channeltok, *amounttok, *delaytok;
1223 struct route_hop *res;
1224
1225 res = tal(cmd, struct route_hop);
1226 idtok = json_get_member(buffer, tok, "id");
1227 channeltok = json_get_member(buffer, tok, "channel");
1228 amounttok = json_get_member(buffer, tok, "amount_msat");
1229 delaytok = json_get_member(buffer, tok, "delay");
1230
1231 /* General verification that all fields that we need are present. */
1232 if (!idtok && !channeltok)
1233 return command_fail(
1234 cmd, JSONRPC2_INVALID_PARAMS,
1235 "Either 'id' or 'channel' is required for a route_hop");
1236
1237 if (!amounttok)
1238 return command_fail(cmd, JSONRPC2_INVALID_PARAMS,
1239 "'amount_msat' is required");
1240
1241 if (!delaytok)
1242 return command_fail(cmd, JSONRPC2_INVALID_PARAMS,
1243 "'delay' is required");
1244
1245 /* Parsing of actual values including sanity check for all parsed
1246 * values. */
1247 if (!idtok) {
1248 memset(&res->node_id, 0, sizeof(struct node_id));
1249 } else if (!json_to_node_id(buffer, idtok, &res->node_id)) {
1250 return command_fail_badparam(cmd, name, buffer, idtok,
1251 "should be a node_id");
1252 }
1253
1254 if (!channeltok) {
1255 memset(&res->scid, 0, sizeof(struct short_channel_id));
1256 } else if (!json_to_short_channel_id(buffer, channeltok, &res->scid)) {
1257 return command_fail_badparam(cmd, name, buffer, channeltok,
1258 "should be a short_channel_id");
1259 }
1260
1261 if (!json_to_msat(buffer, amounttok, &res->amount))
1262 return command_fail_badparam(cmd, name, buffer, amounttok,
1263 "should be a valid amount_msat");
1264
1265 if (!json_to_number(buffer, delaytok, &res->delay) || res->delay < 1)
1266 return command_fail_badparam(cmd, name, buffer, delaytok,
1267 "should be a positive, non-zero, number");
1268
1269 *hop = res;
1270 return NULL;
1271 }
1272
json_sendonion(struct command * cmd,const char * buffer,const jsmntok_t * obj UNNEEDED,const jsmntok_t * params)1273 static struct command_result *json_sendonion(struct command *cmd,
1274 const char *buffer,
1275 const jsmntok_t *obj UNNEEDED,
1276 const jsmntok_t *params)
1277 {
1278 u8 *onion;
1279 struct onionpacket *packet;
1280 enum onion_wire failcode;
1281 struct route_hop *first_hop;
1282 struct sha256 *payment_hash;
1283 struct lightningd *ld = cmd->ld;
1284 const char *label, *invstring;
1285 struct node_id *destination;
1286 struct secret *path_secrets;
1287 struct amount_msat *msat;
1288 u64 *partid, *group;
1289 struct sha256 *local_offer_id = NULL;
1290
1291 if (!param(cmd, buffer, params,
1292 p_req("onion", param_bin_from_hex, &onion),
1293 p_req("first_hop", param_route_hop, &first_hop),
1294 p_req("payment_hash", param_sha256, &payment_hash),
1295 p_opt("label", param_escaped_string, &label),
1296 p_opt("shared_secrets", param_secrets_array, &path_secrets),
1297 p_opt_def("partid", param_u64, &partid, 0),
1298 /* FIXME: parameter should be invstring now */
1299 p_opt("bolt11", param_string, &invstring),
1300 p_opt_def("msatoshi", param_msat, &msat, AMOUNT_MSAT(0)),
1301 p_opt("destination", param_node_id, &destination),
1302 p_opt("localofferid", param_sha256, &local_offer_id),
1303 p_opt("groupid", param_u64, &group),
1304 NULL))
1305 return command_param_failed();
1306
1307 /* If groupid was not provided default to incrementing from the previous one. */
1308 if (group == NULL) {
1309 group = tal(tmpctx, u64);
1310 *group =
1311 wallet_payment_get_groupid(cmd->ld->wallet, payment_hash) +
1312 1;
1313 }
1314
1315 packet = parse_onionpacket(cmd, onion, tal_bytelen(onion), &failcode);
1316
1317 if (!packet)
1318 return command_fail(cmd, JSONRPC2_INVALID_PARAMS,
1319 "Could not parse the onion. Parsing failed "
1320 "with failcode=%d",
1321 failcode);
1322
1323 return send_payment_core(ld, cmd, payment_hash, *partid, *group,
1324 first_hop, *msat, AMOUNT_MSAT(0),
1325 label, invstring, packet, destination, NULL, NULL,
1326 path_secrets, local_offer_id);
1327 }
1328
1329 static const struct json_command sendonion_command = {
1330 "sendonion",
1331 "payment",
1332 json_sendonion,
1333 "Send a payment with a pre-computed onion."
1334 };
1335 AUTODATA(json_command, &sendonion_command);
1336
1337 /*-----------------------------------------------------------------------------
1338 JSON-RPC sendpay interface
1339 -----------------------------------------------------------------------------*/
1340
param_route_hop_style(struct command * cmd,const char * name,const char * buffer,const jsmntok_t * tok,enum route_hop_style ** style)1341 static struct command_result *param_route_hop_style(struct command *cmd,
1342 const char *name,
1343 const char *buffer,
1344 const jsmntok_t *tok,
1345 enum route_hop_style **style)
1346 {
1347 *style = tal(cmd, enum route_hop_style);
1348 if (json_tok_streq(buffer, tok, "legacy")) {
1349 **style = ROUTE_HOP_LEGACY;
1350 return NULL;
1351 } else if (json_tok_streq(buffer, tok, "tlv")) {
1352 **style = ROUTE_HOP_TLV;
1353 return NULL;
1354 }
1355
1356 return command_fail_badparam(cmd, name, buffer, tok,
1357 "should be 'legacy' or 'tlv'");
1358 }
1359
param_route_hops(struct command * cmd,const char * name,const char * buffer,const jsmntok_t * tok,struct route_hop ** hops)1360 static struct command_result *param_route_hops(struct command *cmd,
1361 const char *name,
1362 const char *buffer,
1363 const jsmntok_t *tok,
1364 struct route_hop **hops)
1365 {
1366 size_t i;
1367 const jsmntok_t *t;
1368
1369 if (tok->type != JSMN_ARRAY || tok->size == 0)
1370 return command_fail(cmd, JSONRPC2_INVALID_PARAMS,
1371 "%s must be an (non-empty) array", name);
1372
1373 *hops = tal_arr(cmd, struct route_hop, tok->size);
1374 json_for_each_arr(i, t, tok) {
1375 struct amount_msat *msat, *amount_msat;
1376 struct node_id *id;
1377 struct short_channel_id *channel;
1378 unsigned *delay, *direction;
1379 struct pubkey *blinding;
1380 u8 *enctlv;
1381 enum route_hop_style *style, default_style;
1382
1383 if (!param(cmd, buffer, t,
1384 /* Only *one* of these is required */
1385 p_opt("msatoshi", param_msat, &msat),
1386 p_opt("amount_msat", param_msat, &amount_msat),
1387 /* These three actually required */
1388 p_opt("id", param_node_id, &id),
1389 p_opt("delay", param_number, &delay),
1390 p_opt("channel", param_short_channel_id, &channel),
1391 /* Allowed (getroute supplies it) but ignored */
1392 p_opt("direction", param_number, &direction),
1393 p_opt("style", param_route_hop_style, &style),
1394 p_opt("blinding", param_pubkey, &blinding),
1395 p_opt("enctlv", param_bin_from_hex, &enctlv),
1396 NULL))
1397 return command_param_failed();
1398
1399 if (!msat && !amount_msat)
1400 return command_fail(cmd, JSONRPC2_INVALID_PARAMS,
1401 "%s[%zi]: must have msatoshi"
1402 " or amount_msat", name, i);
1403 if (!id || !channel || !delay)
1404 return command_fail(cmd, JSONRPC2_INVALID_PARAMS,
1405 "%s[%zi]: must have id, channel"
1406 " and delay", name, i);
1407 if (msat && amount_msat && !amount_msat_eq(*msat, *amount_msat))
1408 return command_fail(cmd, JSONRPC2_INVALID_PARAMS,
1409 "%s[%zi]: msatoshi %s != amount_msat %s",
1410 name, i,
1411 type_to_string(tmpctx,
1412 struct amount_msat,
1413 msat),
1414 type_to_string(tmpctx,
1415 struct amount_msat,
1416 amount_msat));
1417 if (!msat)
1418 msat = amount_msat;
1419
1420 if (blinding || enctlv) {
1421 if (style && *style == ROUTE_HOP_LEGACY)
1422 return command_fail(cmd, JSONRPC2_INVALID_PARAMS,
1423 "%s[%zi]: Can't have blinding or enctlv with legacy", name, i);
1424 default_style = ROUTE_HOP_TLV;
1425 } else
1426 default_style = ROUTE_HOP_LEGACY;
1427
1428 (*hops)[i].amount = *msat;
1429 (*hops)[i].node_id = *id;
1430 (*hops)[i].delay = *delay;
1431 (*hops)[i].scid = *channel;
1432 (*hops)[i].blinding = blinding;
1433 (*hops)[i].enctlv = enctlv;
1434 (*hops)[i].style = style ? *style : default_style;
1435 }
1436
1437 return NULL;
1438 }
1439
json_sendpay(struct command * cmd,const char * buffer,const jsmntok_t * obj UNNEEDED,const jsmntok_t * params)1440 static struct command_result *json_sendpay(struct command *cmd,
1441 const char *buffer,
1442 const jsmntok_t *obj UNNEEDED,
1443 const jsmntok_t *params)
1444 {
1445 struct sha256 *rhash;
1446 struct route_hop *route;
1447 struct amount_msat *msat;
1448 const char *invstring, *label;
1449 u64 *partid, *group;
1450 struct secret *payment_secret;
1451 struct sha256 *local_offer_id = NULL;
1452
1453 /* For generating help, give new-style. */
1454 if (!param(cmd, buffer, params,
1455 p_req("route", param_route_hops, &route),
1456 p_req("payment_hash", param_sha256, &rhash),
1457 p_opt("label", param_escaped_string, &label),
1458 p_opt("msatoshi", param_msat, &msat),
1459 /* FIXME: parameter should be invstring now */
1460 p_opt("bolt11", param_string, &invstring),
1461 p_opt("payment_secret", param_secret, &payment_secret),
1462 p_opt_def("partid", param_u64, &partid, 0),
1463 p_opt("localofferid", param_sha256, &local_offer_id),
1464 p_opt("groupid", param_u64, &group),
1465 NULL))
1466 return command_param_failed();
1467
1468 if (*partid && !msat)
1469 return command_fail(cmd, JSONRPC2_INVALID_PARAMS,
1470 "Must specify msatoshi with partid");
1471
1472 const struct amount_msat final_amount = route[tal_count(route)-1].amount;
1473
1474 /* If groupid was not provided default to incrementing from the previous one. */
1475 if (group == NULL) {
1476 group = tal(tmpctx, u64);
1477 *group = wallet_payment_get_groupid(cmd->ld->wallet, rhash) + 1;
1478 }
1479
1480 if (msat && !*partid && !amount_msat_eq(*msat, final_amount))
1481 return command_fail(cmd, JSONRPC2_INVALID_PARAMS,
1482 "Do not specify msatoshi (%s) without"
1483 " partid: if you do, it must be exactly"
1484 " the final amount (%s)",
1485 type_to_string(tmpctx, struct amount_msat,
1486 msat),
1487 type_to_string(tmpctx, struct amount_msat,
1488 &final_amount));
1489
1490 /* For MPP, the total we send must *exactly* equal the amount
1491 * we promise to send (msatoshi). So no single payment can be
1492 * > than that. */
1493 if (*partid) {
1494 if (amount_msat_greater(final_amount, *msat))
1495 return command_fail(cmd, JSONRPC2_INVALID_PARAMS,
1496 "Final amount %s is greater than"
1497 " %s, despite MPP",
1498 type_to_string(tmpctx,
1499 struct amount_msat,
1500 &final_amount),
1501 type_to_string(tmpctx,
1502 struct amount_msat,
1503 msat));
1504 }
1505
1506 if (*partid && !payment_secret)
1507 return command_fail(cmd, JSONRPC2_INVALID_PARAMS,
1508 "partid requires payment_secret");
1509
1510 return send_payment(cmd->ld, cmd, rhash, *partid, *group,
1511 route,
1512 final_amount,
1513 msat ? *msat : final_amount,
1514 label, invstring, local_offer_id, payment_secret);
1515 }
1516
1517 static const struct json_command sendpay_command = {
1518 "sendpay",
1519 "payment",
1520 json_sendpay,
1521 "Send along {route} in return for preimage of {payment_hash}"
1522 };
1523 AUTODATA(json_command, &sendpay_command);
1524
waitsendpay_timeout(struct command * cmd)1525 static void waitsendpay_timeout(struct command *cmd)
1526 {
1527 was_pending(command_fail(cmd, PAY_IN_PROGRESS,
1528 "Timed out while waiting"));
1529 }
1530
json_waitsendpay(struct command * cmd,const char * buffer,const jsmntok_t * obj UNNEEDED,const jsmntok_t * params)1531 static struct command_result *json_waitsendpay(struct command *cmd,
1532 const char *buffer,
1533 const jsmntok_t *obj UNNEEDED,
1534 const jsmntok_t *params)
1535 {
1536 struct sha256 *rhash;
1537 unsigned int *timeout;
1538 struct command_result *res;
1539 u64 *partid, *groupid;
1540
1541 if (!param(cmd, buffer, params,
1542 p_req("payment_hash", param_sha256, &rhash),
1543 p_opt("timeout", param_number, &timeout),
1544 p_opt_def("partid", param_u64, &partid, 0),
1545 p_opt("groupid", param_u64, &groupid),
1546 NULL))
1547 return command_param_failed();
1548
1549 if (groupid == NULL) {
1550 groupid = tal(cmd, u64);
1551 *groupid = wallet_payment_get_groupid(cmd->ld->wallet, rhash);
1552 }
1553 res = wait_payment(cmd->ld, cmd, rhash, *partid, *groupid);
1554 if (res)
1555 return res;
1556
1557 if (timeout)
1558 new_reltimer(cmd->ld->timers, cmd, time_from_sec(*timeout),
1559 &waitsendpay_timeout, cmd);
1560 return command_still_pending(cmd);
1561 }
1562
1563 static const struct json_command waitsendpay_command = {
1564 "waitsendpay",
1565 "payment",
1566 json_waitsendpay,
1567 "Wait for payment attempt on {payment_hash} to succeed or fail, "
1568 "but only up to {timeout} seconds."
1569 };
1570 AUTODATA(json_command, &waitsendpay_command);
1571
json_listsendpays(struct command * cmd,const char * buffer,const jsmntok_t * obj UNNEEDED,const jsmntok_t * params)1572 static struct command_result *json_listsendpays(struct command *cmd,
1573 const char *buffer,
1574 const jsmntok_t *obj UNNEEDED,
1575 const jsmntok_t *params)
1576 {
1577 const struct wallet_payment **payments;
1578 struct json_stream *response;
1579 struct sha256 *rhash;
1580 const char *invstring, *status_str;
1581
1582 if (!param(cmd, buffer, params,
1583 /* FIXME: parameter should be invstring now */
1584 p_opt("bolt11", param_string, &invstring),
1585 p_opt("payment_hash", param_sha256, &rhash),
1586 p_opt("status", param_string, &status_str),
1587 NULL))
1588 return command_param_failed();
1589
1590 if (rhash && invstring) {
1591 return command_fail(cmd, JSONRPC2_INVALID_PARAMS,
1592 "Can only specify one of"
1593 " {bolt11} or {payment_hash}");
1594 }
1595
1596 if (invstring) {
1597 struct bolt11 *b11;
1598 char *fail;
1599
1600 b11 = bolt11_decode(cmd, invstring, cmd->ld->our_features, NULL,
1601 chainparams, &fail);
1602 if (b11) {
1603 rhash = &b11->payment_hash;
1604 } else {
1605 struct tlv_invoice *b12;
1606
1607 b12 = invoice_decode(cmd, invstring, strlen(invstring),
1608 cmd->ld->our_features,
1609 chainparams, &fail);
1610 if (b12 && b12->payment_hash)
1611 rhash = b12->payment_hash;
1612 else
1613 return command_fail(cmd, JSONRPC2_INVALID_PARAMS,
1614 "Invalid invstring: %s", fail);
1615 }
1616 }
1617
1618 if (status_str) {
1619 enum wallet_payment_status status;
1620
1621 if (!string_to_payment_status(status_str, &status))
1622 return command_fail(cmd, JSONRPC2_INVALID_PARAMS, "Unrecognized status: %s", status_str);
1623 payments = wallet_payment_list(cmd, cmd->ld->wallet, rhash, &status);
1624 } else
1625 payments = wallet_payment_list(cmd, cmd->ld->wallet, rhash, NULL);
1626
1627 response = json_stream_success(cmd);
1628
1629 json_array_start(response, "payments");
1630 for (size_t i = 0; i < tal_count(payments); i++) {
1631 json_object_start(response, NULL);
1632 json_add_payment_fields(response, payments[i]);
1633 json_object_end(response);
1634 }
1635 json_array_end(response);
1636
1637 return command_success(cmd, response);
1638 }
1639
1640 static const struct json_command listsendpays_command = {
1641 "listsendpays",
1642 "payment",
1643 json_listsendpays,
1644 "Show sendpay, old and current, optionally limiting to {bolt11} or {payment_hash}."
1645 };
1646 AUTODATA(json_command, &listsendpays_command);
1647
1648
json_delpay(struct command * cmd,const char * buffer,const jsmntok_t * obj UNNEEDED,const jsmntok_t * params)1649 static struct command_result *json_delpay(struct command *cmd,
1650 const char *buffer,
1651 const jsmntok_t *obj UNNEEDED,
1652 const jsmntok_t *params)
1653 {
1654 struct json_stream *response;
1655 const struct wallet_payment **payments;
1656 const char *status_str;
1657 enum wallet_payment_status status;
1658 struct sha256 *payment_hash;
1659
1660 if (!param(cmd, buffer, params,
1661 p_req("payment_hash", param_sha256, &payment_hash),
1662 p_req("status", param_string, &status_str),
1663 NULL))
1664 return command_param_failed();
1665
1666 if (!string_to_payment_status(status_str, &status))
1667 return command_fail(cmd, JSONRPC2_INVALID_PARAMS, "Unrecognized status: %s", status_str);
1668
1669 switch(status){
1670 case PAYMENT_COMPLETE:
1671 case PAYMENT_FAILED:
1672 break;
1673 case PAYMENT_PENDING:
1674 return command_fail(cmd, JSONRPC2_INVALID_PARAMS, "Invalid status: %s",
1675 payment_status_to_string(status));
1676 }
1677
1678 payments = wallet_payment_list(cmd, cmd->ld->wallet, payment_hash, NULL);
1679
1680 if (tal_count(payments) == 0)
1681 return command_fail(cmd, PAY_NO_SUCH_PAYMENT, "Unknown payment with payment_hash: %s",
1682 type_to_string(tmpctx, struct sha256, payment_hash));
1683
1684 for (int i = 0; i < tal_count(payments); i++) {
1685 if (payments[i]->status != status) {
1686 return command_fail(cmd, PAY_STATUS_UNEXPECTED, "Payment with hash %s has %s status but it should be %s",
1687 type_to_string(tmpctx, struct sha256, payment_hash),
1688 payment_status_to_string(payments[i]->status),
1689 payment_status_to_string(status));
1690 }
1691 }
1692
1693 wallet_payment_delete_by_hash(cmd->ld->wallet, payment_hash);
1694
1695 response = json_stream_success(cmd);
1696 json_array_start(response, "payments");
1697 for (int i = 0; i < tal_count(payments); i++) {
1698 json_object_start(response, NULL);
1699 json_add_payment_fields(response, payments[i]);
1700 json_object_end(response);
1701 }
1702 json_array_end(response);
1703 return command_success(cmd, response);
1704 }
1705
1706 static const struct json_command delpay_command = {
1707 "delpay",
1708 "payment",
1709 json_delpay,
1710 "Delete payment with {payment_hash} and {status}",
1711 };
1712 AUTODATA(json_command, &delpay_command);
1713
json_createonion(struct command * cmd,const char * buffer,const jsmntok_t * obj UNNEEDED,const jsmntok_t * params)1714 static struct command_result *json_createonion(struct command *cmd,
1715 const char *buffer,
1716 const jsmntok_t *obj UNNEEDED,
1717 const jsmntok_t *params)
1718 {
1719 struct json_stream *response;
1720 struct secret *session_key, *shared_secrets;
1721 struct sphinx_path *sp;
1722 u8 *assocdata, *serialized;
1723 u32 *packet_size;
1724 struct onionpacket *packet;
1725 struct sphinx_hop *hops;
1726
1727 if (!param(cmd, buffer, params,
1728 p_req("hops", param_hops_array, &hops),
1729 p_req("assocdata", param_bin_from_hex, &assocdata),
1730 p_opt("session_key", param_secret, &session_key),
1731 p_opt_def("onion_size", param_number, &packet_size, ROUTING_INFO_SIZE),
1732 NULL)) {
1733 return command_param_failed();
1734 }
1735
1736 if (session_key == NULL)
1737 sp = sphinx_path_new(cmd, assocdata);
1738 else
1739 sp = sphinx_path_new_with_key(cmd, assocdata, session_key);
1740
1741 for (size_t i=0; i<tal_count(hops); i++)
1742 sphinx_add_hop(sp, &hops[i].pubkey, hops[i].raw_payload);
1743
1744 if (sphinx_path_payloads_size(sp) > *packet_size)
1745 return command_fail(
1746 cmd, JSONRPC2_INVALID_PARAMS,
1747 "Payloads exceed maximum onion packet size.");
1748
1749 packet = create_onionpacket(cmd, sp, *packet_size, &shared_secrets);
1750 if (!packet)
1751 return command_fail(cmd, LIGHTNINGD,
1752 "Could not create onion packet");
1753
1754 serialized = serialize_onionpacket(cmd, packet);
1755
1756 response = json_stream_success(cmd);
1757 json_add_hex(response, "onion", serialized, tal_bytelen(serialized));
1758 json_array_start(response, "shared_secrets");
1759 for (size_t i=0; i<tal_count(hops); i++) {
1760 json_add_secret(response, NULL, &shared_secrets[i]);
1761 }
1762 json_array_end(response);
1763 return command_success(cmd, response);
1764 }
1765
1766 static const struct json_command createonion_command = {
1767 "createonion",
1768 "payment",
1769 json_createonion,
1770 "Create an onion going through the provided nodes, each with its own payload"
1771 };
1772 AUTODATA(json_command, &createonion_command);
1773