cln-plugin 0.6.0

A CLN plugin library. Write your plugin in Rust.
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
#include "config.h"
#include <bitcoin/psbt.h>
#include <bitcoin/script.h>
#include <ccan/array_size/array_size.h>
#include <ccan/tal/str/str.h>
#include <common/addr.h>
#include <common/channel_type.h>
#include <common/json_channel_type.h>
#include <common/json_param.h>
#include <common/json_stream.h>
#include <common/memleak.h>
#include <common/psbt_open.h>
#include <common/pseudorand.h>
#include <inttypes.h>
#include <plugins/spender/multifundchannel.h>
#include <plugins/spender/openchannel.h>

/* Global counter to create unique mfc->id values */
static u64 mfc_id;

/* Which destinations has a value of "all", or -1.  */
static struct multifundchannel_destination *all_dest(const struct multifundchannel_command *mfc)
{
	for (size_t i = 0; i < tal_count(mfc->destinations); i++) {
		if (mfc->destinations[i].all)
			return &mfc->destinations[i];
	}
	return NULL;
}

size_t dest_count(const struct multifundchannel_command *mfc,
		  enum channel_protocol protocol)
{
	size_t count = 0, i;
	for (i = 0; i < tal_count(mfc->destinations); i++) {
		if (mfc->destinations[i].protocol == protocol)
			count++;
	}
	return count;
}

static void fail_destination(struct multifundchannel_destination *dest)
{
	dest->fail_state = dest->state;
	dest->state = MULTIFUNDCHANNEL_FAILED;
}

void fail_destination_tok(struct multifundchannel_destination *dest,
			  const char *buf,
			  const jsmntok_t *error)
{
	const char *err;
	const jsmntok_t *data_tok;

	err = json_scan(tmpctx, buf, error, "{code:%,message:%}",
			JSON_SCAN(json_to_int, &dest->error_code),
			JSON_SCAN_TAL(dest->mfc,
				      json_strdup,
				      &dest->error_message));
	if (err)
		plugin_err(dest->mfc->cmd->plugin,
			   "`fundchannel_complete` failure failed to parse %s",
			   err);

	data_tok = json_get_member(buf, error, "data");
	if (data_tok)
		dest->error_data = json_strdup(dest->mfc, buf, data_tok);
	else
		dest->error_data = NULL;

	fail_destination(dest);
}

void fail_destination_msg(struct multifundchannel_destination *dest,
			  enum jsonrpc_errcode error_code,
			  const char *err_str TAKES)
{
	dest->error_code = error_code;
	dest->error_message = tal_strdup(dest->mfc, err_str);
	dest->error_data = NULL;

	fail_destination(dest);
}

/* Return true if this destination failed, false otherwise.  */
static bool dest_failed(struct multifundchannel_destination *dest)
{
	return dest->state == MULTIFUNDCHANNEL_FAILED;
}

bool is_v2(const struct multifundchannel_destination *dest)
{
	return dest->protocol == OPEN_CHANNEL;
}

static bool
has_commitments_secured(const struct multifundchannel_destination *dest)
{
	/* If it failed, make sure we hadn't gotten
	 * commitments yet */
	enum multifundchannel_state state = dest->state;
	if (state == MULTIFUNDCHANNEL_FAILED)
		state = dest->fail_state;

	switch (state) {
	case MULTIFUNDCHANNEL_START_NOT_YET:
	case MULTIFUNDCHANNEL_CONNECTED:
	case MULTIFUNDCHANNEL_STARTED:
	case MULTIFUNDCHANNEL_UPDATED:
		return false;
	case MULTIFUNDCHANNEL_COMPLETED:
	case MULTIFUNDCHANNEL_SECURED:
	case MULTIFUNDCHANNEL_SIGNED_NOT_SECURED:
	case MULTIFUNDCHANNEL_SIGNED:
	case MULTIFUNDCHANNEL_DONE:
		return true;
	case MULTIFUNDCHANNEL_FAILED:
		/* Shouldn't be FAILED */
		break;
	}
	abort();
}

/*-----------------------------------------------------------------------------
Command Cleanup
-----------------------------------------------------------------------------*/

/*~
We disallow the use of command_fail and forward_error directly
in the rest of the code.

This ensures that if we ever fail a multifundchannel, we do cleanup
by doing fundchannel_cancel and unreserveinputs.
*/

/* TODO: This is lengthy enough to deserve its own source file,
clocking in at 240 loc.
*/

/* Object for performing cleanup.  */
struct multifundchannel_cleanup {
	size_t pending;
	struct command_result *(*cb)(void *arg);
	void *arg;
};

/* Done when all cleanup operations have completed.  */
static struct command_result *
mfc_cleanup_complete(struct multifundchannel_cleanup *cleanup)
{
	tal_steal(tmpctx, cleanup);
	return cleanup->cb(cleanup->arg);
}

static struct command_result *
mfc_cleanup_done(struct command *cmd,
		 const char *method,
		 const char *buf UNUSED,
		 const jsmntok_t *res UNUSED,
		 struct multifundchannel_cleanup *cleanup)
{
	--cleanup->pending;
	if (cleanup->pending == 0)
		return mfc_cleanup_complete(cleanup);
	else
		return command_still_pending(cmd);
}

static struct command_result *unreserve_call(struct command *cmd,
					     struct wally_psbt *psbt,
					     void *cb, void *cbdata)
{
	struct wally_psbt *pruned_psbt;
	struct out_req *req = jsonrpc_request_start(cmd,
						    "unreserveinputs",
						    cb, cb, cbdata);

	/* We might have peer's inputs on this, get rid of them */
	tal_wally_start();
	if (wally_psbt_clone_alloc(psbt, 0, &pruned_psbt) != WALLY_OK)
		abort();
	tal_wally_end_onto(NULL, pruned_psbt, struct wally_psbt);

	for (size_t i = pruned_psbt->num_inputs - 1;
	     i < pruned_psbt->num_inputs;
	     i--) {
		if (!psbt_input_is_ours(&pruned_psbt->inputs[i]))
			psbt_rm_input(pruned_psbt, i);
	}

	json_add_psbt(req->js, "psbt", take(pruned_psbt));
	json_add_u32(req->js, "reserve", 2016);
	return send_outreq(req);
}

/* Cleans up a txid by doing `txdiscard` on it.  */
static void
mfc_cleanup_psbt(struct command *cmd,
		 struct multifundchannel_cleanup *cleanup,
		 struct wally_psbt *psbt)
{
	unreserve_call(cmd, psbt, mfc_cleanup_done, cleanup);
}

/* Cleans up a `openchannel_init` by doing `openchannel_abort` for the channel*/
static void
mfc_cleanup_oc(struct command *cmd,
	       struct multifundchannel_cleanup *cleanup,
	       struct multifundchannel_destination *dest)
{
	struct out_req *req = jsonrpc_request_start(cmd,
						     "openchannel_abort",
						     &mfc_cleanup_done,
						     &mfc_cleanup_done,
						     cleanup);
	json_add_channel_id(req->js, "channel_id", &dest->channel_id);
	send_outreq(req);
}

/* Cleans up a `fundchannel_start` by doing `fundchannel_cancel` on
the node.
*/
static void
mfc_cleanup_fc(struct command *cmd,
	       struct multifundchannel_cleanup *cleanup,
	       struct multifundchannel_destination *dest)
{
	struct out_req *req = jsonrpc_request_start(cmd,
						    "fundchannel_cancel",
						    &mfc_cleanup_done,
						    &mfc_cleanup_done,
						    cleanup);
	json_add_node_id(req->js, "id", &dest->id);

	send_outreq(req);
}

