forked from ElementsProject/lightning
-
Notifications
You must be signed in to change notification settings - Fork 0
/
walletrpc.c
942 lines (809 loc) · 27.4 KB
/
walletrpc.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
#include "config.h"
#include <bitcoin/base58.h>
#include <bitcoin/script.h>
#include <ccan/cast/cast.h>
#include <common/addr.h>
#include <common/bech32.h>
#include <common/configdir.h>
#include <common/json_command.h>
#include <common/json_helpers.h>
#include <common/json_tok.h>
#include <common/key_derive.h>
#include <common/param.h>
#include <common/psbt_keypath.h>
#include <common/psbt_open.h>
#include <common/type_to_string.h>
#include <db/exec.h>
#include <errno.h>
#include <hsmd/hsmd_wiregen.h>
#include <lightningd/chaintopology.h>
#include <lightningd/channel.h>
#include <lightningd/coin_mvts.h>
#include <lightningd/jsonrpc.h>
#include <lightningd/lightningd.h>
#include <lightningd/peer_control.h>
#include <wallet/txfilter.h>
#include <wallet/walletrpc.h>
#include <wally_psbt.h>
#include <wire/wire_sync.h>
/* May return NULL if encoding error occurs. */
static char *
encode_pubkey_to_addr(const tal_t *ctx,
const struct pubkey *pubkey,
bool is_p2sh_p2wpkh,
/* Output: redeemscript to use to redeem outputs
* paying to the address.
* May be NULL if redeemscript is do not care. */
u8 **out_redeemscript)
{
char *out;
const char *hrp;
struct sha256 h;
struct ripemd160 h160;
u8 *redeemscript;
bool ok;
if (is_p2sh_p2wpkh) {
redeemscript = bitcoin_redeem_p2sh_p2wpkh(ctx, pubkey);
sha256(&h, redeemscript, tal_count(redeemscript));
ripemd160(&h160, h.u.u8, sizeof(h));
out = p2sh_to_base58(ctx,
chainparams,
&h160);
} else {
hrp = chainparams->onchain_hrp;
/* out buffer is 73 + strlen(human readable part),
* see common/bech32.h*/
out = tal_arr(ctx, char, 73 + strlen(hrp));
pubkey_to_hash160(pubkey, &h160);
/* I am uncertain why this is so for direct SegWit
* outputs, but this is how listaddrs worked prior to
* this code being refactored. */
redeemscript = tal_dup_arr(ctx, u8,
(u8 *) &h160, sizeof(h160),
0);
ok = segwit_addr_encode(out, hrp, 0, h160.u.u8, sizeof(h160));
if (!ok)
out = tal_free(out);
}
if (out_redeemscript)
*out_redeemscript = redeemscript;
else
tal_free(redeemscript);
return out;
}
enum addrtype {
ADDR_P2SH_SEGWIT = 1,
ADDR_BECH32 = 2,
ADDR_ALL = (ADDR_P2SH_SEGWIT + ADDR_BECH32)
};
/* Extract bool indicating "p2sh-segwit" or "bech32" */
static struct command_result *param_newaddr(struct command *cmd,
const char *name,
const char *buffer,
const jsmntok_t *tok,
enum addrtype **addrtype)
{
*addrtype = tal(cmd, enum addrtype);
if (json_tok_streq(buffer, tok, "p2sh-segwit"))
**addrtype = ADDR_P2SH_SEGWIT;
else if (json_tok_streq(buffer, tok, "bech32"))
**addrtype = ADDR_BECH32;
else if (json_tok_streq(buffer, tok, "all"))
**addrtype = ADDR_ALL;
else
return command_fail(cmd, JSONRPC2_INVALID_PARAMS,
"'%s' should be 'bech32', 'p2sh-segwit' or 'all', not '%.*s'",
name, tok->end - tok->start, buffer + tok->start);
return NULL;
}
static struct command_result *json_newaddr(struct command *cmd,
const char *buffer,
const jsmntok_t *obj UNNEEDED,
const jsmntok_t *params)
{
struct json_stream *response;
struct pubkey pubkey;
enum addrtype *addrtype;
s64 keyidx;
char *p2sh, *bech32;
u8 *b32script;
if (!param(cmd, buffer, params,
p_opt_def("addresstype", param_newaddr, &addrtype, ADDR_BECH32),
NULL))
return command_param_failed();
keyidx = wallet_get_newindex(cmd->ld);
if (keyidx < 0) {
return command_fail(cmd, LIGHTNINGD, "Keys exhausted ");
}
if (!bip32_pubkey(cmd->ld->wallet->bip32_base, &pubkey, keyidx))
return command_fail(cmd, LIGHTNINGD, "Keys generation failure");
b32script = scriptpubkey_p2wpkh(tmpctx, &pubkey);
if (*addrtype & ADDR_BECH32)
txfilter_add_scriptpubkey(cmd->ld->owned_txfilter, b32script);
if (*addrtype & ADDR_P2SH_SEGWIT)
txfilter_add_scriptpubkey(cmd->ld->owned_txfilter,
scriptpubkey_p2sh(tmpctx, b32script));
p2sh = encode_pubkey_to_addr(cmd, &pubkey, true, NULL);
bech32 = encode_pubkey_to_addr(cmd, &pubkey, false, NULL);
if (!p2sh || !bech32) {
return command_fail(cmd, LIGHTNINGD,
"p2wpkh address encoding failure.");
}
response = json_stream_success(cmd);
if (*addrtype & ADDR_BECH32)
json_add_string(response, "bech32", bech32);
if (*addrtype & ADDR_P2SH_SEGWIT)
json_add_string(response, "p2sh-segwit", p2sh);
return command_success(cmd, response);
}
static const struct json_command newaddr_command = {
"newaddr",
"bitcoin",
json_newaddr,
"Get a new {bech32, p2sh-segwit} (or all) address to fund a channel (default is bech32)", false,
"Generates a new address (or both) that belongs to the internal wallet. Funds sent to these addresses will be managed by lightningd. Use `withdraw` to withdraw funds to an external wallet."
};
AUTODATA(json_command, &newaddr_command);
static struct command_result *json_listaddrs(struct command *cmd,
const char *buffer,
const jsmntok_t *obj UNNEEDED,
const jsmntok_t *params)
{
struct json_stream *response;
struct pubkey pubkey;
u64 *bip32_max_index;
if (!param(cmd, buffer, params,
p_opt("bip32_max_index", param_u64, &bip32_max_index),
NULL))
return command_param_failed();
if (!bip32_max_index) {
bip32_max_index = tal(cmd, u64);
*bip32_max_index = db_get_intvar(cmd->ld->wallet->db,
"bip32_max_index", 0);
}
response = json_stream_success(cmd);
json_array_start(response, "addresses");
for (s64 keyidx = 0; keyidx <= *bip32_max_index; keyidx++) {
if (keyidx == BIP32_INITIAL_HARDENED_CHILD){
break;
}
if (!bip32_pubkey(cmd->ld->wallet->bip32_base, &pubkey, keyidx))
abort();
// p2sh
u8 *redeemscript_p2sh;
char *out_p2sh = encode_pubkey_to_addr(cmd,
&pubkey,
true,
&redeemscript_p2sh);
// bech32 : p2wpkh
u8 *redeemscript_p2wpkh;
char *out_p2wpkh = encode_pubkey_to_addr(cmd,
&pubkey,
false,
&redeemscript_p2wpkh);
if (!out_p2wpkh) {
abort();
}
// outputs
json_object_start(response, NULL);
json_add_u64(response, "keyidx", keyidx);
json_add_pubkey(response, "pubkey", &pubkey);
json_add_string(response, "p2sh", out_p2sh);
json_add_hex_talarr(response, "p2sh_redeemscript",
redeemscript_p2sh);
json_add_string(response, "bech32", out_p2wpkh);
json_add_hex_talarr(response, "bech32_redeemscript",
redeemscript_p2wpkh);
json_object_end(response);
}
json_array_end(response);
return command_success(cmd, response);
}
static const struct json_command listaddrs_command = {
"dev-listaddrs",
"developer",
json_listaddrs,
"Show addresses list up to derivation {index} (default is the last bip32 index)",
false,
"Show addresses of your internal wallet. Use `newaddr` to generate a new address."
};
AUTODATA(json_command, &listaddrs_command);
static void json_add_utxo(struct json_stream *response,
const char *fieldname,
struct wallet *wallet,
const struct utxo *utxo)
{
const char *out;
bool reserved;
json_object_start(response, fieldname);
json_add_txid(response, "txid", &utxo->outpoint.txid);
json_add_num(response, "output", utxo->outpoint.n);
json_add_amount_sat_compat(response, utxo->amount,
"value", "amount_msat");
if (utxo->is_p2sh) {
struct pubkey key;
bip32_pubkey(wallet->bip32_base, &key, utxo->keyindex);
json_add_hex_talarr(response, "redeemscript",
bitcoin_redeem_p2sh_p2wpkh(tmpctx, &key));
}
json_add_hex_talarr(response, "scriptpubkey", utxo->scriptPubkey);
out = encode_scriptpubkey_to_addr(tmpctx, chainparams,
utxo->scriptPubkey);
if (!out)
log_broken(wallet->log,
"Could not encode utxo %s%s!",
type_to_string(tmpctx,
struct bitcoin_outpoint,
&utxo->outpoint),
utxo->close_info ? " (has close_info)" : "");
else
json_add_string(response, "address", out);
if (utxo->spendheight)
json_add_string(response, "status", "spent");
else if (utxo->blockheight) {
json_add_string(response, "status", "confirmed");
json_add_num(response, "blockheight", *utxo->blockheight);
} else
json_add_string(response, "status", "unconfirmed");
reserved = utxo_is_reserved(utxo,
get_block_height(wallet->ld->topology));
json_add_bool(response, "reserved", reserved);
if (reserved)
json_add_num(response, "reserved_to_block",
utxo->reserved_til);
if (utxo->close_info && utxo->close_info->csv > 1) {
json_add_num(response, "csv_lock", utxo->close_info->csv);
if (utxo->blockheight)
json_add_u32(response, "spendable_at",
*utxo->blockheight + utxo->close_info->csv);
}
json_object_end(response);
}
static void json_add_utxos(struct json_stream *response,
struct wallet *wallet,
struct utxo **utxos)
{
for (size_t i = 0; i < tal_count(utxos); i++)
json_add_utxo(response, NULL, wallet, utxos[i]);
}
static struct command_result *json_listfunds(struct command *cmd,
const char *buffer,
const jsmntok_t *obj UNNEEDED,
const jsmntok_t *params)
{
struct json_stream *response;
struct peer *p;
struct utxo **utxos, **reserved_utxos, **spent_utxos;
bool *spent;
if (!param(cmd, buffer, params,
p_opt_def("spent", param_bool, &spent, false),
NULL))
return command_param_failed();
response = json_stream_success(cmd);
utxos = wallet_get_utxos(cmd, cmd->ld->wallet, OUTPUT_STATE_AVAILABLE);
reserved_utxos = wallet_get_utxos(cmd, cmd->ld->wallet, OUTPUT_STATE_RESERVED);
json_array_start(response, "outputs");
json_add_utxos(response, cmd->ld->wallet, utxos);
json_add_utxos(response, cmd->ld->wallet, reserved_utxos);
if (*spent) {
spent_utxos = wallet_get_utxos(cmd, cmd->ld->wallet, OUTPUT_STATE_SPENT);
json_add_utxos(response, cmd->ld->wallet, spent_utxos);
}
json_array_end(response);
/* Add funds that are allocated to channels */
json_array_start(response, "channels");
list_for_each(&cmd->ld->peers, p, list) {
struct channel *c;
list_for_each(&p->channels, c, list) {
/* We don't print out uncommitted channels */
if (channel_unsaved(c))
continue;
json_object_start(response, NULL);
json_add_node_id(response, "peer_id", &p->id);
/* Mirrors logic in listpeers */
json_add_bool(response, "connected",
channel_active(c) && c->connected);
json_add_string(response, "state",
channel_state_name(c));
if (c->scid)
json_add_short_channel_id(response,
"short_channel_id",
c->scid);
json_add_amount_sat_compat(response,
amount_msat_to_sat_round_down(c->our_msat),
"channel_sat",
"our_amount_msat");
json_add_amount_sat_compat(response, c->funding_sats,
"channel_total_sat",
"amount_msat");
json_add_txid(response, "funding_txid",
&c->funding.txid);
json_add_num(response, "funding_output",
c->funding.n);
json_object_end(response);
}
}
json_array_end(response);
return command_success(cmd, response);
}
static const struct json_command listfunds_command = {
"listfunds",
"utility",
json_listfunds,
"Show available funds from the internal wallet",
false,
"Returns a list of funds (outputs) that can be used "
"by the internal wallet to open new channels "
"or can be withdrawn, using the `withdraw` command, to another wallet. "
"Includes spent outputs if {spent} is set to true."
};
AUTODATA(json_command, &listfunds_command);
struct txo_rescan {
struct command *cmd;
struct utxo **utxos;
struct json_stream *response;
};
static void process_utxo_result(struct bitcoind *bitcoind,
const struct bitcoin_tx_output *txout,
void *arg)
{
struct txo_rescan *rescan = arg;
struct json_stream *response = rescan->response;
struct utxo *u = rescan->utxos[0];
enum output_status newstate =
txout == NULL ? OUTPUT_STATE_SPENT : OUTPUT_STATE_AVAILABLE;
json_object_start(rescan->response, NULL);
json_add_txid(response, "txid", &u->outpoint.txid);
json_add_num(response, "output", u->outpoint.n);
json_add_num(response, "oldstate", u->status);
json_add_num(response, "newstate", newstate);
json_object_end(rescan->response);
wallet_update_output_status(bitcoind->ld->wallet, &u->outpoint,
u->status, newstate);
/* Remove the utxo we just resolved */
rescan->utxos[0] = rescan->utxos[tal_count(rescan->utxos) - 1];
tal_resize(&rescan->utxos, tal_count(rescan->utxos) - 1);
if (tal_count(rescan->utxos) == 0) {
/* Complete the response */
json_array_end(rescan->response);
was_pending(command_success(rescan->cmd, rescan->response));
} else {
bitcoind_getutxout(bitcoind->ld->topology->bitcoind,
&rescan->utxos[0]->outpoint,
process_utxo_result, rescan);
}
}
static struct command_result *json_dev_rescan_outputs(struct command *cmd,
const char *buffer,
const jsmntok_t *obj UNNEEDED,
const jsmntok_t *params)
{
struct txo_rescan *rescan = tal(cmd, struct txo_rescan);
if (!param(cmd, buffer, params, NULL))
return command_param_failed();
rescan->response = json_stream_success(cmd);
rescan->cmd = cmd;
/* Open the outputs structure so we can incrementally add results */
json_array_start(rescan->response, "outputs");
rescan->utxos = wallet_get_utxos(rescan, cmd->ld->wallet, OUTPUT_STATE_ANY);
if (tal_count(rescan->utxos) == 0) {
json_array_end(rescan->response);
return command_success(cmd, rescan->response);
}
bitcoind_getutxout(cmd->ld->topology->bitcoind,
&rescan->utxos[0]->outpoint,
process_utxo_result,
rescan);
return command_still_pending(cmd);
}
static const struct json_command dev_rescan_output_command = {
"dev-rescan-outputs",
"developer",
json_dev_rescan_outputs,
"Synchronize the state of our funds with bitcoind",
false,
"For each output stored in the internal wallet ask `bitcoind` whether we are in sync with its state (spent vs. unspent)"
};
AUTODATA(json_command, &dev_rescan_output_command);
struct {
enum wallet_tx_type t;
const char *name;
} wallet_tx_type_display_names[] = {
{TX_THEIRS, "theirs"},
{TX_WALLET_DEPOSIT, "deposit"},
{TX_WALLET_WITHDRAWAL, "withdraw"},
{TX_CHANNEL_FUNDING, "channel_funding"},
{TX_CHANNEL_CLOSE, "channel_mutual_close"},
{TX_CHANNEL_UNILATERAL, "channel_unilateral_close"},
{TX_CHANNEL_SWEEP, "channel_sweep"},
{TX_CHANNEL_HTLC_SUCCESS, "channel_htlc_success"},
{TX_CHANNEL_HTLC_TIMEOUT, "channel_htlc_timeout"},
{TX_CHANNEL_PENALTY, "channel_penalty"},
{TX_CHANNEL_CHEAT, "channel_unilateral_cheat"},
{0, NULL}
};
#if EXPERIMENTAL_FEATURES
static const char *txtype_to_string(enum wallet_tx_type t)
{
for (size_t i = 0; wallet_tx_type_display_names[i].name != NULL; i++)
if (t == wallet_tx_type_display_names[i].t)
return wallet_tx_type_display_names[i].name;
return NULL;
}
static void json_add_txtypes(struct json_stream *result, const char *fieldname, enum wallet_tx_type value)
{
json_array_start(result, fieldname);
for (size_t i = 0; wallet_tx_type_display_names[i].name != NULL; i++) {
if (value & wallet_tx_type_display_names[i].t)
json_add_string(result, NULL, wallet_tx_type_display_names[i].name);
}
json_array_end(result);
}
#endif
static void json_transaction_details(struct json_stream *response,
const struct wallet_transaction *tx)
{
struct wally_tx *wtx = tx->tx->wtx;
json_object_start(response, NULL);
json_add_txid(response, "hash", &tx->id);
json_add_hex_talarr(response, "rawtx", tx->rawtx);
json_add_num(response, "blockheight", tx->blockheight);
json_add_num(response, "txindex", tx->txindex);
#if EXPERIMENTAL_FEATURES
if (tx->annotation.type != 0)
json_add_txtypes(response, "type", tx->annotation.type);
if (tx->annotation.channel.u64 != 0)
json_add_short_channel_id(response, "channel", &tx->annotation.channel);
#endif
json_add_u32(response, "locktime", wtx->locktime);
json_add_u32(response, "version", wtx->version);
json_array_start(response, "inputs");
for (size_t i = 0; i < wtx->num_inputs; i++) {
struct bitcoin_txid prevtxid;
struct wally_tx_input *in = &wtx->inputs[i];
bitcoin_tx_input_get_txid(tx->tx, i, &prevtxid);
json_object_start(response, NULL);
json_add_txid(response, "txid", &prevtxid);
json_add_u32(response, "index", in->index);
json_add_u32(response, "sequence", in->sequence);
#if EXPERIMENTAL_FEATURES
struct tx_annotation *ann = &tx->input_annotations[i];
const char *txtype = txtype_to_string(ann->type);
if (txtype != NULL)
json_add_string(response, "type", txtype);
if (ann->channel.u64 != 0)
json_add_short_channel_id(response, "channel", &ann->channel);
#endif
json_object_end(response);
}
json_array_end(response);
json_array_start(response, "outputs");
for (size_t i = 0; i < wtx->num_outputs; i++) {
struct wally_tx_output *out = &wtx->outputs[i];
struct amount_asset amt = bitcoin_tx_output_get_amount(tx->tx, i);
struct amount_sat sat;
/* TODO We should eventually handle non-bitcoin assets as well. */
if (amount_asset_is_main(&amt))
sat = amount_asset_to_sat(&amt);
else
sat = AMOUNT_SAT(0);
json_object_start(response, NULL);
json_add_u32(response, "index", i);
if (deprecated_apis)
json_add_amount_sat_only(response, "satoshis", sat);
json_add_amount_sat_only(response, "msat", sat);
#if EXPERIMENTAL_FEATURES
struct tx_annotation *ann = &tx->output_annotations[i];
const char *txtype = txtype_to_string(ann->type);
if (txtype != NULL)
json_add_string(response, "type", txtype);
if (ann->channel.u64 != 0)
json_add_short_channel_id(response, "channel", &ann->channel);
#endif
json_add_hex(response, "scriptPubKey", out->script, out->script_len);
json_object_end(response);
}
json_array_end(response);
json_object_end(response);
}
static struct command_result *json_listtransactions(struct command *cmd,
const char *buffer,
const jsmntok_t *obj UNNEEDED,
const jsmntok_t *params)
{
struct json_stream *response;
struct wallet_transaction *txs;
if (!param(cmd, buffer, params, NULL))
return command_param_failed();
txs = wallet_transactions_get(cmd->ld->wallet, cmd);
response = json_stream_success(cmd);
json_array_start(response, "transactions");
for (size_t i = 0; i < tal_count(txs); i++)
json_transaction_details(response, &txs[i]);
json_array_end(response);
return command_success(cmd, response);
}
static const struct json_command listtransactions_command = {
"listtransactions",
"payment",
json_listtransactions,
"List transactions that we stored in the wallet",
false,
"Returns transactions tracked in the wallet. This includes deposits, "
"withdrawals and transactions related to channels. A transaction may have "
"multiple types, e.g., a transaction may both be a close and a deposit if "
"it closes the channel and returns funds to the wallet."
};
AUTODATA(json_command, &listtransactions_command);
static bool in_only_inputs(const u32 *only_inputs, u32 this)
{
for (size_t i = 0; i < tal_count(only_inputs); i++)
if (only_inputs[i] == this)
return true;
return false;
}
static struct command_result *match_psbt_inputs_to_utxos(struct command *cmd,
struct wally_psbt *psbt,
const u32 *only_inputs,
struct utxo ***utxos)
{
*utxos = tal_arr(cmd, struct utxo *, 0);
for (size_t i = 0; i < psbt->tx->num_inputs; i++) {
struct utxo *utxo;
struct bitcoin_outpoint outpoint;
if (only_inputs && !in_only_inputs(only_inputs, i))
continue;
wally_tx_input_get_outpoint(&psbt->tx->inputs[i], &outpoint);
utxo = wallet_utxo_get(*utxos, cmd->ld->wallet, &outpoint);
if (!utxo) {
if (only_inputs)
return command_fail(cmd, LIGHTNINGD,
"Aborting PSBT signing. UTXO %s is unknown (and specified by signonly)",
type_to_string(tmpctx, struct bitcoin_outpoint,
&outpoint));
continue;
}
/* Oops we haven't reserved this utxo yet! */
if (!utxo_is_reserved(utxo, get_block_height(cmd->ld->topology)))
return command_fail(cmd, LIGHTNINGD,
"Aborting PSBT signing. UTXO %s is not reserved",
type_to_string(tmpctx, struct bitcoin_outpoint,
&utxo->outpoint));
tal_arr_expand(utxos, utxo);
}
return NULL;
}
static void match_psbt_outputs_to_wallet(struct wally_psbt *psbt,
struct wallet *w)
{
assert(psbt->tx->num_outputs == psbt->num_outputs);
tal_wally_start();
for (size_t outndx = 0; outndx < psbt->num_outputs; ++outndx) {
u32 index;
bool is_p2sh;
const u8 *script;
struct ext_key ext;
script = wally_tx_output_get_script(tmpctx,
&psbt->tx->outputs[outndx]);
if (!script)
continue;
if (!wallet_can_spend(w, script, &index, &is_p2sh))
continue;
if (bip32_key_from_parent(
w->bip32_base, index, BIP32_FLAG_KEY_PUBLIC, &ext) != WALLY_OK) {
abort();
}
psbt_set_keypath(index, &ext, &psbt->outputs[outndx].keypaths);
}
tal_wally_end(psbt);
}
static struct command_result *param_input_numbers(struct command *cmd,
const char *name,
const char *buffer,
const jsmntok_t *tok,
u32 **input_nums)
{
struct command_result *res;
const jsmntok_t *arr, *t;
size_t i;
res = param_array(cmd, name, buffer, tok, &arr);
if (res)
return res;
*input_nums = tal_arr(cmd, u32, arr->size);
json_for_each_arr(i, t, arr) {
u32 *num;
res = param_number(cmd, name, buffer, t, &num);
if (res)
return res;
(*input_nums)[i] = *num;
tal_free(num);
}
return NULL;
}
static struct command_result *json_signpsbt(struct command *cmd,
const char *buffer,
const jsmntok_t *obj UNNEEDED,
const jsmntok_t *params)
{
struct command_result *res;
struct json_stream *response;
struct wally_psbt *psbt, *signed_psbt;
struct utxo **utxos;
u32 *input_nums;
if (!param(cmd, buffer, params,
p_req("psbt", param_psbt, &psbt),
p_opt("signonly", param_input_numbers, &input_nums),
NULL))
return command_param_failed();
/* Sanity check! */
for (size_t i = 0; i < tal_count(input_nums); i++) {
if (input_nums[i] >= psbt->num_inputs)
return command_fail(cmd, JSONRPC2_INVALID_PARAMS,
"signonly[%zu]: %u out of range",
i, input_nums[i]);
}
/* We have to find/locate the utxos that are ours on this PSBT,
* so that the HSM knows how/what to sign for (it's possible some of
* our utxos require more complicated data to sign for e.g.
* closeinfo outputs */
res = match_psbt_inputs_to_utxos(cmd, psbt, input_nums, &utxos);
if (res)
return res;
if (tal_count(utxos) == 0)
return command_fail(cmd, LIGHTNINGD,
"No wallet inputs to sign");
/* Update the keypaths on any outputs that are in our wallet (change addresses). */
match_psbt_outputs_to_wallet(psbt, cmd->ld->wallet);
/* FIXME: hsm will sign almost anything, but it should really
* fail cleanly (not abort!) and let us report the error here. */
u8 *msg = towire_hsmd_sign_withdrawal(cmd,
cast_const2(const struct utxo **, utxos),
psbt);
if (!wire_sync_write(cmd->ld->hsm_fd, take(msg)))
fatal("Could not write sign_withdrawal to HSM: %s",
strerror(errno));
msg = wire_sync_read(cmd, cmd->ld->hsm_fd);
if (!fromwire_hsmd_sign_withdrawal_reply(cmd, msg, &signed_psbt))
fatal("HSM gave bad sign_withdrawal_reply %s",
tal_hex(tmpctx, msg));
response = json_stream_success(cmd);
json_add_psbt(response, "signed_psbt", signed_psbt);
return command_success(cmd, response);
}
static const struct json_command signpsbt_command = {
"signpsbt",
"bitcoin",
json_signpsbt,
"Sign this wallet's inputs on a provided PSBT.",
false
};
AUTODATA(json_command, &signpsbt_command);
struct sending_psbt {
struct command *cmd;
struct utxo **utxos;
struct wally_tx *wtx;
/* Hold onto b/c has data about
* which are to external addresses */
struct wally_psbt *psbt;
u32 reserve_blocks;
};
static void maybe_notify_new_external_send(struct lightningd *ld,
struct bitcoin_txid *txid,
u32 outnum,
struct wally_psbt *psbt)
{
struct chain_coin_mvt *mvt;
struct bitcoin_outpoint outpoint;
struct amount_sat amount;
u32 index;
bool is_p2sh;
const u8 *script;
/* If it's not going to an external address, ignore */
if (!psbt_output_to_external(&psbt->outputs[outnum]))
return;
/* If it's going to our wallet, ignore */
script = wally_tx_output_get_script(tmpctx,
&psbt->tx->outputs[outnum]);
if (wallet_can_spend(ld->wallet, script, &index, &is_p2sh))
return;
outpoint.txid = *txid;
outpoint.n = outnum;
amount = psbt_output_get_amount(psbt, outnum);
mvt = new_coin_external_deposit(NULL, &outpoint,
0, amount,
DEPOSIT);
mvt->originating_acct = WALLET;
notify_chain_mvt(ld, mvt);
tal_free(mvt);
}
static void sendpsbt_done(struct bitcoind *bitcoind UNUSED,
bool success, const char *msg,
struct sending_psbt *sending)
{
struct lightningd *ld = sending->cmd->ld;
struct json_stream *response;
struct bitcoin_txid txid;
struct amount_sat change;
if (!success) {
/* Unreserve the inputs again. */
for (size_t i = 0; i < tal_count(sending->utxos); i++) {
wallet_unreserve_utxo(ld->wallet,
sending->utxos[i],
get_block_height(ld->topology),
sending->reserve_blocks);
}
was_pending(command_fail(sending->cmd, LIGHTNINGD,
"Error broadcasting transaction: %s."
" Unsent tx discarded %s",
msg,
type_to_string(tmpctx, struct wally_tx,
sending->wtx)));
return;
}
wallet_transaction_add(ld->wallet, sending->wtx, 0, 0);
/* Extract the change output and add it to the DB */
wallet_extract_owned_outputs(ld->wallet, sending->wtx, NULL, &change);
wally_txid(sending->wtx, &txid);
for (size_t i = 0; i < sending->psbt->num_outputs; i++)
maybe_notify_new_external_send(ld, &txid, i, sending->psbt);
response = json_stream_success(sending->cmd);
json_add_hex_talarr(response, "tx", linearize_wtx(tmpctx, sending->wtx));
json_add_txid(response, "txid", &txid);
was_pending(command_success(sending->cmd, response));
}
static struct command_result *json_sendpsbt(struct command *cmd,
const char *buffer,
const jsmntok_t *obj UNNEEDED,
const jsmntok_t *params)
{
struct command_result *res;
struct sending_psbt *sending;
struct wally_psbt *psbt;
struct lightningd *ld = cmd->ld;
u32 *reserve_blocks;
if (!param(cmd, buffer, params,
p_req("psbt", param_psbt, &psbt),
p_opt_def("reserve", param_number, &reserve_blocks, 12 * 6),
NULL))
return command_param_failed();
sending = tal(cmd, struct sending_psbt);
sending->cmd = cmd;
sending->reserve_blocks = *reserve_blocks;
psbt_finalize(psbt);
sending->wtx = psbt_final_tx(sending, psbt);
/* psbt contains info about which outputs are to external,
* and thus need a coin_move issued for them. We only
* notify if the transaction broadcasts */
sending->psbt = tal_steal(sending, psbt);
if (!sending->wtx)
return command_fail(cmd, LIGHTNINGD,
"PSBT not finalizeable %s",
type_to_string(tmpctx, struct wally_psbt,
psbt));
/* We have to find/locate the utxos that are ours on this PSBT,
* so that we know who to mark as used.
*/
res = match_psbt_inputs_to_utxos(cmd, psbt, NULL, &sending->utxos);
if (res)
return res;
for (size_t i = 0; i < tal_count(sending->utxos); i++) {
if (!wallet_reserve_utxo(ld->wallet, sending->utxos[i],
get_block_height(ld->topology),
sending->reserve_blocks))
fatal("UTXO not reservable?");
}
/* Now broadcast the transaction */
bitcoind_sendrawtx(cmd->ld->topology->bitcoind,
tal_hex(tmpctx,
linearize_wtx(tmpctx, sending->wtx)),
sendpsbt_done, sending);
return command_still_pending(cmd);
}
static const struct json_command sendpsbt_command = {
"sendpsbt",
"bitcoin",
json_sendpsbt,
"Finalize, extract and send a PSBT.",
false
};
AUTODATA(json_command, &sendpsbt_command);