forked from ElementsProject/lightning
-
Notifications
You must be signed in to change notification settings - Fork 0
/
onchaind.c
3621 lines (3195 loc) · 107 KB
/
onchaind.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/array_size/array_size.h>
#include <ccan/asort/asort.h>
#include <ccan/cast/cast.h>
#include <ccan/mem/mem.h>
#include <ccan/tal/str/str.h>
#include <common/htlc_tx.h>
#include <common/initial_commit_tx.h>
#include <common/keyset.h>
#include <common/lease_rates.h>
#include <common/memleak.h>
#include <common/overflows.h>
#include <common/peer_billboard.h>
#include <common/psbt_keypath.h>
#include <common/status.h>
#include <common/subdaemon.h>
#include <common/type_to_string.h>
#include <hsmd/hsmd_wiregen.h>
#include <onchaind/onchain_types.h>
#include <onchaind/onchaind_wiregen.h>
#include <unistd.h>
#include <wally_bip32.h>
#include <wire/wire_sync.h>
#include "onchain_types_names_gen.h"
/* stdin == requests */
#define REQ_FD STDIN_FILENO
#define HSM_FD 3
/* Required in various places: keys for commitment transaction. */
static const struct keyset *keyset;
/* IFF it's their commitment tx: HSM can't derive their per-commitment point! */
static const struct pubkey *remote_per_commitment_point;
/* The commitment number we're dealing with (if not mutual close) */
static u64 commit_num;
/* Min and max feerates we ever used */
static u32 min_possible_feerate, max_possible_feerate;
/* The dust limit to use when we generate transactions. */
static struct amount_sat dust_limit;
/* The CSV delays for each side. */
static u32 to_self_delay[NUM_SIDES];
/* Where we send money to (our wallet) */
static u32 our_wallet_index;
static struct ext_key our_wallet_ext_key;
static struct pubkey our_wallet_pubkey;
/* Their revocation secret (only if they cheated). */
static const struct secret *remote_per_commitment_secret;
/* one value is useful for a few witness scripts */
static const u8 ONE = 0x1;
/* When to tell master about HTLCs which are missing/timed out */
static u32 reasonable_depth;
/* The messages to send at that depth. */
static u8 **missing_htlc_msgs;
/* The messages which were sent to us while waiting for a specific msg. */
static const u8 **queued_msgs;
/* Our recorded channel balance at 'chain time' */
static struct amount_msat our_msat;
/* Needed for anchor outputs */
static struct pubkey funding_pubkey[NUM_SIDES];
/* At what commit number does option_static_remotekey apply? */
static u64 static_remotekey_start[NUM_SIDES];
/* Does option_anchor_outputs apply to this commitment tx? */
static bool option_anchor_outputs;
/* Does option_anchors_zero_fee_htlc_tx apply to this commitment tx? */
static bool option_anchors_zero_fee_htlc_tx;
/* The minimum relay feerate acceptable to the fullnode. */
static u32 min_relay_feerate;
/* If we broadcast a tx, or need a delay to resolve the output. */
struct proposed_resolution {
/* Once we had lightningd create tx, here's what it told us
* witnesses were (we ignore sigs!). */
/* NULL if answer is to simply ignore it. */
const struct onchain_witness_element **welements;
/* Non-zero if this is CSV-delayed. */
u32 depth_required;
enum tx_type tx_type;
};
/* How it actually got resolved. */
struct resolution {
struct bitcoin_txid txid;
unsigned int depth;
enum tx_type tx_type;
};
struct tracked_output {
enum tx_type tx_type;
struct bitcoin_outpoint outpoint;
u32 tx_blockheight;
/* FIXME: Convert all depths to blocknums, then just get new blk msgs */
u32 depth;
struct amount_sat sat;
enum output_type output_type;
/* If it is an HTLC, this is set, wscript is non-NULL. */
struct htlc_stub htlc;
const u8 *wscript;
/* If it's an HTLC off our unilateral, this is their sig for htlc_tx */
const struct bitcoin_signature *remote_htlc_sig;
/* Our proposed solution (if any) */
struct proposed_resolution *proposal;
/* If it is resolved. */
struct resolution *resolved;
/* stashed so we can pass it along to the coin ledger */
struct sha256 payment_hash;
};
static const char *tx_type_name(enum tx_type tx_type)
{
size_t i;
for (i = 0; enum_tx_type_names[i].name; i++)
if (enum_tx_type_names[i].v == tx_type)
return enum_tx_type_names[i].name;
return "unknown";
}
static const char *output_type_name(enum output_type output_type)
{
size_t i;
for (i = 0; enum_output_type_names[i].name; i++)
if (enum_output_type_names[i].v == output_type)
return enum_output_type_names[i].name;
return "unknown";
}
static const u8 *queue_until_msg(const tal_t *ctx, enum onchaind_wire mtype)
{
const u8 *msg;
while ((msg = wire_sync_read(ctx, REQ_FD)) != NULL) {
if (fromwire_peektype(msg) == mtype)
return msg;
/* Process later */
tal_arr_expand(&queued_msgs, tal_steal(queued_msgs, msg));
}
status_failed(STATUS_FAIL_HSM_IO, "Waiting for %s: connection lost",
onchaind_wire_name(mtype));
}
/* helper to compare output script with our tal'd script */
static bool wally_tx_output_scripteq(const struct wally_tx_output *out,
const u8 *script)
{
return memeq(out->script, out->script_len, script, tal_bytelen(script));
}
/* The feerate for the HTLC txs (which we grind) are the same as the
* feerate for the main tx. However, there may be dust HTLCs which
* were added to the fee, so we can only estimate a maximum feerate */
static void trim_maximum_feerate(struct amount_sat funding,
const struct tx_parts *commitment)
{
size_t weight;
struct amount_sat fee = funding;
/* FIXME: This doesn't work for elements? */
if (chainparams->is_elements)
return;
weight = bitcoin_tx_core_weight(tal_count(commitment->inputs),
tal_count(commitment->outputs));
/* BOLT #3:
* ## Commitment Transaction
*...
* * `txin[0]` script bytes: 0
* * `txin[0]` witness: `0 <signature_for_pubkey1> <signature_for_pubkey2>`
*/
/* Account for witness (1 byte count + 1 empty + sig + sig) */
assert(tal_count(commitment->inputs) == 1);
weight += bitcoin_tx_input_weight(false, 1 + 1 + 2 * bitcoin_tx_input_sig_weight());
for (size_t i = 0; i < tal_count(commitment->outputs); i++) {
struct amount_asset amt;
weight += bitcoin_tx_output_weight(commitment->outputs[i]
->script_len);
amt = wally_tx_output_get_amount(commitment->outputs[i]);
if (!amount_asset_is_main(&amt))
continue;
if (!amount_sat_sub(&fee, fee, amount_asset_to_sat(&amt))) {
status_failed(STATUS_FAIL_INTERNAL_ERROR,
"Unable to subtract fee");
}
}
status_debug("reducing max_possible_feerate from %u...",
max_possible_feerate);
/* This is naive, but simple. */
while (amount_sat_greater(amount_tx_fee(max_possible_feerate, weight),
fee))
max_possible_feerate--;
status_debug("... to %u", max_possible_feerate);
}
static void send_coin_mvt(struct chain_coin_mvt *mvt TAKES)
{
wire_sync_write(REQ_FD,
take(towire_onchaind_notify_coin_mvt(NULL, mvt)));
if (taken(mvt))
tal_free(mvt);
}
static void record_channel_withdrawal(const struct bitcoin_txid *tx_txid,
struct tracked_output *out,
u32 blockheight,
enum mvt_tag tag)
{
send_coin_mvt(take(new_onchaind_withdraw(NULL, &out->outpoint, tx_txid,
blockheight, out->sat, tag)));
}
static void record_external_spend(const struct bitcoin_txid *txid,
struct tracked_output *out,
u32 blockheight,
enum mvt_tag tag)
{
send_coin_mvt(take(new_coin_external_spend(NULL, &out->outpoint,
txid, blockheight,
out->sat, tag)));
}
static void record_external_spend_tags(const struct bitcoin_txid *txid,
struct tracked_output *out,
u32 blockheight,
enum mvt_tag *tags TAKES)
{
send_coin_mvt(take(new_coin_external_spend_tags(NULL, &out->outpoint,
txid, blockheight,
out->sat, tags)));
}
static void record_external_output(const struct bitcoin_outpoint *out,
struct amount_sat amount,
u32 blockheight,
enum mvt_tag tag)
{
send_coin_mvt(take(new_coin_external_deposit(NULL, out, blockheight,
amount, tag)));
}
static void record_external_deposit(const struct tracked_output *out,
u32 blockheight,
enum mvt_tag tag)
{
record_external_output(&out->outpoint, out->sat, blockheight, tag);
}
static void record_external_deposit_tags(const struct tracked_output *out,
u32 blockheight,
enum mvt_tag *tags TAKES)
{
send_coin_mvt(take(new_coin_external_deposit_tags(NULL, &out->outpoint,
blockheight, out->sat,
tags)));
}
static void record_mutual_close(const struct tx_parts *tx,
const u8 *remote_scriptpubkey,
u32 blockheight)
{
/* FIXME: if we ever change how closes happen, this will
* need to be updated as there's no longer 1 output
* per peer */
for (size_t i = 0; i < tal_count(tx->outputs); i++) {
struct bitcoin_outpoint out;
if (!wally_tx_output_scripteq(tx->outputs[i],
remote_scriptpubkey))
continue;
out.n = i;
out.txid = tx->txid;
record_external_output(&out,
amount_sat(tx->outputs[i]->satoshi),
blockheight,
TO_THEM);
break;
}
}
static void record_channel_deposit(struct tracked_output *out,
u32 blockheight, enum mvt_tag tag)
{
send_coin_mvt(take(new_onchaind_deposit(NULL,
&out->outpoint,
blockheight, out->sat,
tag)));
}
static void record_to_us_htlc_fulfilled(struct tracked_output *out,
u32 blockheight)
{
send_coin_mvt(take(new_onchain_htlc_deposit(NULL,
&out->outpoint,
blockheight,
out->sat,
&out->payment_hash)));
}
static void record_to_them_htlc_fulfilled(struct tracked_output *out,
u32 blockheight)
{
send_coin_mvt(take(new_onchain_htlc_withdraw(NULL,
&out->outpoint,
blockheight,
out->sat,
&out->payment_hash)));
}
static void record_anchor(struct tracked_output *out)
{
enum mvt_tag *tags = new_tag_arr(NULL, ANCHOR);
tal_arr_expand(&tags, IGNORED);
send_coin_mvt(take(new_coin_wallet_deposit_tagged(NULL,
&out->outpoint,
out->tx_blockheight,
out->sat,
tags)));
}
static void record_coin_movements(struct tracked_output *out,
u32 blockheight,
const struct bitcoin_txid *txid)
{
/* For 'timeout' htlcs, we re-record them as a deposit
* before we withdraw them again. When the channel closed,
* we reported this as withdrawn (since we didn't know the
* total amount of pending htlcs that are to-them). So
* we have to "deposit" it again before we withdraw it.
* This is just to make the channel account close out nicely
* AND so we can accurately calculate our on-chain fee burden */
if (out->tx_type == OUR_HTLC_TIMEOUT_TX
|| out->tx_type == OUR_HTLC_SUCCESS_TX)
record_channel_deposit(out, out->tx_blockheight, HTLC_TX);
if (out->resolved->tx_type == OUR_HTLC_TIMEOUT_TO_US)
record_channel_deposit(out, out->tx_blockheight, HTLC_TIMEOUT);
/* there is a case where we've fulfilled an htlc onchain,
* in which case we log a deposit to the channel */
if (out->resolved->tx_type == THEIR_HTLC_FULFILL_TO_US
|| out->resolved->tx_type == OUR_HTLC_SUCCESS_TX)
record_to_us_htlc_fulfilled(out, out->tx_blockheight);
/* If it's our to-us and our close, we publish *another* tx
* which spends the output when the timeout ends */
if (out->tx_type == OUR_UNILATERAL) {
if (out->output_type == DELAYED_OUTPUT_TO_US)
record_channel_deposit(out, out->tx_blockheight,
CHANNEL_TO_US);
else if (out->output_type == OUR_HTLC) {
record_channel_deposit(out, out->tx_blockheight,
HTLC_TIMEOUT);
record_channel_withdrawal(txid, out, blockheight,
HTLC_TIMEOUT);
} else if (out->output_type == THEIR_HTLC)
record_channel_withdrawal(txid, out, blockheight,
HTLC_FULFILL);
}
if (out->tx_type == THEIR_REVOKED_UNILATERAL
|| out->resolved->tx_type == OUR_PENALTY_TX)
record_channel_deposit(out, out->tx_blockheight, PENALTY);
if (out->resolved->tx_type == OUR_DELAYED_RETURN_TO_WALLET
|| out->resolved->tx_type == THEIR_HTLC_FULFILL_TO_US
|| out->output_type == DELAYED_OUTPUT_TO_US
|| out->resolved->tx_type == OUR_HTLC_TIMEOUT_TO_US
|| out->resolved->tx_type == OUR_PENALTY_TX) {
/* penalty rbf cases, the amount might be zero */
if (amount_sat_zero(out->sat))
record_channel_withdrawal(txid, out, blockheight, TO_MINER);
else
record_channel_withdrawal(txid, out, blockheight, TO_WALLET);
}
}
/* We vary feerate until signature they offered matches. */
static bool grind_htlc_tx_fee(struct amount_sat *fee,
struct bitcoin_tx *tx,
const struct bitcoin_signature *remotesig,
const u8 *wscript,
u64 weight)
{
struct amount_sat prev_fee = AMOUNT_SAT(UINT64_MAX), input_amt;
input_amt = psbt_input_get_amount(tx->psbt, 0);
for (u64 i = min_possible_feerate; i <= max_possible_feerate; i++) {
/* BOLT #3:
*
* The fee for an HTLC-timeout transaction:
* - If `option_anchors_zero_fee_htlc_tx` applies:
* 1. MUST be 0.
* - Otherwise, MUST be calculated to match:
* 1. Multiply `feerate_per_kw` by 663
* (666 if `option_anchor_outputs` applies)
* and divide by 1000 (rounding down).
*
* The fee for an HTLC-success transaction:
* - If `option_anchors_zero_fee_htlc_tx` applies:
* 1. MUST be 0.
* - Otherwise, MUST be calculated to match:
* 1. Multiply `feerate_per_kw` by 703
* (706 if `option_anchor_outputs` applies)
* and divide by 1000 (rounding down).
*/
struct amount_sat out;
*fee = amount_tx_fee(i, weight);
/* Minor optimization: don't check same fee twice */
if (amount_sat_eq(*fee, prev_fee))
continue;
prev_fee = *fee;
if (!amount_sat_sub(&out, input_amt, *fee))
break;
bitcoin_tx_output_set_amount(tx, 0, out);
bitcoin_tx_finalize(tx);
if (!check_tx_sig(tx, 0, NULL, wscript,
&keyset->other_htlc_key, remotesig))
continue;
status_debug("grind feerate_per_kw for %"PRIu64" = %"PRIu64,
weight, i);
return true;
}
return false;
}
static bool set_htlc_timeout_fee(struct bitcoin_tx *tx,
const struct bitcoin_signature *remotesig,
const u8 *wscript)
{
static struct amount_sat fee = AMOUNT_SAT_INIT(UINT64_MAX);
struct amount_sat amount;
struct amount_asset asset = bitcoin_tx_output_get_amount(tx, 0);
size_t weight;
amount = amount_asset_to_sat(&asset);
assert(amount_asset_is_main(&asset));
/* BOLT #3:
*
* The fee for an HTLC-timeout transaction:
* - If `option_anchors_zero_fee_htlc_tx` applies:
* 1. MUST be 0.
* - Otherwise, MUST be calculated to match:
* 1. Multiply `feerate_per_kw` by 663 (666 if `option_anchor_outputs`
* applies) and divide by 1000 (rounding down).
*/
if (option_anchors_zero_fee_htlc_tx) {
fee = AMOUNT_SAT(0);
goto set_amount;
}
if (option_anchor_outputs)
weight = 666;
else
weight = 663;
weight += elements_tx_overhead(chainparams, 1, 1);
if (amount_sat_eq(fee, AMOUNT_SAT(UINT64_MAX))) {
struct amount_sat grindfee;
if (grind_htlc_tx_fee(&grindfee, tx, remotesig, wscript, weight)) {
/* Cache this for next time */
fee = grindfee;
return true;
}
return false;
}
if (!amount_sat_sub(&amount, amount, fee))
status_failed(STATUS_FAIL_INTERNAL_ERROR,
"Cannot deduct htlc-timeout fee %s from tx %s",
type_to_string(tmpctx, struct amount_sat, &fee),
type_to_string(tmpctx, struct bitcoin_tx, tx));
set_amount:
bitcoin_tx_output_set_amount(tx, 0, amount);
bitcoin_tx_finalize(tx);
return check_tx_sig(tx, 0, NULL, wscript,
&keyset->other_htlc_key, remotesig);
}
static struct amount_sat get_htlc_success_fee(struct tracked_output *out)
{
static struct amount_sat fee = AMOUNT_SAT_INIT(UINT64_MAX);
size_t weight;
struct amount_msat htlc_amount;
struct bitcoin_tx *tx;
/* We only grind once, since they're all equiv. */
if (!amount_sat_eq(fee, AMOUNT_SAT(UINT64_MAX)))
return fee;
if (option_anchors_zero_fee_htlc_tx) {
fee = AMOUNT_SAT(0);
return fee;
}
if (!amount_sat_to_msat(&htlc_amount, out->sat))
status_failed(STATUS_FAIL_INTERNAL_ERROR,
"Overflow in get_htlc_success_fee %s",
type_to_string(tmpctx,
struct amount_sat,
&out->sat));
tx = htlc_success_tx(tmpctx, chainparams,
&out->outpoint,
out->wscript,
htlc_amount,
to_self_delay[LOCAL],
0,
keyset,
option_anchor_outputs,
option_anchors_zero_fee_htlc_tx);
/* BOLT #3:
*
* The fee for an HTLC-success transaction:
* - If `option_anchors_zero_fee_htlc_tx` applies:
* 1. MUST be 0.
* - Otherwise, MUST be calculated to match:
* 1. Multiply `feerate_per_kw` by 703 (706 if `option_anchor_outputs`
* applies) and divide by 1000 (rounding down).
*/
if (option_anchor_outputs)
weight = 706;
else
weight = 703;
weight += elements_tx_overhead(chainparams, 1, 1);
if (!grind_htlc_tx_fee(&fee, tx, out->remote_htlc_sig,
out->wscript, weight)) {
status_failed(STATUS_FAIL_INTERNAL_ERROR,
"htlc_success_fee can't be found "
"for tx %s (weight %zu, feerate %u-%u), signature %s, wscript %s",
type_to_string(tmpctx, struct bitcoin_tx, tx),
weight,
min_possible_feerate, max_possible_feerate,
type_to_string(tmpctx,
struct bitcoin_signature,
out->remote_htlc_sig),
tal_hex(tmpctx, out->wscript));
}
return fee;
}
static void hsm_get_per_commitment_point(struct pubkey *per_commitment_point)
{
u8 *msg = towire_hsmd_get_per_commitment_point(NULL, commit_num);
struct secret *unused;
if (!wire_sync_write(HSM_FD, take(msg)))
status_failed(STATUS_FAIL_HSM_IO, "Writing sign_htlc_tx to hsm");
msg = wire_sync_read(tmpctx, HSM_FD);
if (!msg
|| !fromwire_hsmd_get_per_commitment_point_reply(tmpctx, msg,
per_commitment_point,
&unused))
status_failed(STATUS_FAIL_HSM_IO,
"Reading hsm_get_per_commitment_point_reply: %s",
tal_hex(tmpctx, msg));
}
static struct tracked_output *
new_tracked_output(struct tracked_output ***outs,
const struct bitcoin_outpoint *outpoint,
u32 tx_blockheight,
enum tx_type tx_type,
struct amount_sat sat,
enum output_type output_type,
const struct htlc_stub *htlc,
const u8 *wscript,
const struct bitcoin_signature *remote_htlc_sig)
{
struct tracked_output *out = tal(*outs, struct tracked_output);
status_debug("Tracking output %s: %s/%s",
type_to_string(tmpctx, struct bitcoin_outpoint, outpoint),
tx_type_name(tx_type),
output_type_name(output_type));
out->tx_type = tx_type;
out->outpoint = *outpoint;
out->tx_blockheight = tx_blockheight;
out->depth = 0;
out->sat = sat;
out->output_type = output_type;
out->proposal = NULL;
out->resolved = NULL;
if (htlc)
out->htlc = *htlc;
out->wscript = tal_steal(out, wscript);
out->remote_htlc_sig = tal_dup_or_null(out, struct bitcoin_signature,
remote_htlc_sig);
tal_arr_expand(outs, out);
return out;
}
static void ignore_output(struct tracked_output *out)
{
status_debug("Ignoring output %s: %s/%s",
type_to_string(tmpctx, struct bitcoin_outpoint,
&out->outpoint),
tx_type_name(out->tx_type),
output_type_name(out->output_type));
out->resolved = tal(out, struct resolution);
out->resolved->txid = out->outpoint.txid;
out->resolved->depth = 0;
out->resolved->tx_type = SELF;
}
static void handle_spend_created(struct tracked_output *out, const u8 *msg)
{
struct onchain_witness_element **witness;
bool worthwhile;
if (!fromwire_onchaind_spend_created(tmpctx, msg, &worthwhile, &witness))
master_badmsg(WIRE_ONCHAIND_SPEND_CREATED, msg);
out->proposal->welements
= cast_const2(const struct onchain_witness_element **,
tal_steal(out->proposal, witness));
/* Did it decide it's not worth it? Don't wait for it. */
if (!worthwhile)
ignore_output(out);
}
static struct proposed_resolution *new_proposed_resolution(struct tracked_output *out,
unsigned int block_required,
enum tx_type tx_type)
{
struct proposed_resolution *proposal = tal(out, struct proposed_resolution);
proposal->tx_type = tx_type;
proposal->depth_required = block_required - out->tx_blockheight;
return proposal;
}
/* Modern style: we don't create tx outselves, but tell lightningd. */
static void propose_resolution_to_master(struct tracked_output *out,
const u8 *send_message TAKES,
unsigned int block_required,
enum tx_type tx_type)
{
/* i.e. we want this in @block_required, so it will be broadcast by
* lightningd after it sees @block_required - 1. */
status_debug("Telling lightningd about %s to resolve %s/%s"
" after block %u (%i more blocks)",
tx_type_name(tx_type),
tx_type_name(out->tx_type),
output_type_name(out->output_type),
block_required - 1, block_required - 1 - out->tx_blockheight);
out->proposal = new_proposed_resolution(out, block_required, tx_type);
wire_sync_write(REQ_FD, send_message);
/* Get reply now: if we're replaying, tx could be included before we
* tell lightningd about it, so we need to recognize it! */
handle_spend_created(out,
queue_until_msg(tmpctx, WIRE_ONCHAIND_SPEND_CREATED));
}
/* Create and broadcast this tx now */
static void propose_immediate_resolution(struct tracked_output *out,
const u8 *send_message TAKES,
enum tx_type tx_type)
{
/* We add 1 to blockheight (meaning you can broadcast it now) to avoid
* having to check for < 0 in various places we print messages */
propose_resolution_to_master(out, send_message, out->tx_blockheight+1,
tx_type);
}
/* If UTXO reaches this block, ignore it (it's not for us, it's ok!) */
static void propose_ignore(struct tracked_output *out,
unsigned int block_required,
enum tx_type tx_type)
{
status_debug("Propose ignoring %s/%s as %s"
" after block %u (%i more blocks)",
tx_type_name(out->tx_type),
output_type_name(out->output_type),
tx_type_name(tx_type),
block_required,
block_required - out->tx_blockheight);
/* If it's already passed, don't underflow. */
if (block_required < out->tx_blockheight)
block_required = out->tx_blockheight;
out->proposal = new_proposed_resolution(out, block_required, tx_type);
out->proposal->welements = NULL;
/* Can we immediately ignore? */
if (out->proposal->depth_required == 0)
ignore_output(out);
}
/* Do any of these tx_parts spend this outpoint? If so, return it */
static const struct wally_tx_input *
which_input_spends(const struct tx_parts *tx_parts,
const struct bitcoin_outpoint *outpoint)
{
for (size_t i = 0; i < tal_count(tx_parts->inputs); i++) {
struct bitcoin_outpoint o;
if (!tx_parts->inputs[i])
continue;
wally_tx_input_get_outpoint(tx_parts->inputs[i], &o);
if (!bitcoin_outpoint_eq(&o, outpoint))
continue;
return tx_parts->inputs[i];
}
return NULL;
}
/* Does this tx input's witness match the witness we expected? */
static bool onchain_witness_element_matches(const struct onchain_witness_element **welements,
const struct wally_tx_input *input)
{
const struct wally_tx_witness_stack *stack = input->witness;
if (stack->num_items != tal_count(welements))
return false;
for (size_t i = 0; i < stack->num_items; i++) {
/* Don't compare signatures: they can change with
* other details */
if (welements[i]->is_signature)
continue;
if (!memeq(stack->items[i].witness,
stack->items[i].witness_len,
welements[i]->witness,
tal_bytelen(welements[i]->witness)))
return false;
}
return true;
}
/* This simple case: true if this was resolved by our proposal. */
static bool resolved_by_proposal(struct tracked_output *out,
const struct tx_parts *tx_parts)
{
const struct wally_tx_input *input;
/* If there's no TX associated, it's not us. */
if (!out->proposal->welements)
return false;
input = which_input_spends(tx_parts, &out->outpoint);
if (!input)
return false;
if (!onchain_witness_element_matches(out->proposal->welements, input))
return false;
out->resolved = tal(out, struct resolution);
out->resolved->txid = tx_parts->txid;
status_debug("Resolved %s/%s by our proposal %s (%s)",
tx_type_name(out->tx_type),
output_type_name(out->output_type),
tx_type_name(out->proposal->tx_type),
type_to_string(tmpctx, struct bitcoin_txid,
&out->resolved->txid));
out->resolved->depth = 0;
out->resolved->tx_type = out->proposal->tx_type;
return true;
}
/* Otherwise, we figure out what happened and then call this. */
static void resolved_by_other(struct tracked_output *out,
const struct bitcoin_txid *txid,
enum tx_type tx_type)
{
out->resolved = tal(out, struct resolution);
out->resolved->txid = *txid;
out->resolved->depth = 0;
out->resolved->tx_type = tx_type;
status_debug("Resolved %s/%s by %s (%s)",
tx_type_name(out->tx_type),
output_type_name(out->output_type),
tx_type_name(tx_type),
type_to_string(tmpctx, struct bitcoin_txid, txid));
}
static void unknown_spend(struct tracked_output *out,
const struct tx_parts *tx_parts)
{
out->resolved = tal(out, struct resolution);
out->resolved->txid = tx_parts->txid;
out->resolved->depth = 0;
out->resolved->tx_type = UNKNOWN_TXTYPE;
status_broken("Unknown spend of %s/%s by %s",
tx_type_name(out->tx_type),
output_type_name(out->output_type),
type_to_string(tmpctx, struct bitcoin_txid,
&tx_parts->txid));
}
static u64 unmask_commit_number(const struct tx_parts *tx,
uint32_t locktime,
enum side opener,
const struct pubkey *local_payment_basepoint,
const struct pubkey *remote_payment_basepoint)
{
u64 obscurer;
const struct pubkey *keys[NUM_SIDES];
keys[LOCAL] = local_payment_basepoint;
keys[REMOTE] = remote_payment_basepoint;
/* BOLT #3:
*
* The 48-bit commitment number is obscured by `XOR` with the lower 48 bits of...
*/
obscurer = commit_number_obscurer(keys[opener], keys[!opener]);
/* BOLT #3:
*
* * locktime: upper 8 bits are 0x20, lower 24 bits are the lower 24 bits of the obscured commitment number
*...
* * `txin[0]` sequence: upper 8 bits are 0x80, lower 24 bits are upper 24 bits of the obscured commitment number
*/
return ((locktime & 0x00FFFFFF)
| (tx->inputs[0]->sequence & (u64)0x00FFFFFF) << 24)
^ obscurer;
}
static bool is_mutual_close(const struct tx_parts *tx,
const u8 *local_scriptpubkey,
const u8 *remote_scriptpubkey)
{
size_t i;
bool local_matched = false, remote_matched = false;
for (i = 0; i < tal_count(tx->outputs); i++) {
/* To be paranoid, we only let each one match once. */
if (chainparams->is_elements &&
tx->outputs[i]->script_len == 0) {
/* This is a fee output, ignore please */
continue;
} else if (wally_tx_output_scripteq(tx->outputs[i],
local_scriptpubkey)
&& !local_matched) {
local_matched = true;
} else if (wally_tx_output_scripteq(tx->outputs[i],
remote_scriptpubkey)
&& !remote_matched)
remote_matched = true;
else
return false;
}
return true;
}
/* We only ever send out one, so matching it is easy. */
static bool is_local_commitment(const struct bitcoin_txid *txid,
const struct bitcoin_txid *our_broadcast_txid)
{
return bitcoin_txid_eq(txid, our_broadcast_txid);
}
/* BOLT #5:
*
* Outputs that are *resolved* are considered *irrevocably resolved*
* once the remote's *resolving* transaction is included in a block at least 100
* deep, on the most-work blockchain.
*/
static size_t num_not_irrevocably_resolved(struct tracked_output **outs)
{
size_t i, num = 0;
for (i = 0; i < tal_count(outs); i++) {
if (!outs[i]->resolved || outs[i]->resolved->depth < 100)
num++;
}
return num;
}
/* If a tx spends @out, and is CSV delayed by @delay, what's the first
* block it can get into? */
static u32 rel_blockheight(const struct tracked_output *out, u32 delay)
{
return out->tx_blockheight + delay;
}
/* What is the first block that the proposal can get into? */
static u32 prop_blockheight(const struct tracked_output *out)
{
return rel_blockheight(out, out->proposal->depth_required);
}
static void billboard_update(struct tracked_output **outs)
{
const struct tracked_output *best = NULL;
/* Highest priority is to report on proposals we have */
for (size_t i = 0; i < tal_count(outs); i++) {
if (!outs[i]->proposal || outs[i]->resolved)
continue;
if (!best || prop_blockheight(outs[i]) < prop_blockheight(best))
best = outs[i];
}
if (best) {
/* If we've broadcast and not seen yet, this happens */
if (best->proposal->depth_required <= best->depth) {
peer_billboard(false,
"%u outputs unresolved: waiting confirmation that we spent %s (%s) using %s",
num_not_irrevocably_resolved(outs),
output_type_name(best->output_type),
type_to_string(tmpctx,
struct bitcoin_outpoint,
&best->outpoint),
tx_type_name(best->proposal->tx_type));
} else {
peer_billboard(false,
"%u outputs unresolved: in %u blocks will spend %s (%s) using %s",
num_not_irrevocably_resolved(outs),
best->proposal->depth_required - best->depth,
output_type_name(best->output_type),
type_to_string(tmpctx,
struct bitcoin_outpoint,
&best->outpoint),
tx_type_name(best->proposal->tx_type));
}
return;
}
/* Now, just report on the last thing we're waiting out. */
for (size_t i = 0; i < tal_count(outs); i++) {
/* FIXME: Can this happen? No proposal, no resolution? */
if (!outs[i]->resolved)
continue;
if (!best || outs[i]->resolved->depth < best->resolved->depth)
best = outs[i];
}
if (best) {
peer_billboard(false,
"All outputs resolved:"
" waiting %u more blocks before forgetting"
" channel",
best->resolved->depth < 100
? 100 - best->resolved->depth : 0);
return;
}
/* Not sure this can happen, but take last one (there must be one!) */
best = outs[tal_count(outs)-1];
peer_billboard(false, "%u outputs unresolved: %s is one (depth %u)",
num_not_irrevocably_resolved(outs),
output_type_name(best->output_type), best->depth);
}
static void unwatch_txid(const struct bitcoin_txid *txid)
{
u8 *msg;
msg = towire_onchaind_unwatch_tx(NULL, txid);