/* Core cleanup function.  */
static struct command_result *
mfc_cleanup_(struct multifundchannel_command *mfc,
	     struct command_result *(*cb)(void *arg),
	     void *arg)
{
	struct multifundchannel_cleanup *cleanup;
	unsigned int i;

	plugin_log(mfc->cmd->plugin, LOG_DBG,
		   "mfc %"PRIu64": cleanup!", mfc->id);

	cleanup = tal(mfc, struct multifundchannel_cleanup);
	cleanup->pending = 0;
	cleanup->cb = cb;
	cleanup->arg = arg;

	/* If there's commitments, anywhere, we have to fail/restart.
	 * We also cleanup the PSBT if there's no v2's around */
	if (mfc->psbt) {
		plugin_log(mfc->cmd->plugin, LOG_DBG,
			   "mfc %"PRIu64": unreserveinputs task.", mfc->id);

		++cleanup->pending;
		mfc_cleanup_psbt(mfc->cmd, cleanup, mfc->psbt);
	}
	for (i = 0; i < tal_count(mfc->destinations); ++i) {
		struct multifundchannel_destination *dest;
		dest = &mfc->destinations[i];

		switch (dest->state) {
		case MULTIFUNDCHANNEL_STARTED:
			/* v1 handling */
			if (!is_v2(dest)) {
				plugin_log(mfc->cmd->plugin, LOG_DBG,
					   "mfc %"PRIu64", dest %u: "
					   "fundchannel_cancel task.",
					   mfc->id, dest->index);
				++cleanup->pending;
				mfc_cleanup_fc(mfc->cmd, cleanup, dest);
			} else { /* v2 handling */
				plugin_log(mfc->cmd->plugin, LOG_DBG,
					   "mfc %"PRIu64", dest %u:"
					   " openchannel_abort task.",
					   mfc->id, dest->index);
				++cleanup->pending;
				mfc_cleanup_oc(mfc->cmd, cleanup, dest);
			}
			continue;
		case MULTIFUNDCHANNEL_COMPLETED:
			/* Definitely a v1 */
			plugin_log(mfc->cmd->plugin, LOG_DBG,
				   "mfc %"PRIu64", dest %u: "
				   "fundchannel_cancel task.",
				   mfc->id, dest->index);
			++cleanup->pending;
			mfc_cleanup_fc(mfc->cmd, cleanup, dest);
			continue;
		case MULTIFUNDCHANNEL_UPDATED:
			/* Definitely a v2 */
			plugin_log(mfc->cmd->plugin, LOG_DBG,
				   "mfc %"PRIu64", dest %u:"
				   " openchannel_abort task.",
				   mfc->id, dest->index);
			++cleanup->pending;
			mfc_cleanup_oc(mfc->cmd, cleanup, dest);
			continue;
		case MULTIFUNDCHANNEL_SECURED:
		case MULTIFUNDCHANNEL_SIGNED:
		case MULTIFUNDCHANNEL_SIGNED_NOT_SECURED:
			/* We don't actually *send* the
			 * transaction until here,
			 * but peer isnt going to forget. This
			 * open is borked until an input is
			 * spent or it times out */
			continue;
		case MULTIFUNDCHANNEL_START_NOT_YET:
		case MULTIFUNDCHANNEL_CONNECTED:
		case MULTIFUNDCHANNEL_DONE:
		case MULTIFUNDCHANNEL_FAILED:
			/* Nothing to do ! */
			continue;
		}
		/* We shouldn't make it this far */
		abort();
	}

	if (cleanup->pending == 0)
		return mfc_cleanup_complete(cleanup);
	else
		return command_still_pending(mfc->cmd);
}
#define mfc_cleanup(mfc, cb, arg) \
	mfc_cleanup_(mfc, typesafe_cb(struct command_result *, void *, \
				      (cb), (arg)), \
		     (arg))

/*---------------------------------------------------------------------------*/

/* These are the actual implementations of the cleanup entry functions.  */

struct mfc_fail_object {
	struct multifundchannel_command *mfc;
	struct command *cmd;
	enum jsonrpc_errcode code;
	const char *msg;
};

static struct command_result *
mfc_fail_complete(struct mfc_fail_object *obj)
{
	plugin_log(obj->mfc->cmd->plugin, LOG_DBG,
		   "mfc %"PRIu64": cleanup done, failing.", obj->mfc->id);
	return command_fail(obj->cmd, obj->code, "%s", obj->msg);
}

/* Use this instead of command_fail.  */
static struct command_result *
mfc_fail(struct multifundchannel_command *mfc, enum jsonrpc_errcode code,
	 const char *fmt, ...)
{
	struct mfc_fail_object *obj;
	const char *msg;
	va_list ap;

	va_start(ap, fmt);
	msg = tal_vfmt(mfc, fmt, ap);
	va_end(ap);

	obj = tal(mfc, struct mfc_fail_object);
	obj->mfc = mfc;
	obj->cmd = mfc->cmd;
	obj->code = code;
	obj->msg = msg;

	return mfc_cleanup(mfc, &mfc_fail_complete, obj);
}
struct mfc_err_raw_object {
	struct multifundchannel_command *mfc;
	const char *error;
};
static struct command_result *
mfc_err_raw_complete(struct mfc_err_raw_object *obj)
{
	plugin_log(obj->mfc->cmd->plugin, LOG_DBG,
		   "mfc %"PRIu64": cleanup done, failing raw.", obj->mfc->id);
	return command_err_raw(obj->mfc->cmd, obj->error);
}

/* Use this instead of command_err_raw.  */
static struct command_result *
mfc_err_raw(struct multifundchannel_command *mfc, const char *json_string)
{
	struct mfc_err_raw_object *obj;

	obj = tal(mfc, struct mfc_err_raw_object);
	obj->mfc = mfc;
	obj->error = tal_strdup(obj, json_string);

	return mfc_cleanup(mfc, &mfc_err_raw_complete, obj);
}
struct command_result *
mfc_forward_error(struct command *cmd,
		  const char *method,
		  const char *buf, const jsmntok_t *error,
		  struct multifundchannel_command *mfc)
{
	plugin_log(cmd->plugin, LOG_DBG,
		   "mfc %"PRIu64": forwarding error, about to cleanup.",
		   mfc->id);
	return mfc_err_raw(mfc, json_strdup(tmpctx, buf, error));
}

struct mfc_finished_object {
	struct multifundchannel_command *mfc;
	struct command *cmd;
	struct json_stream *response;
};
static struct command_result *
mfc_finished_complete(struct mfc_finished_object *obj)
{
	plugin_log(obj->mfc->cmd->plugin, LOG_DBG,
		   "mfc %"PRIu64": cleanup done, finishing command.",
		   obj->mfc->id);
	return command_finished(obj->cmd, obj->response);
}

struct command_result *
mfc_finished(struct multifundchannel_command *mfc,
	     struct json_stream *response)
{
	struct mfc_finished_object *obj;

	/* The response will be constructed by jsonrpc_stream_success,
	which allocates off the command, so it should be safe to
	just store it here.
	*/
	obj = tal(mfc, struct mfc_finished_object);
	obj->mfc = mfc;
	obj->cmd = mfc->cmd;
	obj->response = response;

	return mfc_cleanup(mfc, &mfc_finished_complete, obj);
}

/*---------------------------------------------------------------------------*/
/*~
We now have an unsigned funding transaction in
mfc->psbt and mfc->txid that puts the money into
2-of-2 channel outpoints.

However, we cannot sign and broadcast it yet!
We need to get backout transactions --- the initial
commitment transactions --- in case any of the
peers disappear later.
Those initial commitment transactions are the
unilateral close (force-close) transactions
for each channel.
With unilateral opportunity to close, we can then
safely broadcast the tx, so that in case the
peer disappears, we can recover our funds.

The `fundchannel_complete` command performs the
negotiation with the peer to sign the initial
commiteent transactions.
Only once the `lightningd` has the transactions
signed does the `fundchannel_complete` command
return with a success.
After that point we can `signpsbt`+`sendpsbt`
the transaction.
*/

/*~
And finally we are done.
*/
struct command_result *
multifundchannel_finished(struct multifundchannel_command *mfc)
{
	unsigned int i;
	struct json_stream *out;

	plugin_log(mfc->cmd->plugin, LOG_DBG,
		   "mfc %"PRIu64": done.", mfc->id);

	out = jsonrpc_stream_success(mfc->cmd);
	json_add_string(out, "tx", mfc->final_tx);
	json_add_string(out, "txid", mfc->final_txid);
	json_array_start(out, "channel_ids");
	for (i = 0; i < tal_count(mfc->destinations); ++i) {
		json_object_start(out, NULL);
		json_add_node_id(out, "id", &mfc->destinations[i].id);
		json_add_channel_id(out, "channel_id",
				    &mfc->destinations[i].channel_id);
		json_add_channel_type(out, "channel_type",
				      mfc->destinations[i].channel_type);
		json_add_num(out, "outnum", mfc->destinations[i].outnum);
		if (mfc->destinations[i].close_to_script)
			json_add_hex_talarr(out, "close_to",
				mfc->destinations[i].close_to_script);
		json_object_end(out);
	}
	json_array_end(out);

	json_array_start(out, "failed");
	for (i = 0; i < tal_count(mfc->removeds); ++i) {
		json_object_start(out, NULL);
		json_add_node_id(out, "id", &mfc->removeds[i].id);
		json_add_string(out, "method", mfc->removeds[i].method);
		json_object_start(out, "error"); /* Start error object */
		json_add_s32(out, "code", mfc->removeds[i].error_code);
		json_add_string(out, "message",
				mfc->removeds[i].error_message);
		if (mfc->removeds[i].error_data)
			json_add_jsonstr(out, "data",
					 mfc->removeds[i].error_data,
					 strlen(mfc->removeds[i].error_data));
		json_object_end(out); /* End error object */
		json_object_end(out);
	}
	json_array_end(out);

	return mfc_finished(mfc, out);
}

