forked from ElementsProject/lightning
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathonchain_control.c
1693 lines (1450 loc) · 50.7 KB
/
onchain_control.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "config.h"
#include <bitcoin/feerate.h>
#include <bitcoin/script.h>
#include <ccan/cast/cast.h>
#include <ccan/tal/str/str.h>
#include <common/htlc_tx.h>
#include <common/key_derive.h>
#include <common/psbt_keypath.h>
#include <common/type_to_string.h>
#include <db/exec.h>
#include <errno.h>
#include <hsmd/capabilities.h>
#include <hsmd/hsmd_wiregen.h>
#include <inttypes.h>
#include <lightningd/chaintopology.h>
#include <lightningd/channel.h>
#include <lightningd/channel_control.h>
#include <lightningd/coin_mvts.h>
#include <lightningd/hsm_control.h>
#include <lightningd/onchain_control.h>
#include <lightningd/peer_control.h>
#include <lightningd/subd.h>
#include <onchaind/onchaind_wiregen.h>
#include <wallet/txfilter.h>
#include <wally_bip32.h>
#include <wally_psbt.h>
#include <wire/wire_sync.h>
/* We dump all the known preimages when onchaind starts up. */
static void onchaind_tell_fulfill(struct channel *channel)
{
struct htlc_in_map_iter ini;
struct htlc_in *hin;
u8 *msg;
struct lightningd *ld = channel->peer->ld;
for (hin = htlc_in_map_first(ld->htlcs_in, &ini);
hin;
hin = htlc_in_map_next(ld->htlcs_in, &ini)) {
if (hin->key.channel != channel)
continue;
/* BOLT #5:
*
* A local node:
* - if it receives (or already possesses) a payment preimage
* for an unresolved HTLC output that it has been offered AND
* for which it has committed to an outgoing HTLC:
* - MUST *resolve* the output by spending it, using the
* HTLC-success transaction.
* - MUST NOT reveal its own preimage when it's not the final recipient...
* - MUST resolve the output of that HTLC-success transaction.
* - otherwise:
* - if the *remote node* is NOT irrevocably committed to
* the HTLC:
* - MUST NOT *resolve* the output by spending it.
*/
/* We only set preimage once it's irrevocably committed, and
* we spend even if we don't have an outgoing HTLC (eg. local
* payment complete) */
if (!hin->preimage)
continue;
msg = towire_onchaind_known_preimage(channel, hin->preimage);
subd_send_msg(channel->owner, take(msg));
}
}
/* If we want to know if this HTLC is missing, return depth. */
static bool tell_if_missing(const struct channel *channel,
struct htlc_stub *stub,
bool *tell_immediate)
{
struct htlc_out *hout;
/* Keep valgrind happy. */
*tell_immediate = false;
/* Don't care about incoming HTLCs, just ones we offered. */
if (stub->owner == REMOTE)
return false;
/* Might not be a current HTLC. */
hout = find_htlc_out(channel->peer->ld->htlcs_out, channel, stub->id);
if (!hout)
return false;
/* BOLT #5:
*
* - for any committed HTLC that does NOT have an output in this
* commitment transaction:
* - once the commitment transaction has reached reasonable depth:
* - MUST fail the corresponding incoming HTLC (if any).
* - if no *valid* commitment transaction contains an output
* corresponding to the HTLC.
* - MAY fail the corresponding incoming HTLC sooner.
*/
if (hout->hstate >= RCVD_ADD_REVOCATION
&& hout->hstate < SENT_REMOVE_REVOCATION)
*tell_immediate = true;
log_debug(channel->log,
"We want to know if htlc %"PRIu64" is missing (%s)",
hout->key.id, *tell_immediate ? "immediate" : "later");
return true;
}
static void handle_onchain_init_reply(struct channel *channel, const u8 *msg)
{
struct htlc_stub *stubs;
u64 commit_num;
bool *tell, *tell_immediate;
if (!fromwire_onchaind_init_reply(msg, &commit_num)) {
channel_internal_error(channel, "Invalid onchaind_init_reply %s",
tal_hex(tmpctx, msg));
return;
}
/* FIXME: We may already be ONCHAIN state when we implement restart! */
channel_set_state(channel,
FUNDING_SPEND_SEEN,
ONCHAIN,
REASON_UNKNOWN,
"Onchain init reply");
/* Tell it about any relevant HTLCs */
/* FIXME: Filter by commitnum! */
stubs = wallet_htlc_stubs(tmpctx, channel->peer->ld->wallet, channel,
commit_num);
tell = tal_arr(stubs, bool, tal_count(stubs));
tell_immediate = tal_arr(stubs, bool, tal_count(stubs));
for (size_t i = 0; i < tal_count(stubs); i++) {
tell[i] = tell_if_missing(channel, &stubs[i],
&tell_immediate[i]);
}
msg = towire_onchaind_htlcs(channel, stubs, tell, tell_immediate);
subd_send_msg(channel->owner, take(msg));
/* Tell it about any preimages we know. */
onchaind_tell_fulfill(channel);
}
/**
* Notify onchaind about the depth change of the watched tx.
*/
static void onchain_tx_depth(struct channel *channel,
const struct bitcoin_txid *txid,
unsigned int depth)
{
u8 *msg;
msg = towire_onchaind_depth(channel, txid, depth);
subd_send_msg(channel->owner, take(msg));
}
/**
* Entrypoint for the txwatch callback, calls onchain_tx_depth.
*/
static enum watch_result onchain_tx_watched(struct lightningd *ld,
struct channel *channel,
const struct bitcoin_txid *txid,
const struct bitcoin_tx *tx,
unsigned int depth)
{
u32 blockheight = get_block_height(ld->topology);
if (tx != NULL) {
struct bitcoin_txid txid2;
bitcoin_txid(tx, &txid2);
if (!bitcoin_txid_eq(txid, &txid2)) {
channel_internal_error(channel, "Txid for %s is not %s",
type_to_string(tmpctx,
struct bitcoin_tx,
tx),
type_to_string(tmpctx,
struct bitcoin_txid,
txid));
return DELETE_WATCH;
}
}
if (depth == 0) {
log_unusual(channel->log, "Chain reorganization!");
channel_set_owner(channel, NULL);
/* We will most likely be freed, so this is a noop */
return KEEP_WATCHING;
}
/* Store the channeltx so we can replay later */
wallet_channeltxs_add(ld->wallet, channel,
WIRE_ONCHAIND_DEPTH, txid, 0, blockheight);
onchain_tx_depth(channel, txid, depth);
return KEEP_WATCHING;
}
static void watch_tx_and_outputs(struct channel *channel,
const struct bitcoin_tx *tx);
/**
* Notify onchaind that an output was spent and register new watches.
*/
static void onchain_txo_spent(struct channel *channel, const struct bitcoin_tx *tx, size_t input_num, u32 blockheight)
{
u8 *msg;
/* Onchaind needs all inputs, since it uses those to compare
* with existing spends (which can vary, with feerate changes). */
struct tx_parts *parts = tx_parts_from_wally_tx(tmpctx, tx->wtx,
-1, -1);
watch_tx_and_outputs(channel, tx);
msg = towire_onchaind_spent(channel, parts, input_num, blockheight);
subd_send_msg(channel->owner, take(msg));
}
/**
* Entrypoint for the txowatch callback, stores tx and calls onchain_txo_spent.
*/
static enum watch_result onchain_txo_watched(struct channel *channel,
const struct bitcoin_tx *tx,
size_t input_num,
const struct block *block)
{
struct bitcoin_txid txid;
bitcoin_txid(tx, &txid);
/* Store the channeltx so we can replay later */
wallet_channeltxs_add(channel->peer->ld->wallet, channel,
WIRE_ONCHAIND_SPENT, &txid, input_num,
block->height);
onchain_txo_spent(channel, tx, input_num, block->height);
/* We don't need to keep watching: If this output is double-spent
* (reorg), we'll get a zero depth cb to onchain_tx_watched, and
* restart onchaind. */
return DELETE_WATCH;
}
/* To avoid races, we watch the tx and all outputs. */
static void watch_tx_and_outputs(struct channel *channel,
const struct bitcoin_tx *tx)
{
struct bitcoin_outpoint outpoint;
struct txwatch *txw;
struct lightningd *ld = channel->peer->ld;
bitcoin_txid(tx, &outpoint.txid);
/* Make txwatch a parent of txo watches, so we can unwatch together. */
txw = watch_tx(channel->owner, ld->topology, channel, tx,
onchain_tx_watched);
for (outpoint.n = 0; outpoint.n < tx->wtx->num_outputs; outpoint.n++)
watch_txo(txw, ld->topology, channel, &outpoint,
onchain_txo_watched);
}
static void handle_onchain_log_coin_move(struct channel *channel, const u8 *msg)
{
struct chain_coin_mvt *mvt = tal(NULL, struct chain_coin_mvt);
if (!fromwire_onchaind_notify_coin_mvt(msg, mvt)) {
channel_internal_error(channel, "Invalid onchain notify_coin_mvt");
return;
}
/* Any 'ignored' payments get registed to the wallet */
if (!mvt->account_name)
mvt->account_name = type_to_string(mvt, struct channel_id,
&channel->cid);
else
mvt->originating_acct = type_to_string(mvt, struct channel_id,
&channel->cid);
notify_chain_mvt(channel->peer->ld, mvt);
tal_free(mvt);
}
static void handle_onchain_unwatch_tx(struct channel *channel, const u8 *msg)
{
struct bitcoin_txid txid;
struct txwatch *txw;
if (!fromwire_onchaind_unwatch_tx(msg, &txid)) {
channel_internal_error(channel, "Invalid onchain_unwatch_tx");
return;
}
/* Frees the txo watches, too: see watch_tx_and_outputs() */
txw = find_txwatch(channel->peer->ld->topology, &txid, channel);
if (!txw)
log_unusual(channel->log, "Can't unwatch txid %s",
type_to_string(tmpctx, struct bitcoin_txid, &txid));
tal_free(txw);
}
static void handle_extracted_preimage(struct channel *channel, const u8 *msg)
{
struct preimage preimage;
if (!fromwire_onchaind_extracted_preimage(msg, &preimage)) {
channel_internal_error(channel, "Invalid extracted_preimage");
return;
}
onchain_fulfilled_htlc(channel, &preimage);
}
static void handle_missing_htlc_output(struct channel *channel, const u8 *msg)
{
struct htlc_stub htlc;
if (!fromwire_onchaind_missing_htlc_output(msg, &htlc)) {
channel_internal_error(channel, "Invalid missing_htlc_output");
return;
}
/* We only set tell_if_missing on LOCAL htlcs */
if (htlc.owner != LOCAL) {
channel_internal_error(channel,
"onchaind_missing_htlc_output: htlc %"PRIu64" is not local!",
htlc.id);
return;
}
/* BOLT #5:
*
* - for any committed HTLC that does NOT have an output in this
* commitment transaction:
* - once the commitment transaction has reached reasonable depth:
* - MUST fail the corresponding incoming HTLC (if any).
* - if no *valid* commitment transaction contains an output
* corresponding to the HTLC.
* - MAY fail the corresponding incoming HTLC sooner.
*/
onchain_failed_our_htlc(channel, &htlc, "missing in commitment tx", false);
}
static void handle_onchain_htlc_timeout(struct channel *channel, const u8 *msg)
{
struct htlc_stub htlc;
if (!fromwire_onchaind_htlc_timeout(msg, &htlc)) {
channel_internal_error(channel, "Invalid onchain_htlc_timeout");
return;
}
/* It should tell us about timeouts on our LOCAL htlcs */
if (htlc.owner != LOCAL) {
channel_internal_error(channel,
"onchaind_htlc_timeout: htlc %"PRIu64" is not local!",
htlc.id);
return;
}
/* BOLT #5:
*
* - if the commitment transaction HTLC output has *timed out* and
* hasn't been *resolved*:
* - MUST *resolve* the output by spending it using the HTLC-timeout
* transaction.
*/
onchain_failed_our_htlc(channel, &htlc, "timed out", true);
}
static void handle_irrevocably_resolved(struct channel *channel, const u8 *msg UNUSED)
{
/* FIXME: Implement check_htlcs to ensure no dangling hout->in ptrs! */
free_htlcs(channel->peer->ld, channel);
log_info(channel->log, "onchaind complete, forgetting peer");
/* This will also free onchaind. */
delete_channel(channel);
}
/**
* onchain_add_utxo -- onchaind is telling us about an UTXO we own
*/
static void onchain_add_utxo(struct channel *channel, const u8 *msg)
{
struct chain_coin_mvt *mvt;
u32 blockheight;
struct bitcoin_outpoint outpoint;
u32 csv_lock;
struct amount_sat amount;
struct pubkey *commitment_point;
u8 *scriptPubkey;
if (!fromwire_onchaind_add_utxo(
tmpctx, msg, &outpoint, &commitment_point,
&amount, &blockheight, &scriptPubkey,
&csv_lock)) {
log_broken(channel->log,
"onchaind gave invalid add_utxo message: %s",
tal_hex(msg, msg));
return;
}
assert(blockheight);
outpointfilter_add(channel->peer->ld->wallet->owned_outpoints,
&outpoint);
log_debug(channel->log, "adding utxo to watch %s, csv %u",
type_to_string(tmpctx, struct bitcoin_outpoint, &outpoint),
csv_lock);
wallet_add_onchaind_utxo(channel->peer->ld->wallet,
&outpoint, scriptPubkey,
blockheight, amount, channel,
commitment_point,
csv_lock);
mvt = new_coin_wallet_deposit(msg, &outpoint, blockheight,
amount, DEPOSIT);
mvt->originating_acct = type_to_string(mvt, struct channel_id,
&channel->cid);
notify_chain_mvt(channel->peer->ld, mvt);
}
static void onchain_annotate_txout(struct channel *channel, const u8 *msg)
{
struct bitcoin_outpoint outpoint;
enum wallet_tx_type type;
if (!fromwire_onchaind_annotate_txout(msg, &outpoint, &type))
fatal("onchaind gave invalid onchain_annotate_txout "
"message: %s",
tal_hex(msg, msg));
wallet_annotate_txout(channel->peer->ld->wallet, &outpoint, type,
channel->dbid);
}
static void onchain_annotate_txin(struct channel *channel, const u8 *msg)
{
struct bitcoin_txid txid;
enum wallet_tx_type type;
u32 innum;
if (!fromwire_onchaind_annotate_txin(msg, &txid, &innum, &type))
fatal("onchaind gave invalid onchain_annotate_txin "
"message: %s",
tal_hex(msg, msg));
wallet_annotate_txin(channel->peer->ld->wallet, &txid, innum, type,
channel->dbid);
}
/* All onchaind-produced txs are actually of the same form: */
struct onchain_signing_info {
/* Fields common to every callback: */
struct channel *channel;
/* Minimum block */
u32 minblock;
/* Block we want this mined by */
u32 deadline_block;
/* Witness script for tx */
u8 *wscript;
/* Trailing element for witness stack */
const tal_t *stack_elem;
/* Information for consider_onchain_rebroadcast */
struct amount_sat fee;
struct bitcoin_outpoint out;
struct amount_sat out_sats;
u32 to_self_delay;
u32 locktime;
u8 *(*sign)(const tal_t *ctx,
const struct bitcoin_tx *tx,
const struct onchain_signing_info *info);
/* Information for consider_onchain_htlc_tx_rebroadcast */
struct bitcoin_tx *raw_htlc_tx;
/* Tagged union (for sanity checking!) */
enum onchaind_wire msgtype;
union {
/* WIRE_ONCHAIND_SPEND_HTLC_TIMEDOUT */
struct {
u64 commit_num;
} htlc_timedout;
/* WIRE_ONCHAIND_SPEND_PENALTY */
struct {
struct secret remote_per_commitment_secret;
} spend_penalty;
/* WIRE_ONCHAIND_SPEND_HTLC_SUCCESS */
struct {
u64 commit_num;
struct bitcoin_signature remote_htlc_sig;
struct preimage preimage;
} htlc_success;
/* WIRE_ONCHAIND_SPEND_HTLC_TIMEOUT */
struct {
u64 commit_num;
struct bitcoin_signature remote_htlc_sig;
} htlc_timeout;
/* WIRE_ONCHAIND_SPEND_FULFILL */
struct {
struct pubkey remote_per_commitment_point;
struct preimage preimage;
} fulfill;
/* WIRE_ONCHAIND_SPEND_HTLC_EXPIRED */
struct {
struct pubkey remote_per_commitment_point;
} htlc_expired;
} u;
};
/* If we don't care / don't know */
static u32 infinite_block_deadline(const struct chain_topology *topo)
{
return get_block_height(topo) + 300;
}
static struct onchain_signing_info *new_signing_info(const tal_t *ctx,
struct channel *channel,
enum onchaind_wire msgtype)
{
struct onchain_signing_info *info = tal(ctx, struct onchain_signing_info);
info->channel = channel;
info->msgtype = msgtype;
return info;
}
static u8 *sign_tx_to_us(const tal_t *ctx,
const struct bitcoin_tx *tx,
const struct onchain_signing_info *info)
{
assert(info->msgtype == WIRE_ONCHAIND_SPEND_TO_US);
return towire_hsmd_sign_any_delayed_payment_to_us(ctx,
info->u.htlc_timedout.commit_num,
tx, info->wscript,
0,
&info->channel->peer->id,
info->channel->dbid);
}
static u8 *sign_penalty(const tal_t *ctx,
const struct bitcoin_tx *tx,
const struct onchain_signing_info *info)
{
assert(info->msgtype == WIRE_ONCHAIND_SPEND_PENALTY);
return towire_hsmd_sign_any_penalty_to_us(ctx,
&info->u.spend_penalty.remote_per_commitment_secret,
tx, info->wscript,
0,
&info->channel->peer->id,
info->channel->dbid);
}
static u8 *sign_htlc_success(const tal_t *ctx,
const struct bitcoin_tx *tx,
const struct onchain_signing_info *info)
{
const bool anchor_outputs = channel_type_has_anchors(info->channel->type);
assert(info->msgtype == WIRE_ONCHAIND_SPEND_HTLC_SUCCESS);
return towire_hsmd_sign_any_local_htlc_tx(ctx,
info->u.htlc_success.commit_num,
tx, info->wscript,
anchor_outputs,
0,
&info->channel->peer->id,
info->channel->dbid);
}
static u8 *sign_htlc_timeout(const tal_t *ctx,
const struct bitcoin_tx *tx,
const struct onchain_signing_info *info)
{
const bool anchor_outputs = channel_type_has_anchors(info->channel->type);
assert(info->msgtype == WIRE_ONCHAIND_SPEND_HTLC_TIMEOUT);
return towire_hsmd_sign_any_local_htlc_tx(ctx,
info->u.htlc_timeout.commit_num,
tx, info->wscript,
anchor_outputs,
0,
&info->channel->peer->id,
info->channel->dbid);
}
static u8 *sign_fulfill(const tal_t *ctx,
const struct bitcoin_tx *tx,
const struct onchain_signing_info *info)
{
const bool anchor_outputs = channel_type_has_anchors(info->channel->type);
assert(info->msgtype == WIRE_ONCHAIND_SPEND_FULFILL);
return towire_hsmd_sign_any_remote_htlc_to_us(ctx,
&info->u.fulfill.remote_per_commitment_point,
tx, info->wscript,
anchor_outputs,
0,
&info->channel->peer->id,
info->channel->dbid);
}
static u8 *sign_htlc_expired(const tal_t *ctx,
const struct bitcoin_tx *tx,
const struct onchain_signing_info *info)
{
const bool anchor_outputs = channel_type_has_anchors(info->channel->type);
assert(info->msgtype == WIRE_ONCHAIND_SPEND_HTLC_EXPIRED);
return towire_hsmd_sign_any_remote_htlc_to_us(ctx,
&info->u.htlc_expired.remote_per_commitment_point,
tx, info->wscript,
anchor_outputs,
0,
&info->channel->peer->id,
info->channel->dbid);
}
/* Matches bitcoin_witness_sig_and_element! */
static const struct onchain_witness_element **
onchain_witness_sig_and_element(const tal_t *ctx, u8 **witness)
{
struct onchain_witness_element **welements;
welements = tal_arr(ctx, struct onchain_witness_element *,
tal_count(witness));
for (size_t i = 0; i < tal_count(welements); i++) {
welements[i] = tal(welements, struct onchain_witness_element);
/* See bitcoin_witness_sig_and_element */
welements[i]->is_signature = (i == 0);
welements[i]->witness = tal_dup_talarr(welements[i], u8,
witness[i]);
}
return cast_const2(const struct onchain_witness_element **, welements);
}
/* Matches bitcoin_witness_htlc_success_tx & bitcoin_witness_htlc_timeout_tx! */
static const struct onchain_witness_element **
onchain_witness_htlc_tx(const tal_t *ctx, u8 **witness)
{
struct onchain_witness_element **welements;
welements = tal_arr(ctx, struct onchain_witness_element *,
tal_count(witness));
for (size_t i = 0; i < tal_count(welements); i++) {
welements[i] = tal(welements, struct onchain_witness_element);
/* See bitcoin_witness_htlc_success_tx / bitcoin_witness_htlc_timeout_tx */
welements[i]->is_signature = (i == 1 || i == 2);
welements[i]->witness = tal_dup_talarr(welements[i], u8,
witness[i]);
}
return cast_const2(const struct onchain_witness_element **, welements);
}
/* Make normal 1-input-1-output tx to us, but don't sign it yet.
*
* If worthwhile is not NULL, we set it to true normally, or false if
* we had to lower fees so much it's unlikely to get mined
* (i.e. "don't wait up!").
*/
static struct bitcoin_tx *onchaind_tx_unsigned(const tal_t *ctx,
struct channel *channel,
const struct onchain_signing_info *info,
struct amount_sat *fee,
bool *worthwhile)
{
struct bitcoin_tx *tx;
struct amount_sat amt;
size_t weight;
struct pubkey final_key;
struct ext_key final_wallet_ext_key;
u64 block_target;
struct lightningd *ld = channel->peer->ld;
bip32_pubkey(ld, &final_key, channel->final_key_idx);
if (bip32_key_from_parent(ld->bip32_base,
channel->final_key_idx,
BIP32_FLAG_KEY_PUBLIC,
&final_wallet_ext_key) != WALLY_OK) {
channel_internal_error(channel,
"Could not derive final_wallet_ext_key %"PRIu64,
channel->final_key_idx);
return NULL;
}
tx = bitcoin_tx(ctx, chainparams, 1, 1, info->locktime);
bitcoin_tx_add_input(tx, &info->out, info->to_self_delay,
NULL, info->out_sats, NULL, info->wscript);
bitcoin_tx_add_output(
tx, scriptpubkey_p2wpkh(tmpctx, &final_key), NULL, info->out_sats);
psbt_add_keypath_to_last_output(tx, channel->final_key_idx, &final_wallet_ext_key);
/* Worst-case sig is 73 bytes */
weight = bitcoin_tx_weight(tx) + 1 + 3 + 73 + 0 + tal_count(info->wscript);
weight += elements_tx_overhead(chainparams, 1, 1);
block_target = info->deadline_block;
for (;;) {
u32 feerate;
feerate = feerate_for_target(ld->topology, block_target);
*fee = amount_tx_fee(feerate, weight);
log_debug(channel->log,
"Feerate for target %"PRIu64" (%+"PRId64" blocks) is %u, fee %s of %s",
block_target,
block_target - get_block_height(ld->topology),
feerate,
type_to_string(tmpctx, struct amount_sat, fee),
type_to_string(tmpctx, struct amount_sat,
&info->out_sats));
/* If we can afford fee and it's not dust, we're done */
if (amount_sat_sub(&amt, info->out_sats, *fee)
&& amount_sat_greater_eq(amt, channel->our_config.dust_limit))
break;
/* Hmm, can't afford with recommended fee. Try increasing deadline! */
block_target++;
/* If we can't even afford at FEERATE_FLOOR, something is wrong! */
if (feerate == FEERATE_FLOOR) {
amt = channel->our_config.dust_limit;
/* Not quite true, but Never Happens */
*fee = AMOUNT_SAT(0);
log_broken(channel->log, "TX can't afford minimal feerate"
"; setting output to %s",
type_to_string(tmpctx, struct amount_sat, &amt));
break;
}
}
/* If we anticipate waiting a long time (say, 20 blocks past
* the deadline), tell onchaind not to wait */
if (worthwhile) {
*worthwhile = (block_target < info->deadline_block + (u64)20);
if (!*worthwhile) {
log_unusual(channel->log,
"Lowballing feerate for %s sats from %u to %u (deadline %u->%"PRIu64"):"
" won't count on it being spent!",
type_to_string(tmpctx, struct amount_sat, &info->out_sats),
feerate_for_target(ld->topology, info->deadline_block),
feerate_for_target(ld->topology, block_target),
info->deadline_block, block_target);
}
}
/* If we came close to target, it's worthwhile to wait for. */
if (block_target != info->deadline_block)
log_debug(channel->log, "Had to adjust deadline from %u to %"PRIu64" for %s",
info->deadline_block, block_target,
type_to_string(tmpctx, struct amount_sat, &info->out_sats));
bitcoin_tx_output_set_amount(tx, 0, amt);
bitcoin_tx_finalize(tx);
return tx;
}
static u8 **sign_and_get_witness(const tal_t *ctx,
const struct channel *channel,
struct bitcoin_tx *tx,
const struct onchain_signing_info *info)
{
const u8 *msg;
struct bitcoin_signature sig;
struct lightningd *ld = channel->peer->ld;
msg = hsm_sync_req(tmpctx, ld, take(info->sign(NULL, tx, info)));
if (!fromwire_hsmd_sign_tx_reply(msg, &sig))
fatal("Reading sign_tx_reply: %s", tal_hex(tmpctx, msg));
return bitcoin_witness_sig_and_element(ctx, &sig, info->stack_elem,
tal_bytelen(info->stack_elem),
info->wscript);
}
/* Always sets *welements, returns tx. Sets *worthwhile to false if
* it wasn't worthwhile at the given feerate (and it had to drop feerate).
* Returns NULL iff it called channel_internal_error().
*/
static struct bitcoin_tx *onchaind_tx(const tal_t *ctx,
struct channel *channel,
const struct onchain_signing_info *info,
struct amount_sat *fee,
bool *worthwhile,
const struct onchain_witness_element ***welements)
{
struct bitcoin_tx *tx;
u8 **witness;
tx = onchaind_tx_unsigned(ctx, channel, info, fee, worthwhile);
if (!tx)
return NULL;
/* Now sign, and set witness */
witness = sign_and_get_witness(NULL, channel, tx, info);
*welements = onchain_witness_sig_and_element(ctx, witness);
bitcoin_tx_input_set_witness(tx, 0, take(witness));
return tx;
}
static bool consider_onchain_rebroadcast(struct channel *channel,
const struct bitcoin_tx **tx,
struct onchain_signing_info *info)
{
struct bitcoin_tx *newtx;
struct amount_sat newfee;
struct bitcoin_txid oldtxid, newtxid;
u8 **witness;
newtx = onchaind_tx_unsigned(tmpctx, channel, info, &newfee, NULL);
if (!newtx)
return true;
/* FIXME: Don't RBF if fee is not sufficiently increased? */
/* OK! RBF time! */
witness = sign_and_get_witness(NULL, channel, newtx, info);
bitcoin_tx_input_set_witness(newtx, 0, take(witness));
bitcoin_txid(newtx, &newtxid);
bitcoin_txid(*tx, &oldtxid);
/* Don't spam the logs! */
log_(channel->log,
amount_sat_less_eq(newfee, info->fee) ? LOG_DBG : LOG_INFORM,
NULL, false,
"RBF onchain txid %s (fee %s) with txid %s (fee %s)",
type_to_string(tmpctx, struct bitcoin_txid, &oldtxid),
fmt_amount_sat(tmpctx, info->fee),
type_to_string(tmpctx, struct bitcoin_txid, &newtxid),
fmt_amount_sat(tmpctx, newfee));
log_debug(channel->log,
"RBF %s->%s",
type_to_string(tmpctx, struct bitcoin_tx, *tx),
type_to_string(tmpctx, struct bitcoin_tx, newtx));
/* FIXME: This is ugly, but we want the same parent as old tx. */
tal_steal(tal_parent(*tx), newtx);
tal_free(*tx);
*tx = newtx;
info->fee = newfee;
return true;
}
static bool consider_onchain_htlc_tx_rebroadcast(struct channel *channel,
const struct bitcoin_tx **tx,
struct onchain_signing_info *info)
{
struct amount_sat change, excess;
struct utxo **utxos;
u32 feerate;
size_t weight;
struct bitcoin_tx *newtx;
size_t locktime;
struct bitcoin_txid oldtxid, newtxid;
struct wally_psbt *psbt;
const u8 *msg;
struct amount_sat oldfee, newfee;
struct lightningd *ld = channel->peer->ld;
/* We can't do much without anchor outputs (we could CPFP?) */
if (!channel_type_has_anchors(channel->type))
return true;
/* Note that we can have UTXOs taken from us if there are a lot of
* closes going on, so we re-fetch them every time. This is messy,
* but since that bitcoind will take the highest feerate ones, it will
* priority order them for us. */
feerate = feerate_for_target(ld->topology, info->deadline_block);
/* Make a copy to play with */
newtx = clone_bitcoin_tx(tmpctx, info->raw_htlc_tx);
weight = bitcoin_tx_weight(newtx);
utxos = tal_arr(tmpctx, struct utxo *, 0);
/* We'll need this to regenerate PSBT */
if (wally_psbt_get_locktime(newtx->psbt, &locktime) != WALLY_OK) {
log_broken(channel->log, "Cannot get psbt locktime?!");
return true;
}
/* Keep attaching input inputs until we get sufficient fees */
while (tx_feerate(newtx) < feerate) {
struct utxo *utxo;
/* Get fresh utxo */
utxo = wallet_find_utxo(tmpctx, ld->wallet,
get_block_height(ld->topology),
NULL,
0, /* FIXME: unused! */
0, false,
cast_const2(const struct utxo **, utxos));
if (!utxo) {
/* Did we get nothing at all? */
if (tal_count(utxos) == 0) {
log_unusual(channel->log,
"We want to bump HTLC fee, but no funds!");
return true;
}
/* At least we got something, right? */
break;
}
/* Add to any UTXOs we have already */
tal_arr_expand(&utxos, utxo);
weight += bitcoin_tx_simple_input_weight(utxo->is_p2sh);
}
/* We were happy with feerate already (can't happen with zero-fee
* anchors!)? */
if (tal_count(utxos) == 0)
return true;
/* PSBT knows how to spend utxos; append to existing. */
psbt = psbt_using_utxos(tmpctx, ld->wallet, utxos, locktime,
BITCOIN_TX_RBF_SEQUENCE, newtx->psbt);
/* Subtract how much we pay in fees for this tx, to calc excess. */
if (!amount_sat_sub(&excess,
psbt_compute_fee(psbt),
amount_sat((u64)weight * feerate / 1000))) {
excess = AMOUNT_SAT(0);
}
change = change_amount(excess, feerate, weight);
if (!amount_sat_eq(change, AMOUNT_SAT(0))) {
/* Append change output. */
struct pubkey final_key;
bip32_pubkey(ld, &final_key, channel->final_key_idx);
psbt_append_output(psbt,
scriptpubkey_p2wpkh(tmpctx, &final_key),
change);
}
/* Sanity check: are we paying more in fees than HTLC is worth? */
if (amount_sat_greater(psbt_compute_fee(psbt), info->out_sats)) {
log_unusual(channel->log,
"Not spending %s in fees to get an HTLC worth %s!",
fmt_amount_sat(tmpctx, psbt_compute_fee(psbt)),
fmt_amount_sat(tmpctx, info->out_sats));
return true;
}
/* Now, get HSM to sign off. */
msg = towire_hsmd_sign_htlc_tx_mingle(NULL,
&channel->peer->id,
channel->dbid,
cast_const2(const struct utxo **,
utxos),
psbt);
msg = hsm_sync_req(tmpctx, ld, take(msg));
if (!fromwire_hsmd_sign_htlc_tx_mingle_reply(tmpctx, msg, &psbt))
fatal("Reading sign_htlc_tx_mingle_reply: %s",
tal_hex(tmpctx, msg));
if (!psbt_finalize(psbt))
fatal("Non-final PSBT from hsm: %s",
type_to_string(tmpctx, struct wally_psbt, psbt));
newtx = tal(tal_parent(*tx), struct bitcoin_tx);
newtx->chainparams = chainparams;
newtx->wtx = psbt_final_tx(newtx, psbt);
assert(newtx->wtx);
newtx->psbt = tal_steal(newtx, psbt);
bitcoin_txid(*tx, &oldtxid);
bitcoin_txid(newtx, &newtxid);
oldfee = bitcoin_tx_compute_fee(*tx);
newfee = bitcoin_tx_compute_fee(newtx);
/* Don't spam the logs! */
log_(channel->log,
amount_sat_less_eq(newfee, oldfee) ? LOG_DBG : LOG_INFORM,
NULL, false,
"RBF HTLC txid %s (fee %s) with txid %s (fee %s)",
type_to_string(tmpctx, struct bitcoin_txid, &oldtxid),
fmt_amount_sat(tmpctx, oldfee),
type_to_string(tmpctx, struct bitcoin_txid, &newtxid),
fmt_amount_sat(tmpctx, newfee));
tal_free(*tx);
*tx = newtx;
return true;
}
/* We want to mine a success tx before they can timeout */
static u32 htlc_incoming_deadline(const struct channel *channel, u64 htlc_id)
{
struct htlc_in *hin;