forked from ElementsProject/lightning
-
Notifications
You must be signed in to change notification settings - Fork 0
/
funder.c
1722 lines (1487 loc) · 47.8 KB
/
funder.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* This is a plugin which allows you to specify
* your policy for accepting/dual-funding incoming
* v2 channel-open requests.
*
*/
#include "config.h"
#include <bitcoin/feerate.h>
#include <bitcoin/psbt.h>
#include <ccan/array_size/array_size.h>
#include <ccan/json_out/json_out.h>
#include <ccan/tal/str/str.h>
#include <common/json_param.h>
#include <common/json_stream.h>
#include <common/lease_rates.h>
#include <common/memleak.h>
#include <common/overflows.h>
#include <common/psbt_open.h>
#include <common/type_to_string.h>
#include <plugins/funder_policy.h>
#include <plugins/libplugin.h>
/* In-progress channel opens */
static struct list_head pending_opens;
/* Current set policy */
static struct funder_policy *current_policy;
struct pending_open {
struct list_node list;
struct plugin *p;
struct node_id peer_id;
struct channel_id channel_id;
const struct wally_psbt *psbt;
};
static struct pending_open *
find_channel_pending_open(const struct channel_id *cid)
{
struct pending_open *open;
list_for_each(&pending_opens, open, list) {
if (channel_id_eq(&open->channel_id, cid))
return open;
}
return NULL;
}
static struct pending_open *
new_channel_open(const tal_t *ctx,
struct plugin *p,
const struct node_id id,
const struct channel_id cid,
const struct wally_psbt *psbt STEALS)
{
struct pending_open *open;
/* Make sure we haven't gotten this yet */
assert(!find_channel_pending_open(&cid));
open = tal(ctx, struct pending_open);
open->p = p;
open->peer_id = id;
open->channel_id = cid;
open->psbt = tal_steal(open, psbt);
list_add_tail(&pending_opens, &open->list);
return open;
}
static struct command_result *
unreserve_done(struct command *cmd UNUSED,
const char *buf,
const jsmntok_t *result,
struct pending_open *open)
{
plugin_log(open->p, LOG_DBG,
"`unreserveinputs` for channel %s completed. %*.s",
type_to_string(tmpctx, struct channel_id, &open->channel_id),
json_tok_full_len(result),
json_tok_full(buf, result));
tal_free(open);
return command_done();
}
/* Frees open (eventually, in unreserve_done callback) */
static void unreserve_psbt(struct pending_open *open)
{
struct out_req *req;
plugin_log(open->p, LOG_DBG,
"Calling `unreserveinputs` for channel %s",
type_to_string(tmpctx, struct channel_id,
&open->channel_id));
req = jsonrpc_request_start(open->p, NULL,
"unreserveinputs",
unreserve_done, unreserve_done,
open);
json_add_psbt(req->js, "psbt", open->psbt);
send_outreq(open->p, req);
/* We will free this in callback, but remove from list *now*
* to avoid calling twice! */
list_del_from(&pending_opens, &open->list);
notleak(open);
}
static void cleanup_peer_pending_opens(const struct node_id *id)
{
struct pending_open *i, *next;
list_for_each_safe(&pending_opens, i, next, list) {
if (node_id_eq(&i->peer_id, id)) {
unreserve_psbt(i);
}
}
}
static struct command_result *
command_hook_cont_psbt(struct command *cmd, struct wally_psbt *psbt)
{
struct json_stream *response;
response = jsonrpc_stream_success(cmd);
json_add_string(response, "result", "continue");
json_add_psbt(response, "psbt", psbt);
return command_finished(cmd, response);
}
static struct command_result *
datastore_del_fail(struct command *cmd,
const char *buf,
const jsmntok_t *error,
void *data UNUSED)
{
/* Eh, ok fine */
return notification_handled(cmd);
}
static struct command_result *
datastore_del_success(struct command *cmd,
const char *buf,
const jsmntok_t *result,
void *data UNUSED)
{
/* Cool we deleted some stuff */
plugin_log(cmd->plugin, LOG_DBG,
"`datastore` del succeeded: %*.s",
json_tok_full_len(result),
json_tok_full(buf, result));
return notification_handled(cmd);
}
static struct command_result *
datastore_add_fail(struct command *cmd,
const char *buf,
const jsmntok_t *error,
struct wally_psbt *signed_psbt)
{
/* Oops, something's broken */
plugin_log(cmd->plugin, LOG_BROKEN,
"`datastore` add failed: %*.s",
json_tok_full_len(error),
json_tok_full(buf, error));
return command_hook_cont_psbt(cmd, signed_psbt);
}
static struct command_result *
datastore_add_success(struct command *cmd,
const char *buf,
const jsmntok_t *result,
struct wally_psbt *signed_psbt)
{
const char *key, *err;
err = json_scan(tmpctx, buf, result,
"{key:%}",
JSON_SCAN_TAL(cmd, json_strdup, &key));
if (err)
plugin_err(cmd->plugin,
"`datastore` payload did not scan. %s: %*.s",
err, json_tok_full_len(result),
json_tok_full(buf, result));
/* We saved the infos! */
plugin_log(cmd->plugin, LOG_DBG,
"Saved utxos for channel (%s) to datastore",
key);
return command_hook_cont_psbt(cmd, signed_psbt);
}
static struct command_result *
remember_channel_utxos(struct command *cmd,
struct pending_open *open,
struct wally_psbt *signed_psbt)
{
struct out_req *req;
u8 *utxos_bin;
char *chan_key = tal_fmt(cmd, "funder/%s",
type_to_string(cmd, struct channel_id,
&open->channel_id));
req = jsonrpc_request_start(cmd->plugin, cmd,
"datastore",
&datastore_add_success,
&datastore_add_fail,
signed_psbt);
utxos_bin = tal_arr(cmd, u8, 0);
for (size_t i = 0; i < signed_psbt->num_inputs; i++) {
struct bitcoin_outpoint outpoint;
/* Don't save peer's UTXOS */
if (!psbt_input_is_ours(&signed_psbt->inputs[i]))
continue;
wally_psbt_input_get_outpoint(&signed_psbt->inputs[i],
&outpoint);
towire_bitcoin_outpoint(&utxos_bin, &outpoint);
}
json_add_string(req->js, "key", chan_key);
/* We either update the existing or add a new one, nbd */
json_add_string(req->js, "mode", "create-or-replace");
json_add_hex(req->js, "hex", utxos_bin, tal_bytelen(utxos_bin));
return send_outreq(cmd->plugin, req);
}
static struct command_result *
signpsbt_done(struct command *cmd,
const char *buf,
const jsmntok_t *result,
struct pending_open *open)
{
struct wally_psbt *signed_psbt;
struct command_result *res;
const char *err;
plugin_log(cmd->plugin, LOG_DBG,
"`signpsbt` done for channel %s",
type_to_string(tmpctx, struct channel_id,
&open->channel_id));
err = json_scan(tmpctx, buf, result,
"{signed_psbt:%}",
JSON_SCAN_TAL(cmd, json_to_psbt, &signed_psbt));
if (err)
plugin_err(cmd->plugin,
"`signpsbt` payload did not scan %s: %*.s",
err, json_tok_full_len(result),
json_tok_full(buf, result));
/* Save the list of utxos to the datastore! We'll need
* them again if we rbf */
res = remember_channel_utxos(cmd, open, signed_psbt);
/* The in-flight open is done, let's clean it up! */
list_del_from(&pending_opens, &open->list);
tal_free(open);
return res;
}
static struct command_result *
json_openchannel2_sign_call(struct command *cmd,
const char *buf,
const jsmntok_t *params)
{
struct channel_id cid;
struct wally_psbt *psbt;
const char *err;
struct out_req *req;
struct pending_open *open;
size_t count;
err = json_scan(tmpctx, buf, params,
"{openchannel2_sign:"
"{channel_id:%,psbt:%}}",
JSON_SCAN(json_to_channel_id, &cid),
JSON_SCAN_TAL(cmd, json_to_psbt, &psbt));
if (err)
plugin_err(cmd->plugin,
"`openchannel2_sign` payload did not scan %s: %.*s",
err, json_tok_full_len(params),
json_tok_full(buf, params));
/* If we're not tracking this open, just pass through */
open = find_channel_pending_open(&cid);
if (!open) {
plugin_log(cmd->plugin, LOG_DBG,
"nothing to sign for channel %s",
type_to_string(tmpctx, struct channel_id, &cid));
return command_hook_cont_psbt(cmd, psbt);
}
if (!psbt_has_our_input(psbt)) {
plugin_log(cmd->plugin, LOG_DBG,
"no inputs to sign for channel %s",
type_to_string(tmpctx, struct channel_id, &cid));
return command_hook_cont_psbt(cmd, psbt);
}
plugin_log(cmd->plugin, LOG_DBG,
"openchannel_sign PSBT is %s",
type_to_string(tmpctx, struct wally_psbt, psbt));
req = jsonrpc_request_start(cmd->plugin, cmd,
"signpsbt",
&signpsbt_done,
&forward_error,
open);
json_add_psbt(req->js, "psbt", psbt);
/* Use input markers to identify which inputs
* are ours, only sign those */
json_array_start(req->js, "signonly");
count = 0;
for (size_t i = 0; i < psbt->num_inputs; i++) {
if (psbt_input_is_ours(&psbt->inputs[i])) {
json_add_num(req->js, NULL, i);
count++;
}
}
json_array_end(req->js);
plugin_log(cmd->plugin, LOG_DBG,
"calling `signpsbt` for channel %s for %zu input%s",
type_to_string(tmpctx, struct channel_id,
&open->channel_id), count,
count == 1 ? "" : "s");
return send_outreq(cmd->plugin, req);
}
static struct command_result *
json_openchannel2_changed_call(struct command *cmd,
const char *buf,
const jsmntok_t *params)
{
struct channel_id cid;
struct wally_psbt *psbt;
const char *err;
err = json_scan(tmpctx, buf, params,
"{openchannel2_changed:"
"{channel_id:%,psbt:%}}",
JSON_SCAN(json_to_channel_id, &cid),
JSON_SCAN_TAL(cmd, json_to_psbt, &psbt));
if (err)
plugin_err(cmd->plugin,
"`openchannel2_changed` payload did not"
" scan %s: %.*s",
err, json_tok_full_len(params),
json_tok_full(buf, params));
plugin_log(cmd->plugin, LOG_DBG,
"openchannel_changed PSBT is %s",
type_to_string(tmpctx, struct wally_psbt, psbt));
/* FIXME: do we have any additions or updates to make based
* on their changes? */
/* For now, we assume we're the same as before and continue
* on as planned */
return command_hook_cont_psbt(cmd, psbt);
}
/* Tiny struct to pass info to callback for fundpsbt */
struct open_info {
struct channel_id cid;
struct node_id id;
struct amount_sat our_funding;
struct amount_sat their_funding;
/* If this is an RBF, we'll have this */
struct amount_sat *their_last_funding;
struct amount_sat *our_last_funding;
struct amount_sat channel_max;
u64 funding_feerate_perkw;
u32 locktime;
u32 lease_blockheight;
u32 node_blockheight;
struct amount_sat requested_lease;
/* List of previously-used utxos */
struct bitcoin_outpoint **prev_outs;
};
static struct open_info *new_open_info(const tal_t *ctx)
{
struct open_info *info = tal(ctx, struct open_info);
info->their_last_funding = NULL;
info->our_last_funding = NULL;
info->requested_lease = AMOUNT_SAT(0);
info->lease_blockheight = 0;
info->node_blockheight = 0;
info->prev_outs = NULL;
return info;
}
static struct command_result *
psbt_funded(struct command *cmd,
const char *buf,
const jsmntok_t *result,
struct open_info *info)
{
struct wally_psbt *psbt;
struct json_stream *response;
struct amount_msat our_funding_msat;
const char *err;
err = json_scan(tmpctx, buf, result,
"{psbt:%}",
JSON_SCAN_TAL(tmpctx, json_to_psbt, &psbt));
if (err)
plugin_err(cmd->plugin,
"`fundpsbt` response did not scan %s: %.*s",
err, json_tok_full_len(result),
json_tok_full(buf, result));
/* We also mark all of our inputs as *ours*, so we
* can easily identify them for `signpsbt` later */
for (size_t i = 0; i < psbt->num_inputs; i++)
psbt_input_mark_ours(psbt, &psbt->inputs[i]);
new_channel_open(cmd->plugin, cmd->plugin,
info->id, info->cid, psbt);
if (!amount_sat_to_msat(&our_funding_msat, info->our_funding))
abort();
response = jsonrpc_stream_success(cmd);
json_add_string(response, "result", "continue");
json_add_psbt(response, "psbt", psbt);
json_add_amount_msat(response, "our_funding_msat", our_funding_msat);
/* If we're accepting an lease request, *and* they've
* requested one, fill in our most recent infos */
if (current_policy->rates && !amount_sat_zero(info->requested_lease))
json_add_lease_rates(response, current_policy->rates);
return command_finished(cmd, response);
}
static struct command_result *
psbt_fund_failed(struct command *cmd,
const char *buf,
const jsmntok_t *error,
struct open_info *info)
{
/* Attempt to fund a psbt for this open failed.
* We probably ran out of funds (race?) */
plugin_log(cmd->plugin, LOG_INFORM,
"Unable to secure %s from wallet,"
" continuing channel open to %s"
" without our participation. err %.*s",
type_to_string(tmpctx, struct amount_sat,
&info->our_funding),
type_to_string(tmpctx, struct node_id,
&info->id),
json_tok_full_len(error),
json_tok_full(buf, error));
return command_hook_success(cmd);
}
/* They give msats, we want sats */
static bool json_to_msat_as_sats(const char *buffer, const jsmntok_t *tok,
struct amount_sat *sat)
{
struct amount_msat msat;
if (!json_to_msat(buffer, tok, &msat))
return false;
return amount_msat_to_sat(sat, msat);
}
static struct command_result *param_msat_as_sat(struct command *cmd,
const char *name,
const char *buffer,
const jsmntok_t *tok,
struct amount_sat **sat)
{
struct amount_msat msat;
*sat = tal(cmd, struct amount_sat);
if (parse_amount_msat(&msat, buffer + tok->start, tok->end - tok->start)
&& amount_msat_to_sat(*sat, msat))
return NULL;
return command_fail_badparam(cmd, name, buffer, tok,
"should be a millisatoshi amount");
}
static struct bitcoin_outpoint *
previously_reserved(struct bitcoin_outpoint **prev_outs,
struct bitcoin_outpoint *out)
{
for (size_t i = 0; i < tal_count(prev_outs); i++) {
if (bitcoin_outpoint_eq(prev_outs[i], out))
return prev_outs[i];
}
return NULL;
}
struct funder_utxo {
struct bitcoin_outpoint out;
struct amount_sat val;
};
static struct out_req *
build_utxopsbt_request(struct command *cmd,
struct open_info *info,
struct bitcoin_outpoint **prev_outs,
struct amount_sat requested_funds,
struct amount_sat committed_funds,
struct funder_utxo **avail_utxos)
{
struct out_req *req;
req = jsonrpc_request_start(cmd->plugin, cmd,
"utxopsbt",
&psbt_funded,
&psbt_fund_failed,
info);
/* Add every prev_out */
json_array_start(req->js, "utxos");
for (size_t i = 0; i < tal_count(prev_outs); i++)
json_add_outpoint(req->js, NULL, prev_outs[i]);
/* Next add available utxos until we surpass the
* requested funds goal */
/* FIXME: Update `utxopsbt` to automatically add more inputs? */
for (size_t i = 0; i < tal_count(avail_utxos); i++) {
/* If we've already hit our goal, break */
if (amount_sat_greater_eq(committed_funds, requested_funds))
break;
/* Add this output to the UTXO */
json_add_outpoint(req->js, NULL, &avail_utxos[i]->out);
/* Account for it */
if (!amount_sat_add(&committed_funds, committed_funds,
avail_utxos[i]->val))
/* This should really never happen */
plugin_err(cmd->plugin, "overflow adding committed");
}
json_array_end(req->js);
return req;
}
static struct command_result *
listfunds_success(struct command *cmd,
const char *buf,
const jsmntok_t *result,
struct open_info *info)
{
struct amount_sat available_funds, committed_funds, est_fee;
const jsmntok_t *outputs_tok, *tok;
struct out_req *req;
struct bitcoin_outpoint **avail_prev_outs;
size_t i;
const char *funding_err;
/* We only use this for RBFs, when there's a prev_outs list */
struct funder_utxo **avail_utxos = tal_arr(cmd, struct funder_utxo *, 0);
outputs_tok = json_get_member(buf, result, "outputs");
if (!outputs_tok)
plugin_err(cmd->plugin,
"`listfunds` payload has no outputs token: %*.s",
json_tok_full_len(result),
json_tok_full(buf, result));
available_funds = AMOUNT_SAT(0);
committed_funds = AMOUNT_SAT(0);
avail_prev_outs = tal_arr(info, struct bitcoin_outpoint *, 0);
json_for_each_arr(i, tok, outputs_tok) {
struct funder_utxo *utxo;
bool is_reserved;
struct bitcoin_outpoint *prev_out;
char *status;
const char *err;
utxo = tal(cmd, struct funder_utxo);
err = json_scan(tmpctx, buf, tok,
"{amount_msat:%"
",status:%"
",reserved:%"
",txid:%"
",output:%}",
JSON_SCAN(json_to_msat_as_sats, &utxo->val),
JSON_SCAN_TAL(cmd, json_strdup, &status),
JSON_SCAN(json_to_bool, &is_reserved),
JSON_SCAN(json_to_txid, &utxo->out.txid),
JSON_SCAN(json_to_number, &utxo->out.n));
if (err)
plugin_err(cmd->plugin,
"`listfunds` payload did not scan. %s: %*.s",
err, json_tok_full_len(result),
json_tok_full(buf, result));
/* v2 opens don't support p2sh-wrapped inputs */
if (json_get_member(buf, tok, "redeemscript"))
continue;
/* The estimated fee per utxo. */
est_fee = amount_tx_fee(info->funding_feerate_perkw,
bitcoin_tx_input_weight(false, 110));
/* Did we use this utxo on a previous attempt? */
prev_out = previously_reserved(info->prev_outs, &utxo->out);
/* we skip reserved funds that aren't in our previous
* inputs list! */
if (is_reserved && !prev_out)
continue;
/* we skip unconfirmed+spent funds */
if (!streq(status, "confirmed"))
continue;
/* Don't include outputs that can't cover their weight;
* subtract the fee for this utxo out of the utxo */
if (!amount_sat_sub(&utxo->val, utxo->val, est_fee))
continue;
if (!amount_sat_add(&available_funds, available_funds,
utxo->val))
plugin_err(cmd->plugin,
"`listfunds` overflowed output values");
/* If this is an RBF, we keep track of available utxos */
if (info->prev_outs) {
/* if not previously reserved, it's committed */
if (!prev_out) {
tal_arr_expand(&avail_utxos, utxo);
continue;
}
if (!amount_sat_add(&committed_funds,
committed_funds, utxo->val))
plugin_err(cmd->plugin,
"`listfunds` overflowed"
" committed output values");
/* We also keep a second list of utxos,
* as it's possible some utxos got spent
* between last attempt + this one! */
tal_arr_expand(&avail_prev_outs, prev_out);
}
}
funding_err = calculate_our_funding(current_policy,
info->id,
info->their_funding,
info->our_last_funding,
available_funds,
info->channel_max,
info->requested_lease,
&info->our_funding);
plugin_log(cmd->plugin, LOG_DBG,
"Policy %s returned funding amount of %s. %s",
funder_policy_desc(tmpctx, current_policy),
type_to_string(tmpctx, struct amount_sat,
&info->our_funding),
funding_err ? funding_err : "");
if (amount_sat_zero(info->our_funding))
return command_hook_success(cmd);
plugin_log(cmd->plugin, LOG_DBG,
"Funding channel %s with %s (their input %s)",
type_to_string(tmpctx, struct channel_id, &info->cid),
type_to_string(tmpctx, struct amount_sat,
&info->our_funding),
type_to_string(tmpctx, struct amount_sat,
&info->their_funding));
/* If there's prevouts, we compose a psbt with those first,
* then add more funds for anything missing */
if (info->prev_outs) {
req = build_utxopsbt_request(cmd, info,
avail_prev_outs,
info->our_funding,
committed_funds,
avail_utxos);
json_add_bool(req->js, "reservedok", true);
} else {
req = jsonrpc_request_start(cmd->plugin, cmd,
"fundpsbt",
&psbt_funded,
&psbt_fund_failed,
info);
json_add_bool(req->js, "nonwrapped", true);
}
json_add_string(req->js, "satoshi",
type_to_string(tmpctx, struct amount_sat,
&info->our_funding));
json_add_string(req->js, "feerate",
tal_fmt(tmpctx, "%"PRIu64"%s",
info->funding_feerate_perkw,
feerate_style_name(FEERATE_PER_KSIPA)));
/* Our startweight is zero because we're freeriding on their open
* transaction ! */
json_add_num(req->js, "startweight", 0);
json_add_num(req->js, "min_witness_weight", 110);
json_add_bool(req->js, "excess_as_change", true);
json_add_num(req->js, "locktime", info->locktime);
return send_outreq(cmd->plugin, req);
}
static struct command_result *
listfunds_failed(struct command *cmd,
const char *buf,
const jsmntok_t *error,
struct open_info *info)
{
/* Something went wrong fetching the funds info
* for our wallet. Just keep going */
plugin_log(cmd->plugin, LOG_INFORM,
"Unable to fetch wallet funds info."
" Continuing channel open to %s"
" without our participation. err %.*s",
type_to_string(tmpctx, struct node_id,
&info->id),
json_tok_full_len(error),
json_tok_full(buf, error));
return command_hook_success(cmd);
}
static struct command_result *
json_openchannel2_call(struct command *cmd,
const char *buf,
const jsmntok_t *params)
{
struct open_info *info = new_open_info(cmd);
struct amount_msat max_htlc_inflight, htlc_minimum;
u64 commitment_feerate_perkw,
feerate_our_max, feerate_our_min;
u32 to_self_delay, max_accepted_htlcs;
u16 channel_flags;
const char *err;
struct out_req *req;
err = json_scan(tmpctx, buf, params,
"{openchannel2:"
"{id:%"
",channel_id:%"
",their_funding_msat:%"
",max_htlc_value_in_flight_msat:%"
",htlc_minimum_msat:%"
",funding_feerate_per_kw:%"
",commitment_feerate_per_kw:%"
",feerate_our_max:%"
",feerate_our_min:%"
",to_self_delay:%"
",max_accepted_htlcs:%"
",channel_flags:%"
",locktime:%"
",channel_max_msat:%}}",
JSON_SCAN(json_to_node_id, &info->id),
JSON_SCAN(json_to_channel_id, &info->cid),
JSON_SCAN(json_to_msat_as_sats, &info->their_funding),
JSON_SCAN(json_to_msat, &max_htlc_inflight),
JSON_SCAN(json_to_msat, &htlc_minimum),
JSON_SCAN(json_to_u64, &info->funding_feerate_perkw),
JSON_SCAN(json_to_u64, &commitment_feerate_perkw),
JSON_SCAN(json_to_u64, &feerate_our_max),
JSON_SCAN(json_to_u64, &feerate_our_min),
JSON_SCAN(json_to_u32, &to_self_delay),
JSON_SCAN(json_to_u32, &max_accepted_htlcs),
JSON_SCAN(json_to_u16, &channel_flags),
JSON_SCAN(json_to_u32, &info->locktime),
JSON_SCAN(json_to_msat_as_sats, &info->channel_max));
if (err)
plugin_err(cmd->plugin,
"`openchannel2` payload did not scan %s: %.*s",
err, json_tok_full_len(params),
json_tok_full(buf, params));
/* Channel lease info isn't necessarily included, ignore any err */
json_scan(tmpctx, buf, params,
"{openchannel2:{"
"requested_lease_msat:%"
",lease_blockheight_start:%"
",node_blockheight:%}}",
JSON_SCAN(json_to_msat_as_sats, &info->requested_lease),
JSON_SCAN(json_to_u32, &info->lease_blockheight),
JSON_SCAN(json_to_u32, &info->node_blockheight));
/* We don't fund anything that's above or below our feerate */
if (info->funding_feerate_perkw < feerate_our_min
|| info->funding_feerate_perkw > feerate_our_max) {
plugin_log(cmd->plugin, LOG_DBG,
"their feerate %"PRIu64" is out of"
" our bounds (%"PRIu64"-%"PRIu64")",
info->funding_feerate_perkw,
feerate_our_min,
feerate_our_max);
return command_hook_success(cmd);
}
/* If they've requested funds, but we're not actually
* supporting requested funds...*/
if (!current_policy->rates &&
!amount_sat_zero(info->requested_lease)) {
struct json_stream *res = jsonrpc_stream_success(cmd);
json_add_string(res, "result", "reject");
json_add_string(res, "error_message",
"Peer requested funds but we're not advertising"
" liquidity right now");
return command_finished(cmd, res);
}
/* Check that their block height isn't too far behind */
if (!amount_sat_zero(info->requested_lease)) {
u32 upper_bound, lower_bound;
/* BOLT- #2:
* The receiving node:
* - MAY fail the negotiation if: ...
* - if the `option_will_fund` tlv is present and:
* - the `blockheight` is considered too far in the
* past or future
*/
/* We consider 24 hrs too far out */
upper_bound = info->node_blockheight + 24 * 6;
lower_bound = info->node_blockheight - 24 * 6;
/* Check overflow */
if (upper_bound < info->node_blockheight)
upper_bound = -1;
if (lower_bound > info->node_blockheight)
lower_bound = 0;
if (upper_bound < info->lease_blockheight
|| lower_bound > info->lease_blockheight) {
plugin_log(cmd->plugin, LOG_DBG,
"their blockheight %d is out of"
" our bounds (ours is %d)",
info->lease_blockheight,
info->node_blockheight);
return command_hook_success(cmd);
}
}
/* Figure out what our funds are */
req = jsonrpc_request_start(cmd->plugin, cmd,
"listfunds",
&listfunds_success,
&listfunds_failed,
info);
return send_outreq(cmd->plugin, req);
}
static struct command_result *
datastore_list_fail(struct command *cmd,
const char *buf,
const jsmntok_t *error,
struct open_info *info)
{
struct out_req *req;
/* Oops, something's broken */
plugin_log(cmd->plugin, LOG_BROKEN,
"`datastore` list failed: %*.s",
json_tok_full_len(error),
json_tok_full(buf, error));
/* Figure out what our funds are... same flow
* as with openchannel2 callback. */
req = jsonrpc_request_start(cmd->plugin, cmd,
"listfunds",
&listfunds_success,
&listfunds_failed,
info);
return send_outreq(cmd->plugin, req);
}
static struct command_result *
datastore_list_success(struct command *cmd,
const char *buf,
const jsmntok_t *result,
struct open_info *info)
{
struct out_req *req;
const char *key, *err;
const u8 *utxos_bin;
size_t len, i;
const jsmntok_t *ds_arr_tok, *ds_result;
ds_arr_tok = json_get_member(buf, result, "datastore");
assert(ds_arr_tok->type == JSMN_ARRAY);
/* There should only be one result */
utxos_bin = NULL;
json_for_each_arr(i, ds_result, ds_arr_tok) {
err = json_scan(tmpctx, buf, ds_result,
"{key:%,hex:%}",
JSON_SCAN_TAL(cmd, json_strdup, &key),
JSON_SCAN_TAL(cmd, json_tok_bin_from_hex,
&utxos_bin));
if (err)
plugin_err(cmd->plugin,
"`listdatastore` payload did"
" not scan. %s: %*.s",
err, json_tok_full_len(result),
json_tok_full(buf, result));
/* We found the prev utxo list */
plugin_log(cmd->plugin, LOG_DBG,
"Saved utxos for channel (%s)"
" pulled from datastore", key);
/* There should only be one result */
break;
}
/* Resurrect outpoints from stashed binary */
len = tal_bytelen(utxos_bin);
while (len > 0) {
struct bitcoin_outpoint *outpoint =
tal(info, struct bitcoin_outpoint);
fromwire_bitcoin_outpoint(&utxos_bin,
&len, outpoint);
/* Cursor gets set to null if above fails */
if (!utxos_bin)
plugin_err(cmd->plugin,
"Unable to parse saved utxos: %.*s",
json_tok_full_len(result),
json_tok_full(buf, result));
if (!info->prev_outs)
info->prev_outs =
tal_arr(info, struct bitcoin_outpoint *, 0);
tal_arr_expand(&info->prev_outs, outpoint);
}
req = jsonrpc_request_start(cmd->plugin, cmd,
"listfunds",
&listfunds_success,
&listfunds_failed,
info);
return send_outreq(cmd->plugin, req);
}
/* Peer has asked us to RBF */
static struct command_result *
json_rbf_channel_call(struct command *cmd,
const char *buf,
const jsmntok_t *params)
{
struct open_info *info = new_open_info(cmd);
u64 feerate_our_max, feerate_our_min;
const char *err, *chan_key;
struct out_req *req;
info->their_last_funding = tal(info, struct amount_sat);
info->our_last_funding = tal(info, struct amount_sat);
err = json_scan(tmpctx, buf, params,
"{rbf_channel:"
"{id:%"
",channel_id:%"
",their_last_funding_msat:%"
",their_funding_msat:%"
",our_last_funding_msat:%"
",funding_feerate_per_kw:%"
",feerate_our_max:%"
",feerate_our_min:%"
",locktime:%"
",channel_max_msat:%}}",
JSON_SCAN(json_to_node_id, &info->id),
JSON_SCAN(json_to_channel_id, &info->cid),
JSON_SCAN(json_to_msat_as_sats,
info->their_last_funding),
JSON_SCAN(json_to_msat_as_sats,