static struct command_result *
after_sendpsbt(struct command *cmd,
	       const char *method,
	       const char *buf,
	       const jsmntok_t *result,
	       struct multifundchannel_command *mfc)
{
	const jsmntok_t *tx_tok;
	const jsmntok_t *txid_tok;

	plugin_log(mfc->cmd->plugin, LOG_DBG,
		   "mfc %"PRIu64": sendpsbt done.", mfc->id);

	tx_tok = json_get_member(buf, result, "tx");
	if (!tx_tok)
		plugin_err(cmd->plugin,
			   "sendpsbt response has no 'tx': %.*s",
			   json_tok_full_len(result),
			   json_tok_full(buf, result));
	mfc->final_tx = json_strdup(mfc, buf, tx_tok);

	txid_tok = json_get_member(buf, result, "txid");
	if (!txid_tok)
		plugin_err(cmd->plugin,
			   "sendpsbt response has no 'txid': %.*s",
			   json_tok_full_len(result),
			   json_tok_full(buf, result));
	mfc->final_txid = json_strdup(mfc, buf, txid_tok);

	/* PSBT is no longer something we need to clean up.  */
	mfc->psbt = tal_free(mfc->psbt);

	return multifundchannel_finished(mfc);
}

static struct command_result *
after_signpsbt(struct command *cmd,
	       const char *method,
	       const char *buf,
	       const jsmntok_t *result,
	       struct multifundchannel_command *mfc)
{
	const jsmntok_t *field;
	struct wally_psbt *psbt;
	struct out_req *req;

	plugin_log(mfc->cmd->plugin, LOG_DBG,
		   "mfc %"PRIu64": signpsbt done.", mfc->id);

	field = json_get_member(buf, result, "signed_psbt");
	if (!field)
		plugin_err(mfc->cmd->plugin,
			   "signpsbt did not return 'signed_psbt'? %.*s",
			   json_tok_full_len(result),
			   json_tok_full(buf, result));
	psbt = psbt_from_b64(mfc,
			     buf + field->start,
			     field->end - field->start);
	if (!psbt)
		plugin_err(mfc->cmd->plugin,
			   "signpsbt gave unparseable 'signed_psbt'? %.*s",
			   json_tok_full_len(field),
			   json_tok_full(buf, field));

	if (!psbt_set_version(psbt, 2)) {
		/* It should be well-formed? */
		plugin_err(mfc->cmd->plugin,
			   "mfc: could not set PSBT version: %s",
		   		fmt_wally_psbt(tmpctx, mfc->psbt));
	}

	if (!psbt_finalize(psbt))
		plugin_err(mfc->cmd->plugin,
			   "mfc %"PRIu64": Signed PSBT won't finalize"
			   "%s", mfc->id,
			   fmt_wally_psbt(tmpctx, psbt));


	/* Replace the PSBT.  */
	tal_free(mfc->psbt);
	mfc->psbt = tal_steal(mfc, psbt);

	/*~ Now mark all destinations as being done.
	Why mark it now *before* doing `sendpsbt` rather than after?
	Because `sendpsbt` will do approximately this:

	1.  `sendpsbt` launches `bitcoin-cli`.
	2.  `bitcoin-cli` connects to a `bitcoind` over JSON-RPC
	    over HTTP.
	3.  `bitcoind` validates the transactions and puts it int
	    its local mempool.
	4.  `bitcoind` tells `bitcoin-cli` it all went well.
	5.  `bitcoin-cli` tells `sendpsbt` it all went well.

	If some interruption or problem occurs between steps 3
	and 4, then the transaction is already in some node
	mempool and will likely be broadcast, but `sendpsbt` has
	failed.

	And so we have to mark the channels as being "done"
	*before* we do `sendpsbt`.
	If not, if we error on `sendpsbt`, that would cause us to
	`fundchannel_cancel` all the peers, but that is risky,
	as, the funding transaction could still have been
	broadcast and the channels funded.

	That is, we treat `sendpsbt` failure as a possible
	false negative.
	*/
	for (size_t i = 0; i < tal_count(mfc->destinations); ++i) {
		struct multifundchannel_destination *dest;
		enum multifundchannel_state expected_state;

		dest = &mfc->destinations[i];

		/* Check that every dest is in the right state */
		expected_state = is_v2(dest) ?
			MULTIFUNDCHANNEL_SIGNED : MULTIFUNDCHANNEL_COMPLETED;
		assert(dest->state == expected_state);

		dest->state = MULTIFUNDCHANNEL_DONE;
	}

	/* If there's any v2's, we send the tx via `openchannel_signed` */
	if (dest_count(mfc, OPEN_CHANNEL) > 0) {
		return perform_openchannel_signed(mfc);
	}

	plugin_log(mfc->cmd->plugin, LOG_DBG,
		   "mfc %"PRIu64": sendpsbt.", mfc->id);

	req = jsonrpc_request_start(mfc->cmd,
				    "sendpsbt",
				    &after_sendpsbt,
				    &mfc_forward_error,
				    mfc);
	json_add_psbt(req->js, "psbt", mfc->psbt);
	/* We already reserved inputs by 2 weeks, we don't need
	 * another 72 blocks. */
	json_add_u32(req->js, "reserve", 0);
	return send_outreq(req);
}

struct command_result *
perform_signpsbt(struct multifundchannel_command *mfc)
{
	struct out_req *req;

	/* Now we sign our inputs. You do remember which inputs
	 * are yours, right? */
	plugin_log(mfc->cmd->plugin, LOG_DBG,
		   "mfc %"PRIu64": signpsbt.", mfc->id);

	req = jsonrpc_request_start(mfc->cmd,
				    "signpsbt",
				    &after_signpsbt,
				    &mfc_forward_error,
				    mfc);
	json_add_psbt(req->js, "psbt", mfc->psbt);

	/* Use input markers to identify which inputs
	 * are ours, only sign those */
	json_array_start(req->js, "signonly");
	for (size_t i = 0; i < mfc->psbt->num_inputs; i++) {
		if (psbt_input_is_ours(&mfc->psbt->inputs[i]))
			json_add_num(req->js, NULL, i);
	}
	json_array_end(req->js);
	return send_outreq(req);
}

/*~
Finally with everything set up correctly we `signpsbt`+`sendpsbt` the
funding transaction.
*/
static struct command_result *
after_fundchannel_complete(struct multifundchannel_command *mfc)
{
	unsigned int i;

	plugin_log(mfc->cmd->plugin, LOG_DBG,
		   "mfc %"PRIu64": parallel fundchannel_complete  done.",
		   mfc->id);

	/* Check if any fundchannel_complete failed.  */
	for (i = 0; i < tal_count(mfc->destinations); ++i) {
		struct multifundchannel_destination *dest;

		dest = &mfc->destinations[i];
		if (is_v2(dest))
			continue;

		assert(dest->state == MULTIFUNDCHANNEL_COMPLETED
		    || dest->state == MULTIFUNDCHANNEL_FAILED);

		if (dest->state != MULTIFUNDCHANNEL_FAILED)
			continue;

		/* One of them failed, oh no.  */
		return redo_multifundchannel(mfc, "fundchannel_complete",
					     dest->error_message);
	}

	if (dest_count(mfc, OPEN_CHANNEL) > 0)
		return check_sigs_ready(mfc);

	return perform_signpsbt(mfc);
}


static struct command_result *
fundchannel_complete_done(struct multifundchannel_destination *dest)
{
	struct multifundchannel_command *mfc = dest->mfc;

	--mfc->pending;
	if (mfc->pending == 0)
		return after_fundchannel_complete(mfc);
	else
		return command_still_pending(mfc->cmd);
}

static struct command_result *
fundchannel_complete_ok(struct command *cmd,
			const char *method,
			const char *buf,
			const jsmntok_t *result,
			struct multifundchannel_destination *dest)
{
	struct multifundchannel_command *mfc = dest->mfc;
	const jsmntok_t *channel_id_tok;

	plugin_log(mfc->cmd->plugin, LOG_DBG,
		   "mfc %"PRIu64", dest %u: fundchannel_complete %s done.",
		   mfc->id, dest->index,
		   fmt_node_id(tmpctx, &dest->id));

	channel_id_tok = json_get_member(buf, result, "channel_id");
	if (!channel_id_tok)
		plugin_err(cmd->plugin,
			   "fundchannel_complete no channel_id: %.*s",
			   json_tok_full_len(result),
			   json_tok_full(buf, result));
	json_to_channel_id(buf, channel_id_tok, &dest->channel_id);

	dest->state = MULTIFUNDCHANNEL_COMPLETED;
	return fundchannel_complete_done(dest);
}

static struct command_result *
fundchannel_complete_err(struct command *cmd,
			 const char *method,
			 const char *buf,
			 const jsmntok_t *error,
			 struct multifundchannel_destination *dest)
{
	struct multifundchannel_command *mfc = dest->mfc;

	plugin_log(mfc->cmd->plugin, LOG_DBG,
		   "mfc %"PRIu64", dest %u: "
		   "failed! fundchannel_complete %s: %.*s",
		   mfc->id, dest->index,
		   fmt_node_id(tmpctx, &dest->id),
		   json_tok_full_len(error), json_tok_full(buf, error));

	fail_destination_tok(dest, buf, error);
	return fundchannel_complete_done(dest);
}

static void
fundchannel_complete_dest(struct multifundchannel_destination *dest)
{
	struct multifundchannel_command *mfc = dest->mfc;
	struct command *cmd = mfc->cmd;
	struct out_req *req;

	plugin_log(mfc->cmd->plugin, LOG_DBG,
		   "mfc %"PRIu64", dest %u: fundchannel_complete %s.",
		   mfc->id, dest->index,
		   fmt_node_id(tmpctx, &dest->id));

	req = jsonrpc_request_start(cmd,
				    "fundchannel_complete",
				    &fundchannel_complete_ok,
				    &fundchannel_complete_err,
				    dest);
	json_add_node_id(req->js, "id", &dest->id);
	json_add_psbt(req->js, "psbt", mfc->psbt);

	send_outreq(req);
}

struct command_result *
perform_fundchannel_complete(struct multifundchannel_command *mfc)
{
	unsigned int i;

	plugin_log(mfc->cmd->plugin, LOG_DBG,
		   "mfc %"PRIu64": parallel fundchannel_complete.",
		   mfc->id);

	mfc->pending = dest_count(mfc, FUND_CHANNEL);

	for (i = 0; i < tal_count(mfc->destinations); ++i) {
		if (!is_v2(&mfc->destinations[i]))
			fundchannel_complete_dest(&mfc->destinations[i]);
	}

	assert(mfc->pending != 0);
	return command_still_pending(mfc->cmd);
}

/*~ The PSBT we are holding currently has no outputs
  (except an optional change output).
We now proceed to filling in those outputs now that
we know what the funding scriptpubkeys are.

First thing we do is to shuffle the outputs.
This is needed in order to decorrelate the transaction
outputs from the parameters passed into the command.
We should assume that the caller of the command might
inadvertently leak important privacy data in the order
of its arguments, so we shuffle the outputs.
*/
static struct command_result *
perform_funding_tx_finalize(struct multifundchannel_command *mfc)
{
	struct multifundchannel_destination **deck;
	char *content = tal_strdup(tmpctx, "");
	size_t v1_dest_count = dest_count(mfc, FUND_CHANNEL);
	size_t v2_dest_count = dest_count(mfc, OPEN_CHANNEL);
	size_t i, deck_i;
	u32 psbt_version = mfc->psbt->version;

	plugin_log(mfc->cmd->plugin, LOG_DBG,
		   "mfc %"PRIu64": Creating funding tx.",
		   mfc->id);

	/* We operate over PSBTv2 only */
	if (!psbt_set_version(mfc->psbt, 2)) {
		/* It should be well-formed? */
		plugin_err(mfc->cmd->plugin,
			   "mfc: could not set PSBT version: %s",
		   		fmt_wally_psbt(tmpctx, mfc->psbt));
	}

	/* Construct a deck of destinations.  */
	deck = tal_arr(tmpctx, struct multifundchannel_destination *,
		       v1_dest_count);

	deck_i = 0;
	for (i = 0; i < tal_count(mfc->destinations); i++) {
		if (is_v2(&mfc->destinations[i]))
			continue;

		assert(deck_i < tal_count(deck));
		deck[deck_i++] = &mfc->destinations[i];
	}

	/* Fisher-Yates shuffle.  */
	for (i = tal_count(deck); i > 1; --i) {
		size_t j = pseudorand(i);
		if (j == i - 1)
			continue;
		struct multifundchannel_destination *tmp;
		tmp = deck[j];
		deck[j] = deck[i - 1];
		deck[i - 1] = tmp;
	}

	/* Now that we have our outputs shuffled, add outputs to the PSBT.  */
	for (unsigned int outnum = 0; outnum < tal_count(deck); ++outnum) {
		struct multifundchannel_destination *dest;

		if (outnum != 0)
			tal_append_fmt(&content, ", ");

		/* Funding outpoint.  */
		dest = deck[outnum];
		(void) psbt_insert_output(mfc->psbt,
					  dest->funding_script,
					  dest->amount,
					  outnum);
		/* The actual output index will be based on the
		 * serial_id if this contains any v2 outputs */
		if (v2_dest_count == 0)
			dest->outnum = outnum;
		tal_append_fmt(&content, "%s: %s",
			       fmt_node_id(tmpctx, &dest->id),
			       fmt_amount_sat(tmpctx, dest->amount));
	}

	if (v2_dest_count > 0) {
		/* Add serial_ids to all the new outputs */
		psbt_add_serials(mfc->psbt, TX_INITIATOR);

		/* Now we stash the 'mfc' command, so when/if
		 * signature notifications start coming
		 * in, we'll catch them. */
		register_mfc(mfc);

		/* Take a side-quest to finish filling out
		 * the funding tx */
		return perform_openchannel_update(mfc);
	}

	/* We've only got v1 destinations, move onward */
	/* Elements requires a fee output.  */
	psbt_elements_normalize_fees(mfc->psbt);

	/* Generate the TXID.  */
	mfc->txid = tal(mfc, struct bitcoin_txid);
	psbt_txid(NULL, mfc->psbt, mfc->txid, NULL);

	plugin_log(mfc->cmd->plugin, LOG_DBG,
		   "mfc %"PRIu64": funding tx %s: %s",
		   mfc->id,
		   fmt_bitcoin_txid(tmpctx, mfc->txid),
		   content);

	if (!psbt_set_version(mfc->psbt, psbt_version)) {
		/* It should be well-formed? */
		plugin_err(mfc->cmd->plugin,
			   "mfc: could not set PSBT version: %s",
		   		fmt_wally_psbt(tmpctx, mfc->psbt));
	}

	/* Now we can feed the TXID and outnums to the peer.  */
	return perform_fundchannel_complete(mfc);
}

/*---------------------------------------------------------------------------*/

/*~
We perform all the `fundchannel_start` in parallel.

We need to parallelize `fundchannel_start` execution
since the command has to wait for a response from
the remote peer.
The remote peer is not under our control and might
respond after a long time.

By doing them in parallel, the time it takes to
perform all the `fundchannel_start` is only the
slowest time among all peers.
This is important since faster peers might impose a
timeout on channel opening and fail subsequent
steps if we take too long before running
`fundchannel_complete`.
*/

/* All fundchannel_start/openchannel_init commands have returned
 * with either success or failure.
*/
struct command_result *
after_channel_start(struct multifundchannel_command *mfc)
{
	unsigned int i;

	plugin_log(mfc->cmd->plugin, LOG_DBG,
		   "mfc %"PRIu64": parallel channel starts done.",
		   mfc->id);

	/* Check if any channel start failed.  */
	for (i = 0; i < tal_count(mfc->destinations); ++i) {
		struct multifundchannel_destination *dest;

		dest = &mfc->destinations[i];

		assert(dest->state == MULTIFUNDCHANNEL_STARTED
		    || dest->state == MULTIFUNDCHANNEL_FAILED);

		if (dest->state != MULTIFUNDCHANNEL_FAILED)
			continue;

		/* One of them failed, oh no.  */
		return redo_multifundchannel(mfc,
					     is_v2(dest) ?
					     "openchannel_init" :
					     "fundchannel_start",
					     dest->error_message);
	}

	/* Next step.  */
	return perform_funding_tx_finalize(mfc);
}

static struct command_result *
fundchannel_start_done(struct multifundchannel_destination *dest)
{
	struct multifundchannel_command *mfc = dest->mfc;

	--mfc->pending;
	if (mfc->pending == 0)
		return after_channel_start(mfc);
	else
		return command_still_pending(mfc->cmd);
}

struct channel_type *json_bits_to_channel_type(const tal_t *ctx,
					       const char *buffer, const jsmntok_t *tok)
{
	u8 *features = tal_arr(NULL, u8, 0);
	size_t i;
	const jsmntok_t *t;

	if (tok->type != JSMN_ARRAY)
		return tal_free(features);

	json_for_each_arr(i, t, tok) {
		u32 fbit;
		if (!json_to_u32(buffer, t, &fbit))
			return tal_free(features);
		set_feature_bit(&features, fbit);
	}
	return channel_type_from(ctx, take(features));
}

static struct command_result *
fundchannel_start_ok(struct command *cmd,
		     const char *method,
		     const char *buf,
		     const jsmntok_t *result,
		     struct multifundchannel_destination *dest)
{
	struct multifundchannel_command *mfc = dest->mfc;
	const char *err;

	plugin_log(mfc->cmd->plugin, LOG_DBG,
		   "mfc %"PRIu64", dest %u: fundchannel_start %s done.",
		   mfc->id, dest->index,
		   fmt_node_id(tmpctx, &dest->id));

	/* May not be set */
	dest->close_to_script = NULL;
	err = json_scan(mfc, buf, result,
			"{funding_address:%,"
			"scriptpubkey:%,"
			"channel_type:{bits:%},"
			"close_to?:%}",
			JSON_SCAN_TAL(mfc, json_strdup, &dest->funding_addr),
			JSON_SCAN_TAL(mfc, json_tok_bin_from_hex, &dest->funding_script),
			JSON_SCAN_TAL(mfc, json_bits_to_channel_type, &dest->channel_type),
			JSON_SCAN_TAL(mfc, json_tok_bin_from_hex, &dest->close_to_script));
	if (err)
		plugin_err(cmd->plugin,
			   "fundchannel_start parsing error: %s", err);

	dest->state = MULTIFUNDCHANNEL_STARTED;

	return fundchannel_start_done(dest);
}

static struct command_result *
fundchannel_start_err(struct command *cmd,
		      const char *method,
		      const char *buf,
		      const jsmntok_t *error,
		      struct multifundchannel_destination *dest)
{
	plugin_log(dest->mfc->cmd->plugin, LOG_DBG,
		   "mfc %"PRIu64", dest %u: "
		   "failed! fundchannel_start %s: %.*s.",
		   dest->mfc->id, dest->index,
		   fmt_node_id(tmpctx, &dest->id),
		   json_tok_full_len(error),
		   json_tok_full(buf, error));
	/*
	You might be wondering why we do not just use
	mfc_forward_error here.
	The reason is that other `fundchannel_start`
	commands are running in the meantime,
	and it is still ambiguous whether the opening
	of other destinations was started or not.

	After all parallel `fundchannel_start`s have
	completed, we can then fail.
	*/

	fail_destination_tok(dest, buf, error);
	return fundchannel_start_done(dest);
}

static void
fundchannel_start_dest(struct multifundchannel_destination *dest)
{
	struct multifundchannel_command *mfc = dest->mfc;
	struct command *cmd = mfc->cmd;
	struct out_req *req;

	plugin_log(mfc->cmd->plugin, LOG_DBG,
		   "mfc %"PRIu64", dest %u: fundchannel_start %s.",
		   mfc->id, dest->index,
		   fmt_node_id(tmpctx, &dest->id));

	req = jsonrpc_request_start(cmd,
				    "fundchannel_start",
				    &fundchannel_start_ok,
				    &fundchannel_start_err,
				    dest);

	json_add_node_id(req->js, "id", &dest->id);
	assert(!dest->all);
	json_add_string(req->js, "amount",
			fmt_amount_sat(tmpctx, dest->amount));

	if (mfc->cmtmt_feerate_str)
		json_add_string(req->js, "feerate", mfc->cmtmt_feerate_str);
	else if (mfc->feerate_str)
		json_add_string(req->js, "feerate", mfc->feerate_str);

	json_add_bool(req->js, "announce", dest->announce);
	json_add_amount_msat(req->js, "push_msat", dest->push_msat);

	if (dest->close_to_str)
		json_add_string(req->js, "close_to", dest->close_to_str);

	if (dest->mindepth)
		json_add_u32(req->js, "mindepth", *dest->mindepth);

	if (dest->channel_type) {
		json_add_channel_type_arr(req->js,
					  "channel_type", dest->channel_type);
	}

	if (dest->reserve)
		json_add_string(
		    req->js, "reserve",
		    fmt_amount_sat(tmpctx, *dest->reserve));

	send_outreq(req);
}

static struct command_result *
perform_channel_start(struct multifundchannel_command *mfc)
{
	unsigned int i;

	plugin_log(mfc->cmd->plugin, LOG_DBG,
		   "mfc %"PRIu64": fundchannel_start parallel "
		   "with PSBT %s",
		   mfc->id,
		   fmt_wally_psbt(tmpctx, mfc->psbt));

	mfc->pending = tal_count(mfc->destinations);

	/* Since v2 is now available, we branch depending
	 * on the capability of the peer and our feaures */
	for (i = 0; i < tal_count(mfc->destinations); ++i) {
		if (is_v2(&mfc->destinations[i]))
			openchannel_init_dest(&mfc->destinations[i]);
		else
			fundchannel_start_dest(&mfc->destinations[i]);
	}

	assert(mfc->pending != 0);
	return command_still_pending(mfc->cmd);
}


/*---------------------------------------------------------------------------*/

/*~ Create an initial funding PSBT.

This creation of the initial funding PSBT is solely to reserve inputs for
our use.
This lets us initiate later with fundchannel_start with confidence that we
can actually afford the channels we will create.
*/

static struct command_result *
mfc_psbt_acquired(struct multifundchannel_command *mfc)
{
	/* Add serials to all of our input/outputs, so they're stable
	 * for the life of the tx */
	psbt_add_serials(mfc->psbt, TX_INITIATOR);

	return perform_channel_start(mfc);
}

/* Limited recursion if we discover 'all' is too big for non-wumbo! */
static struct command_result *
perform_fundpsbt(struct multifundchannel_command *mfc, u32 feerate);

static struct command_result *
retry_fundpsbt_capped_all(struct command *cmd,
			  const char *method,
			  const char *buf,
			  const jsmntok_t *result,
			  struct multifundchannel_command *mfc)
{
	/* We've unreserved this, now free it and try again! */
	tal_free(mfc->psbt);
	return perform_fundpsbt(mfc, mfc->feerate_per_kw);
}

static struct command_result *
after_fundpsbt(struct command *cmd,
	       const char *method,
	       const char *buf,
	       const jsmntok_t *result,
	       struct multifundchannel_command *mfc)
{
	const jsmntok_t *field;
	struct multifundchannel_destination *all;

	plugin_log(mfc->cmd->plugin, LOG_DBG,
		   "mfc %"PRIu64": %s done.",
		   mfc->id, mfc->utxos_str ? "utxopsbt" : "fundpsbt");

	field = json_get_member(buf, result, "psbt");
	if (!field)
		goto fail;

	mfc->psbt = psbt_from_b64(mfc,
				  buf + field->start,
				  field->end - field->start);
	if (!mfc->psbt)
		goto fail;

	if (!psbt_set_version(mfc->psbt, 2))
		goto fail;

	/* Mark our inputs now, so we unreserve correctly on failure! */
	for (size_t i = 0; i < mfc->psbt->num_inputs; i++)
		psbt_input_mark_ours(mfc->psbt, &mfc->psbt->inputs[i]);

	field = json_get_member(buf, result, "feerate_per_kw");
	if (!field || !json_to_u32(buf, field, &mfc->feerate_per_kw))
		goto fail;

	field = json_get_member(buf, result, "estimated_final_weight");
	if (!field || !json_to_u32(buf, field, &mfc->estimated_final_weight))
		goto fail;

	all = all_dest(mfc);
	if (all) {
		struct amount_msat msat;

		/* excess_msat is amount to use for "all".  */
		field = json_get_member(buf, result, "excess_msat");
		if (!field || !parse_amount_msat(&msat,
						 buf + field->start,
						 field->end - field->start)
		    || !amount_msat_to_sat(&all->amount, msat))
			goto fail;

		/* Subtract amounts we're using for the other outputs */
		for (size_t i = 0; i < tal_count(mfc->destinations); i++) {
			if (mfc->destinations[i].all)
				continue;
			if (!amount_sat_sub(&all->amount,
					    all->amount,
					    mfc->destinations[i].amount)) {
				return mfc_fail(mfc, JSONRPC2_INVALID_PARAMS,
						"Insufficient funds for `all`"
						" output");
			}
		}

		/* Remove the 'all' flag.  */
		all->all = false;

		/* It's first grade, Spongebob! */
		if (!feature_negotiated(plugin_feature_set(mfc->cmd->plugin),
					all->their_features,
					OPT_LARGE_CHANNELS)
		    && amount_sat_greater(all->amount,
					  chainparams->max_funding)) {
			/* Oh, crap!  Set this amount and retry! */
			plugin_log(mfc->cmd->plugin, LOG_INFORM,
				   "'all' was too large for non-wumbo channel, trimming from %s to %s",
				   fmt_amount_sat(tmpctx, all->amount),
				   fmt_amount_sat(tmpctx, chainparams->max_funding));
			all->amount = chainparams->max_funding;
			return unreserve_call(mfc->cmd, mfc->psbt,
					      retry_fundpsbt_capped_all, mfc);
		}
	}
	return mfc_psbt_acquired(mfc);

fail:
	plugin_err(mfc->cmd->plugin,
		   "Unexpected result from fundpsbt/utxopsbt: %.*s",
		   json_tok_full_len(result),
		   json_tok_full(buf, result));

}

static bool any_dest_negotiated_anchors(const struct plugin *plugin,
					const struct multifundchannel_destination *dests)
{
	for (size_t i = 0; i < tal_count(dests); i++) {
		if (feature_negotiated(plugin_feature_set(plugin),
				       dests[i].their_features,
				       OPT_ANCHORS_ZERO_FEE_HTLC_TX))
			return true;
	}
	return false;
}

static struct command_result *
perform_fundpsbt(struct multifundchannel_command *mfc, u32 feerate)
{
	struct out_req *req;

	/* If the user specified utxos we should use utxopsbt instead
	 * of fundpsbt.  */
	if (mfc->utxos_str) {
		plugin_log(mfc->cmd->plugin, LOG_DBG,
			   "mfc %"PRIu64": utxopsbt.",
			   mfc->id);

		req = jsonrpc_request_start(mfc->cmd,
					    "utxopsbt",
					    &after_fundpsbt,
					    &mfc_forward_error,
					    mfc);
		json_add_jsonstr(req->js, "utxos",
				 mfc->utxos_str, strlen(mfc->utxos_str));
		json_add_bool(req->js, "reservedok", false);
	} else {
		plugin_log(mfc->cmd->plugin, LOG_DBG,
			   "mfc %"PRIu64": fundpsbt.",
			   mfc->id);

		req = jsonrpc_request_start(mfc->cmd,
					    "fundpsbt",
					    &after_fundpsbt,
					    &mfc_forward_error,
					    mfc);
		json_add_u32(req->js, "minconf", mfc->minconf);
		/* If there's any v2 opens, we can't use p2sh inputs */
		json_add_bool(req->js, "nonwrapped",
			      dest_count(mfc, OPEN_CHANNEL) > 0);
	}

	/* If we're about to open an anchor channel, we need emergency funds! */
	if (any_dest_negotiated_anchors(mfc->cmd->plugin,
					mfc->destinations)) {
		json_add_bool(req->js, "opening_anchor_channel", true);
	}

	/* The entire point is to reserve the inputs. */
	/*  BOLT #2:
	 * The sender:
	 *...
	 *     - SHOULD ensure the funding transaction confirms in the next 2016
	 *       blocks.
	 */
	json_add_u32(req->js, "reserve", 2016);
	/* How much do we need to reserve?  */
	if (all_dest(mfc) != NULL)
		json_add_string(req->js, "satoshi", "all");
	else {
		struct amount_sat sum = AMOUNT_SAT(0);
		for (size_t i = 0; i < tal_count(mfc->destinations); ++i) {
			struct amount_sat requested
				= mfc->destinations[i].request_amt;

			if (!amount_sat_add(&sum,
					    sum, mfc->destinations[i].amount))
				return mfc_fail(mfc, JSONRPC2_INVALID_PARAMS,
						"Overflow while summing "
						"destination values.");
			/* Also add in any fees for requested amt! */
			if (!amount_sat_is_zero(requested)) {
				struct amount_sat fee;

				/* Assume they send >= what we've
				 * requested (otherwise we error) */
				if (!lease_rates_calc_fee(mfc->destinations[i].rates,
							  requested, requested,
							  feerate,
							  &fee))
					return mfc_fail(mfc, JSONRPC2_INVALID_PARAMS,
							"Overflow calculating"
							" lease fee.");


				if (!amount_sat_add(&sum, sum, fee))
					return mfc_fail(mfc, JSONRPC2_INVALID_PARAMS,
							"Overflow while summing"
							" lease fee");
			}
		}
		json_add_string(req->js, "satoshi",
				fmt_amount_sat(tmpctx, sum));
	}
	json_add_string(req->js, "feerate", tal_fmt(tmpctx, "%uperkw", feerate));

	{
		size_t startweight;
		size_t num_outs = tal_count(mfc->destinations);
		/* Assume 1 input.
		 * As long as lightningd does not select more than 252
		 * inputs, that estimation should be correct.
		 */
		startweight = bitcoin_tx_core_weight(1, num_outs)
			    + ( bitcoin_tx_output_weight(
					BITCOIN_SCRIPTPUBKEY_P2WSH_LEN)
			      * num_outs
			      );
		json_add_string(req->js, "startweight",
				tal_fmt(tmpctx, "%zu", startweight));
	}

	/* Handle adding a change output if required. */
	json_add_bool(req->js, "excess_as_change", true);

	return send_outreq(req);
}

static struct command_result *
after_getfeerate(struct command *cmd,
		 const char *method,
		 const char *buf,
		 const jsmntok_t *result,
		 struct multifundchannel_command *mfc)
{
	const char *err;
	u32 feerate;

	plugin_log(mfc->cmd->plugin, LOG_DBG,
		   "mfc %"PRIu64": 'parsefeerate' done", mfc->id);

	err = json_scan(tmpctx, buf, result,
			"{perkw:%}",
			JSON_SCAN(json_to_number, &feerate));
	if (err)
		mfc_fail(mfc, JSONRPC2_INVALID_PARAMS,
			 "Unable to parse feerate %s: %.*s",
			 err, json_tok_full_len(result),
			 json_tok_full(buf, result));

	return perform_fundpsbt(mfc, feerate);
}

static struct command_result *
getfeerate(struct multifundchannel_command *mfc)
{
	struct out_req *req;
	/* With the introduction of channel leases (option_will_fund),
	 * we need to include enough in the PSBT to cover our expected
	 * fees for the channel open. This requires that we know
	 * the feerate ahead of time, so that we can figure the
	 * expected lease fees, and add that to the funding amount. */
	req = jsonrpc_request_start(mfc->cmd,
				    "parsefeerate",
				    &after_getfeerate,
				    &mfc_forward_error,
				    mfc);

	/* Internally, it defaults to 'opening', so we use that here */
	json_add_string(req->js, "feerate",
			mfc->feerate_str ? mfc->feerate_str: "opening");

	return send_outreq(req);
}

/*---------------------------------------------------------------------------*/
/*~
First, connect to all the peers.

This is a convenience both to us and to the user.

We delegate parsing for valid node IDs to the
`multiconnect`.
In addition, this means the user does not have to
connect to the specified nodes.

In particular, some implementations (including some
versions of C-Lightning) will disconnect in case
of funding channel failure.
And with a *multi* funding, it is more likely to
fail due to having to coordinate many more nodes.
*/

/* Check results of connect.  */
static struct command_result *
after_multiconnect(struct multifundchannel_command *mfc)
{
	unsigned int i;

	plugin_log(mfc->cmd->plugin, LOG_DBG,
		   "mfc %"PRIu64": multiconnect done.", mfc->id);

	/* Check if anyone failed.  */
	for (i = 0; i < tal_count(mfc->destinations); ++i) {
		struct multifundchannel_destination *dest;

		dest = &mfc->destinations[i];

		assert(dest->state == MULTIFUNDCHANNEL_CONNECTED
		    || dest->state == MULTIFUNDCHANNEL_FAILED);

		if (dest->state != MULTIFUNDCHANNEL_FAILED)
			continue;

		/* One of them failed, oh no. */
		return redo_multifundchannel(mfc, "connect",
					     dest->error_message);
	}

	return getfeerate(mfc);
}

static struct command_result *
connect_done(struct multifundchannel_destination *dest)
{
	struct multifundchannel_command *mfc = dest->mfc;

	--mfc->pending;
	if (mfc->pending == 0)
		return after_multiconnect(mfc);
	else
		return command_still_pending(mfc->cmd);
}


static struct command_result *
connect_ok(struct command *cmd,
	   const char *method,
	   const char *buf,
	   const jsmntok_t *result,
	   struct multifundchannel_destination *dest)
{
	struct multifundchannel_command *mfc = dest->mfc;
	const jsmntok_t *features_tok;

	plugin_log(mfc->cmd->plugin, LOG_DBG,
		   "mfc %"PRIu64", dest %u: connect done.",
		   mfc->id, dest->index);

	features_tok = json_get_member(buf, result, "features");
	if (!features_tok)
		plugin_err(cmd->plugin,
			   "'connect' did not return 'features'? %.*s",
			   json_tok_full_len(result),
			   json_tok_full(buf, result));
	dest->their_features = json_tok_bin_from_hex(mfc, buf, features_tok);
	if (!dest->their_features)
		plugin_err(cmd->plugin,
			   "'connect' has unparesable 'features'? %.*s",
			   json_tok_full_len(features_tok),
			   json_tok_full(buf, features_tok));

	dest->state = MULTIFUNDCHANNEL_CONNECTED;

	/* Set the open protocol to use now */
	if (feature_negotiated(plugin_feature_set(mfc->cmd->plugin),
			       dest->their_features,
			       OPT_DUAL_FUND))
		dest->protocol = OPEN_CHANNEL;
	else if (!amount_sat_is_zero(dest->request_amt) || !(!dest->rates))
		/* Return an error */
		fail_destination_msg(dest, FUNDING_V2_NOT_SUPPORTED,
				     "Tried to buy a liquidity ad"
				     " but we(?) don't have"
				     " experimental-dual-fund"
				     " enabled");

	return connect_done(dest);
}

static struct command_result *
connect_err(struct command *cmd,
	    const char *method,
	    const char *buf,
	    const jsmntok_t *error,
	    struct multifundchannel_destination *dest)
{
	struct multifundchannel_command *mfc = dest->mfc;

	plugin_log(mfc->cmd->plugin, LOG_DBG,
		   "mfc %"PRIu64", dest %u: failed! connect %s: %.*s.",
		   mfc->id, dest->index,
		   fmt_node_id(tmpctx, &dest->id),
		   json_tok_full_len(error),
		   json_tok_full(buf, error));

	fail_destination_tok(dest, buf, error);
	return connect_done(dest);
}

static void
connect_dest(struct multifundchannel_destination *dest)
{
	struct multifundchannel_command *mfc = dest->mfc;
	struct command *cmd = mfc->cmd;
	const char *id;
	struct out_req *req;

	id = fmt_node_id(tmpctx, &dest->id);
	plugin_log(mfc->cmd->plugin, LOG_DBG,
		   "mfc %"PRIu64", dest %u: connect %s.",
		   mfc->id, dest->index, id);

	req = jsonrpc_request_start(cmd,
				    "connect",
				    &connect_ok,
				    &connect_err,
				    dest);
	if (dest->addrhint)
		json_add_string(req->js, "id",
				tal_fmt(tmpctx, "%s@%s",
					id,
					dest->addrhint));
	else
		json_add_node_id(req->js, "id", &dest->id);
	send_outreq(req);
}

/*-----------------------------------------------------------------------------
Starting
-----------------------------------------------------------------------------*/

/* Initiate the multiconnect.  */
static struct command_result *
perform_multiconnect(struct multifundchannel_command *mfc)
{
	unsigned int i;

	plugin_log(mfc->cmd->plugin, LOG_DBG,
		   "mfc %"PRIu64": multiconnect.", mfc->id);

	mfc->pending = tal_count(mfc->destinations);

	for (i = 0; i < tal_count(mfc->destinations); ++i)
		connect_dest(&mfc->destinations[i]);

	assert(mfc->pending != 0);
	return command_still_pending(mfc->cmd);
}


/* Initiate the multifundchannel execution.  */
static struct command_result *
perform_multifundchannel(struct command *timer_cmd,
			 struct multifundchannel_command *mfc)
{
	perform_multiconnect(mfc);
	return timer_complete(timer_cmd);
}


/*-----------------------------------------------------------------------------
Re-try Entry Point
-----------------------------------------------------------------------------*/
/*~ We do cleanup, then we remove failed destinations and if we still have
 * the minimum number, re-run.
*/
struct multifundchannel_redo {
	struct multifundchannel_command *mfc;
	const char *failing_method;
};

/* Filter the failing destinations.  */
static struct command_result *
post_cleanup_redo_multifundchannel(struct multifundchannel_redo *redo)
{
	struct multifundchannel_command *mfc = redo->mfc;
	const char *failing_method = redo->failing_method;
	size_t i;
	struct multifundchannel_destination *old_destinations;
	struct multifundchannel_destination *new_destinations;

	plugin_log(mfc->cmd->plugin, LOG_DBG,
		   "mfc %"PRIu64": Filtering destinations.",
		   mfc->id);

	/* We got the args now.  */
	tal_free(redo);

	/* Clean up previous funding transaction if any.  */
	mfc->psbt = tal_free(mfc->psbt);
	mfc->txid = tal_free(mfc->txid);

	/* Filter out destinations.  */
	old_destinations = tal_steal(tmpctx, mfc->destinations);
	mfc->destinations = NULL;
	new_destinations = tal_arr(mfc, struct multifundchannel_destination,
				   0);

	for (i = 0; i < tal_count(old_destinations); ++i) {
		struct multifundchannel_destination *dest;

		dest = &old_destinations[i];

		/* We have to fail any v2 that has commitments already */
		if (is_v2(dest) && has_commitments_secured(dest)
		     && !dest_failed(dest)) {
			fail_destination_msg(dest, FUNDING_STATE_INVALID,
					     "Attempting retry,"
					     " yet this peer already has"
					     " exchanged commitments and is"
					     " using the v2 open protocol."
					     " Must spend input to reset.");
		}

		if (dest_failed(dest)) {
		    /* We can't re-try committed v2's */
			struct multifundchannel_removed removed;

			plugin_log(mfc->cmd->plugin, LOG_DBG,
				   "mfc %"PRIu64", dest %u: "
				   "failed.",
				   mfc->id, dest->index);

			removed.id = dest->id;
			removed.method = failing_method;
			removed.error_message = dest->error_message;
			removed.error_code = dest->error_code;
			removed.error_data = dest->error_data;
			/* Add to removeds.  */
			tal_arr_expand(&mfc->removeds, removed);
		} else {
			plugin_log(mfc->cmd->plugin, LOG_DBG,
				   "mfc %"PRIu64", dest %u: "
				   "succeeded.",
				   mfc->id, dest->index);

			/* Reset its state.  */
			dest->state = MULTIFUNDCHANNEL_START_NOT_YET;
			/* We do not mess with `dest->index` so we have
			a stable id between reattempts.
			*/
			/* Re-add to new destinations.  */
			tal_arr_expand(&new_destinations, *dest);
			/* FIXME: If this were an array of pointers,
			 * we could make dest itself the parent of
			 * ->addrhint and not need this wart! */
			tal_steal(new_destinations, dest->addrhint);
		}
	}
	mfc->destinations = new_destinations;

	if (tal_count(mfc->destinations) < mfc->minchannels) {
		/* Too many failed. */
		struct json_stream *out;

		assert(tal_count(mfc->removeds) != 0);

		plugin_log(mfc->cmd->plugin, LOG_DBG,
			   "mfc %"PRIu64": %zu destinations failed, failing.",
			   mfc->id, tal_count(mfc->removeds));

		/* Blame it on the last.  */
		i = tal_count(mfc->removeds) - 1;

		out = jsonrpc_stream_fail_data(mfc->cmd,
					       mfc->removeds[i].error_code,
					       mfc->removeds[i].error_message);
		json_add_node_id(out, "id", &mfc->removeds[i].id);
		json_add_string(out, "method", failing_method);
		if (mfc->removeds[i].error_data)
			json_add_jsonstr(out, "data",
					 mfc->removeds[i].error_data,
					 strlen(mfc->removeds[i].error_data));

		/* Close 'data'.  */
		json_object_end(out);

		return mfc_finished(mfc, out);
	}

	/* Okay, we still have destinations to try: wait a second in case it
	 * takes that long to disconnect from peer, then retry.  */
	command_timer(mfc->cmd, time_from_sec(1),
		      perform_multifundchannel, mfc);
	return command_still_pending(mfc->cmd);
}

struct command_result *
redo_multifundchannel(struct multifundchannel_command *mfc,
		      const char *failing_method,
		      const char *why)
{
	struct multifundchannel_redo *redo;

	assert(mfc->pending == 0);

	plugin_log(mfc->cmd->plugin, LOG_DBG,
		   "mfc %"PRIu64": trying redo despite '%s' failure (%s);"
		   " will cleanup for now.",
		   mfc->id, failing_method, why);

	redo = tal(mfc, struct multifundchannel_redo);
	redo->mfc = mfc;
	redo->failing_method = failing_method;

	return mfc_cleanup(mfc, &post_cleanup_redo_multifundchannel, redo);
}

/*-----------------------------------------------------------------------------
Input Validation
-----------------------------------------------------------------------------*/

/* Validates the destinations input argument.

Returns NULL if checking of destinations array worked,
or non-NULL if it failed (and this function has already
executed mfc_fail).
*/
static struct command_result *
param_destinations_array(struct command *cmd, const char *name,
			 const char *buffer, const jsmntok_t *tok,
			 struct multifundchannel_destination **dests)
{
	size_t i;
	const jsmntok_t *json_dest;
	bool has_all = false;

	if (tok->type != JSMN_ARRAY)
		return command_fail_badparam(cmd, name, buffer, tok,
					     "must be an array");
	if (tok->size < 1)
		return command_fail_badparam(cmd, name, buffer, tok,
					     "must have at least one entry");

	*dests = tal_arr(cmd, struct multifundchannel_destination, tok->size);
	for (i = 0; i < tal_count(*dests); ++i)
		(*dests)[i].state = MULTIFUNDCHANNEL_START_NOT_YET;

	json_for_each_arr(i, json_dest, tok) {
		struct multifundchannel_destination *dest;
		const char *id;
		char *addrhint;
		struct amount_sat *amount, *request_amt;
		bool *announce;
		struct amount_msat *push_msat;
		struct lease_rates *rates;

		dest = &(*dests)[i];

		if (!param(cmd, buffer, json_dest,
			   p_req("id", param_string, &id),
			   p_req("amount", param_sat_or_all, &amount),
			   p_opt_def("announce", param_bool, &announce, true),
			   p_opt_def("push_msat", param_msat, &push_msat,
				     AMOUNT_MSAT(0)),
			   /* FIXME: do address validation here?
			    * Note that it will fail eventually (when
			    * passed in to fundchannel_start) if invalid*/
			   p_opt("close_to", param_string,
				 &dest->close_to_str),
			   p_opt_def("request_amt", param_sat, &request_amt,
				     AMOUNT_SAT(0)),
			   p_opt("compact_lease", param_lease_hex, &rates),
			   p_opt("mindepth", param_u32, &dest->mindepth),
			   p_opt("reserve", param_sat, &dest->reserve),
			   p_opt("channel_type", param_channel_type, &dest->channel_type),
			   NULL))
			return command_param_failed();

		addrhint = strchr(id, '@');
		if (addrhint) {
			/* Split at @.  */
			size_t idlen = (size_t) (addrhint - id);
			addrhint = tal_strdup(*dests, addrhint + 1);
			id = tal_strndup(*dests, take(id), idlen);
		}

		if (!node_id_from_hexstr(id, strlen(id), &dest->id))
			return command_fail_badparam(cmd, name, buffer,
						     json_dest,
						     "invalid node id");

		if (!amount_sat_eq(*amount, AMOUNT_SAT(-1ULL)) &&
		    amount_sat_less(*amount, chainparams->dust_limit))
			return command_fail_badparam(cmd, name, buffer,
						     json_dest,
						     "output would be dust");

		if (!amount_sat_is_zero(*request_amt) && !rates)
			return command_fail_badparam(cmd, name, buffer,
					             json_dest,
						     "Must pass in 'compact_"
						     "lease' if requesting"
						     " funds from peer");
		dest->index = i;
		dest->addrhint = addrhint;
		dest->their_features = NULL;
		dest->funding_script = NULL;
		dest->funding_addr = NULL;
		dest->all = amount_sat_eq(*amount, AMOUNT_SAT(-1ULL));
		dest->amount = dest->all ? AMOUNT_SAT(0) : *amount;
		dest->announce = *announce;
		dest->push_msat = *push_msat;
		dest->psbt = NULL;
		dest->updated_psbt = NULL;
		dest->protocol = FUND_CHANNEL;
		dest->request_amt = *request_amt;
		dest->rates = tal_steal(*dests, rates);

		/* Stop leak detection from complaining. */
		tal_free(id);
		tal_free(amount);
		tal_free(push_msat);
		tal_free(request_amt);
		tal_free(announce);

		/* Only one destination can have "all" indicator.  */
		if (dest->all) {
			if (has_all)
				return command_fail_badparam(cmd, name, buffer,
							     json_dest,
							     "only one destination "
							     "can indicate \"all\" "
							     "for 'amount'.");
			else
				has_all = true;
		}

		/* Make sure every id is unique.  */
		for (size_t j = 0; j < i; j++) {
			if (node_id_eq(&dest->id, &(*dests)[j].id))
				return command_fail_badparam(cmd, name, buffer,
							     json_dest,
							     "Duplicate destination");
		}
	}

	return NULL;
}

static struct command_result *
param_positive_number(struct command *cmd,
		      const char *name,
		      const char *buffer,
		      const jsmntok_t *tok,
		      unsigned int **num)
{
	struct command_result *res = param_number(cmd, name, buffer, tok, num);
	if (res)
		return res;
	if (**num == 0)
		return command_fail_badparam(cmd, name, buffer, tok,
					     "should be a positive integer");
	return NULL;
}

static struct command_result *param_utxos_str(struct command *cmd, const char *name,
					      const char * buffer, const jsmntok_t *tok,
					      const char **str)
{
	if (tok->type != JSMN_ARRAY)
		return command_fail_badparam(cmd, name, buffer, tok,
					     "should be an array");
	*str = tal_strndup(cmd, buffer + tok->start,
			   tok->end - tok->start);
	return NULL;
}

/*-----------------------------------------------------------------------------
Command Entry Point
-----------------------------------------------------------------------------*/
static struct command_result *
json_multifundchannel(struct command *cmd,
		      const char *buf,
		      const jsmntok_t *params)
{
	struct multifundchannel_destination *dests;
	u32 *minconf;
	u32 *minchannels;

	struct multifundchannel_command *mfc;

	mfc = tal(cmd, struct multifundchannel_command);
	if (!param(cmd, buf, params,
		   p_req("destinations", param_destinations_array, &dests),
		   p_opt("feerate", param_string, &mfc->feerate_str),
		   p_opt_def("minconf", param_number, &minconf, 1),
		   p_opt("utxos", param_utxos_str, &mfc->utxos_str),
		   p_opt("minchannels", param_positive_number, &minchannels),
		   p_opt("commitment_feerate", param_string, &mfc->cmtmt_feerate_str),
		   NULL))
		return command_param_failed();

	/* Should exist; it would only nonexist if it were a notification.  */
	assert(cmd->id);

	mfc->id = ++mfc_id;
	mfc->cmd = cmd;

	/* Steal destinations array, and set up mfc pointers */
	mfc->destinations = tal_steal(mfc, dests);
	for (size_t i = 0; i < tal_count(mfc->destinations); i++)
		mfc->destinations[i].mfc = mfc;

	mfc->minconf = *minconf;
	/* Default is that all must succeed. */
	mfc->minchannels = minchannels ? *minchannels : tal_count(mfc->destinations);
	mfc->removeds = tal_arr(mfc, struct multifundchannel_removed, 0);
	mfc->psbt = NULL;
	mfc->txid = NULL;
	mfc->final_tx = NULL;
	mfc->final_txid = NULL;

	mfc->sigs_collected = false;

	perform_multiconnect(mfc);
	return command_still_pending(mfc->cmd);
}

const struct plugin_command multifundchannel_commands[] = {
	{
		"multifundchannel",
		json_multifundchannel
	}
};
const size_t num_multifundchannel_commands =
	ARRAY_SIZE(multifundchannel_commands);