forked from ElementsProject/lightning
-
Notifications
You must be signed in to change notification settings - Fork 0
/
onchaind.c
3960 lines (3494 loc) · 117 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/asort/asort.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/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 <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;
/* The feerate for the transaction spending our delayed output. */
static u32 delayed_to_us_feerate;
/* The feerate for transactions spending HTLC outputs. */
static u32 htlc_feerate;
/* The feerate for transactions spending from revoked transactions. */
static u32 penalty_feerate;
/* 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 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 before init_reply was processed. */
static 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;
/* 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 {
/* This can be NULL if our proposal is to simply ignore it after depth */
const struct bitcoin_tx *tx;
/* 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";
}
/* 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_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_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_ignored_wallet_deposit(struct tracked_output *out)
{
struct bitcoin_outpoint outpoint;
/* Every spend tx we construct has a single output. */
bitcoin_txid(out->proposal->tx, &outpoint.txid);
outpoint.n = 0;
enum mvt_tag tag = TO_WALLET;
if (out->tx_type == OUR_HTLC_TIMEOUT_TX
|| out->tx_type == OUR_HTLC_SUCCESS_TX)
tag = HTLC_TX;
else if (out->tx_type == THEIR_REVOKED_UNILATERAL)
tag = PENALTY;
else if (out->tx_type == OUR_UNILATERAL
|| out->tx_type == THEIR_UNILATERAL) {
if (out->output_type == OUR_HTLC)
tag = HTLC_TIMEOUT;
}
if (out->output_type == DELAYED_OUTPUT_TO_US)
tag = CHANNEL_TO_US;
/* Record the in/out through the channel */
record_channel_deposit(out, out->tx_blockheight, tag);
record_channel_withdrawal(&outpoint.txid, out, 0, IGNORED);
}
static void record_anchor(struct tracked_output *out)
{
send_coin_mvt(take(new_coin_wallet_deposit(NULL,
&out->outpoint,
out->tx_blockheight,
out->sat, ANCHOR)));
}
static void record_coin_movements(struct tracked_output *out,
u32 blockheight,
const struct bitcoin_tx *tx,
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, blockheight, HTLC_TX);
if (out->resolved->tx_type == OUR_HTLC_TIMEOUT_TO_US)
record_channel_deposit(out, 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, 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, blockheight, CHANNEL_TO_US);
else if (out->output_type == OUR_HTLC) {
record_channel_deposit(out, 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, 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.
* - 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 amount, fee = AMOUNT_SAT_INIT(UINT64_MAX);
struct amount_asset asset = bitcoin_tx_output_get_amount(tx, 0);
size_t weight;
/* 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_anchor_outputs)
weight = 666;
else
weight = 663;
weight = elements_add_overhead(weight, tx->wtx->num_inputs,
tx->wtx->num_outputs);
assert(amount_asset_is_main(&asset));
amount = amount_asset_to_sat(&asset);
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));
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 void set_htlc_success_fee(struct bitcoin_tx *tx,
const struct bitcoin_signature *remotesig,
const u8 *wscript)
{
static struct amount_sat amt, fee = AMOUNT_SAT_INIT(UINT64_MAX);
struct amount_asset asset;
size_t weight;
/* BOLT #3:
*
* The fee for an HTLC-success transaction:
* - If `option_anchors_zero_fee_htlc_tx` applies:
* 1. MUST BE 0.
* - 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_add_overhead(weight, tx->wtx->num_inputs,
tx->wtx->num_outputs);
if (amount_sat_eq(fee, AMOUNT_SAT(UINT64_MAX))) {
if (!grind_htlc_tx_fee(&fee, tx, remotesig, wscript, weight))
status_failed(STATUS_FAIL_INTERNAL_ERROR,
"htlc_success_fee can't be found "
"for tx %s, signature %s, wscript %s",
type_to_string(tmpctx, struct bitcoin_tx,
tx),
type_to_string(tmpctx,
struct bitcoin_signature,
remotesig),
tal_hex(tmpctx, wscript));
return;
}
asset = bitcoin_tx_output_get_amount(tx, 0);
assert(amount_asset_is_main(&asset));
amt = amount_asset_to_sat(&asset);
if (!amount_sat_sub(&amt, amt, fee))
status_failed(STATUS_FAIL_INTERNAL_ERROR,
"Cannot deduct htlc-success fee %s from tx %s",
type_to_string(tmpctx, struct amount_sat, &fee),
type_to_string(tmpctx, struct bitcoin_tx, tx));
bitcoin_tx_output_set_amount(tx, 0, amt);
bitcoin_tx_finalize(tx);
if (check_tx_sig(tx, 0, NULL, wscript,
&keyset->other_htlc_key, remotesig))
return;
status_failed(STATUS_FAIL_INTERNAL_ERROR,
"htlc_success_fee %s failed sigcheck "
" for tx %s, signature %s, wscript %s",
type_to_string(tmpctx, struct amount_sat, &fee),
type_to_string(tmpctx, struct bitcoin_tx, tx),
type_to_string(tmpctx, struct bitcoin_signature, remotesig),
tal_hex(tmpctx, wscript));
}
static u8 *delayed_payment_to_us(const tal_t *ctx,
struct bitcoin_tx *tx,
const u8 *wscript)
{
return towire_hsmd_sign_delayed_payment_to_us(ctx, commit_num,
tx, wscript);
}
static u8 *remote_htlc_to_us(const tal_t *ctx,
struct bitcoin_tx *tx,
const u8 *wscript)
{
return towire_hsmd_sign_remote_htlc_to_us(ctx,
remote_per_commitment_point,
tx, wscript,
option_anchor_outputs);
}
static u8 *penalty_to_us(const tal_t *ctx,
struct bitcoin_tx *tx,
const u8 *wscript)
{
return towire_hsmd_sign_penalty_to_us(ctx, remote_per_commitment_secret,
tx, wscript);
}
/*
* This covers:
* 1. to-us output spend (`<local_delayedsig> 0`)
* 2. the their-commitment, our HTLC timeout case (`<remotehtlcsig> 0`),
* 3. the their-commitment, our HTLC redeem case (`<remotehtlcsig> <payment_preimage>`)
* 4. the their-revoked-commitment, to-local (`<revocation_sig> 1`)
* 5. the their-revoked-commitment, htlc (`<revocation_sig> <revocationkey>`)
*
* Overrides *tx_type if it all turns to dust.
*/
static struct bitcoin_tx *tx_to_us(const tal_t *ctx,
u8 *(*hsm_sign_msg)(const tal_t *ctx,
struct bitcoin_tx *tx,
const u8 *wscript),
struct tracked_output *out,
u32 to_self_delay,
u32 locktime,
const void *elem, size_t elemsize,
const u8 *wscript,
enum tx_type *tx_type,
u32 feerate)
{
struct bitcoin_tx *tx;
struct amount_sat fee, min_out, amt;
struct bitcoin_signature sig;
size_t weight;
u8 *msg;
u8 **witness;
tx = bitcoin_tx(ctx, chainparams, 1, 1, locktime);
bitcoin_tx_add_input(tx, &out->outpoint, to_self_delay,
NULL, out->sat, NULL, wscript);
bitcoin_tx_add_output(
tx, scriptpubkey_p2wpkh(tx, &our_wallet_pubkey), NULL, out->sat);
/* Worst-case sig is 73 bytes */
weight = bitcoin_tx_weight(tx) + 1 + 3 + 73 + 0 + tal_count(wscript);
weight = elements_add_overhead(weight, 1, 1);
fee = amount_tx_fee(feerate, weight);
/* Result is trivial? Spend with small feerate, but don't wait
* around for it as it might not confirm. */
if (!amount_sat_add(&min_out, dust_limit, fee))
status_failed(STATUS_FAIL_INTERNAL_ERROR,
"Cannot add dust_limit %s and fee %s",
type_to_string(tmpctx, struct amount_sat, &dust_limit),
type_to_string(tmpctx, struct amount_sat, &fee));
if (amount_sat_less(out->sat, min_out)) {
/* FIXME: We should use SIGHASH_NONE so others can take it */
fee = amount_tx_fee(feerate_floor(), weight);
status_unusual("TX %s amount %s too small to"
" pay reasonable fee, using minimal fee"
" and ignoring",
tx_type_name(*tx_type),
type_to_string(tmpctx, struct amount_sat, &out->sat));
*tx_type = IGNORING_TINY_PAYMENT;
}
/* This can only happen if feerate_floor() is still too high; shouldn't
* happen! */
if (!amount_sat_sub(&amt, out->sat, fee)) {
amt = dust_limit;
status_broken("TX %s can't afford minimal feerate"
"; setting output to %s",
tx_type_name(*tx_type),
type_to_string(tmpctx, struct amount_sat,
&amt));
}
bitcoin_tx_output_set_amount(tx, 0, amt);
bitcoin_tx_finalize(tx);
if (!wire_sync_write(HSM_FD, take(hsm_sign_msg(NULL, tx, wscript))))
status_failed(STATUS_FAIL_HSM_IO, "Writing sign request to hsm");
msg = wire_sync_read(tmpctx, HSM_FD);
if (!msg || !fromwire_hsmd_sign_tx_reply(msg, &sig)) {
status_failed(STATUS_FAIL_HSM_IO,
"Reading sign_tx_reply: %s",
tal_hex(tmpctx, msg));
}
witness = bitcoin_witness_sig_and_element(tx, &sig, elem,
elemsize, wscript);
bitcoin_tx_input_set_witness(tx, 0, take(witness));
return tx;
}
/** replace_penalty_tx_to_us
*
* @brief creates a replacement TX for
* a given penalty tx.
*
* @param ctx - the context to allocate
* off of.
* @param hsm_sign_msg - function to construct
* the signing message to HSM.
* @param penalty_tx - the original
* penalty transaction.
* @param output_amount - the output
* amount to use instead of the
* original penalty transaction.
* If this amount is below the dust
* limit, the output is replaced with
* an `OP_RETURN` instead.
*
* @return the signed transaction.
*/
static struct bitcoin_tx *
replace_penalty_tx_to_us(const tal_t *ctx,
u8 *(*hsm_sign_msg)(const tal_t *ctx,
struct bitcoin_tx *tx,
const u8 *wscript),
const struct bitcoin_tx *penalty_tx,
struct amount_sat *output_amount)
{
struct bitcoin_tx *tx;
/* The penalty tx input. */
const struct wally_tx_input *input;
/* Specs of the penalty tx input. */
struct bitcoin_outpoint input_outpoint;
u8 *input_wscript;
u8 *input_element;
struct amount_sat input_amount;
/* Signature from the HSM. */
u8 *msg;
struct bitcoin_signature sig;
/* Witness we generate from the signature and other data. */
u8 **witness;
/* Get the single input of the penalty tx. */
input = &penalty_tx->wtx->inputs[0];
/* Extract the input-side data. */
bitcoin_tx_input_get_txid(penalty_tx, 0, &input_outpoint.txid);
input_outpoint.n = input->index;
input_wscript = tal_dup_arr(tmpctx, u8,
input->witness->items[2].witness,
input->witness->items[2].witness_len,
0);
input_element = tal_dup_arr(tmpctx, u8,
input->witness->items[1].witness,
input->witness->items[1].witness_len,
0);
input_amount = psbt_input_get_amount(penalty_tx->psbt, 0);
/* Create the replacement. */
tx = bitcoin_tx(ctx, chainparams, 1, 1, /*locktime*/ 0);
/* Reconstruct the input. */
bitcoin_tx_add_input(tx, &input_outpoint,
BITCOIN_TX_RBF_SEQUENCE,
NULL, input_amount, NULL, input_wscript);
/* Reconstruct the output with a smaller amount. */
if (amount_sat_greater(*output_amount, dust_limit))
bitcoin_tx_add_output(tx,
scriptpubkey_p2wpkh(tx,
&our_wallet_pubkey),
NULL,
*output_amount);
else {
bitcoin_tx_add_output(tx,
scriptpubkey_opreturn_padded(tx),
NULL,
AMOUNT_SAT(0));
*output_amount = AMOUNT_SAT(0);
}
/* Finalize the transaction. */
bitcoin_tx_finalize(tx);
/* Ask HSM to sign it. */
if (!wire_sync_write(HSM_FD, take(hsm_sign_msg(NULL, tx,
input_wscript))))
status_failed(STATUS_FAIL_HSM_IO, "While feebumping penalty: writing sign request to hsm");
msg = wire_sync_read(tmpctx, HSM_FD);
if (!msg || !fromwire_hsmd_sign_tx_reply(msg, &sig))
status_failed(STATUS_FAIL_HSM_IO, "While feebumping penalty: reading sign_tx_reply: %s", tal_hex(tmpctx, msg));
/* Install the witness with the signature. */
witness = bitcoin_witness_sig_and_element(tx, &sig,
input_element,
tal_bytelen(input_element),
input_wscript);
bitcoin_tx_input_set_witness(tx, 0, take(witness));
return tx;
}
/** min_rbf_bump
*
* @brief computes the minimum RBF bump required by
* BIP125, given an index.
*
* @desc BIP125 requires that an replacement transaction
* pay, not just the fee of the evicted transactions,
* but also the minimum relay fee for itself.
* This function assumes that previous RBF attempts
* paid exactly the return value for that attempt, on
* top of the initial transaction fee.
* It can serve as a baseline for other functions that
* compute a suggested fee: get whichever is higher,
* the fee this function suggests, or your own unique
* function.
*
* This function is provided as a common function that
* all RBF-bump computations can use.
*
* @param weight - the weight of the transaction you
* are RBFing.
* @param index - 0 makes no sense, 1 means this is
* the first RBF attempt, 2 means this is the 2nd
* RBF attempt, etc.
*
* @return the suggested total fee.
*/
static struct amount_sat min_rbf_bump(size_t weight,
size_t index)
{
struct amount_sat min_relay_fee;
struct amount_sat min_rbf_bump;
/* Compute the minimum relay fee for a transaction of the given
* weight. */
min_relay_fee = amount_tx_fee(min_relay_feerate, weight);
/* For every RBF attempt, we add the min-relay-fee.
* Or in other words, we multiply the min-relay-fee by the
* index number of the attempt.
*/
if (mul_overflows_u64(index, min_relay_fee.satoshis)) /* Raw: multiplication. */
min_rbf_bump = AMOUNT_SAT(UINT64_MAX);
else
min_rbf_bump.satoshis = index * min_relay_fee.satoshis; /* Raw: multiplication. */
return min_rbf_bump;
}
/** compute_penalty_output_amount
*
* @brief computes the appropriate output amount for a
* penalty transaction that spends a theft transaction
* that is already of a specific depth.
*
* @param initial_amount - the outout amount of the first
* penalty transaction.
* @param depth - the current depth of the theft
* transaction.
* @param max_depth - the maximum depth of the theft
* transaction, after which the theft transaction will
* succeed.
* @param weight - the weight of the first penalty
* transaction, in Sipa.
*/
static struct amount_sat
compute_penalty_output_amount(struct amount_sat initial_amount,
u32 depth, u32 max_depth,
size_t weight)
{
struct amount_sat max_output_amount;
struct amount_sat output_amount;
struct amount_sat deducted_amount;
assert(depth <= max_depth);
assert(depth > 0);
/* The difference between initial_amount, and the fee suggested
* by min_rbf_bump, is the largest allowed output amount.
*
* depth = 1 is the first attempt, thus maps to the 0th RBF
* (i.e. the initial attempt that is not RBFed itself).
* We actually start to replace at depth = 2, so we use
* depth - 1 as the index for min_rbf_bump.
*/
if (!amount_sat_sub(&max_output_amount,
initial_amount, min_rbf_bump(weight, depth - 1)))
/* If min_rbf_bump is larger than the initial_amount,
* we should just donate the whole output as fee,
* meaning we get 0 output amount.
*/
return AMOUNT_SAT(0);
/* Map the depth / max_depth into a number between 0->1. */
double x = (double) depth / (double) max_depth;
/* Get the cube of the above position, resulting in a graph
* where the y is close to 0 up to less than halfway through,
* then quickly rises up to 1 as depth nears the max depth.
*/
double y = x * x * x;
/* Scale according to the initial_amount. */
deducted_amount.satoshis = (u64) (y * initial_amount.satoshis); /* Raw: multiplication. */
/* output_amount = initial_amount - deducted_amount. */
if (!amount_sat_sub(&output_amount,
initial_amount, deducted_amount))
/* If underflow, force to 0. */
output_amount = AMOUNT_SAT(0);
/* If output exceeds max, return max. */
if (amount_sat_less(max_output_amount, output_amount))
return max_output_amount;
return output_amount;
}
static void hsm_sign_local_htlc_tx(struct bitcoin_tx *tx,
const u8 *wscript,
struct bitcoin_signature *sig)
{
u8 *msg = towire_hsmd_sign_local_htlc_tx(NULL, commit_num,
tx, wscript,
option_anchor_outputs);
if (!wire_sync_write(HSM_FD, take(msg)))
status_failed(STATUS_FAIL_HSM_IO,
"Writing sign_local_htlc_tx to hsm");
msg = wire_sync_read(tmpctx, HSM_FD);
if (!msg || !fromwire_hsmd_sign_tx_reply(msg, sig))
status_failed(STATUS_FAIL_HSM_IO,
"Reading sign_local_htlc_tx: %s",
tal_hex(tmpctx, msg));
}
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 TAKES)
{
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 enum wallet_tx_type onchain_txtype_to_wallet_txtype(enum tx_type t)
{
switch (t) {
case FUNDING_TRANSACTION:
return TX_CHANNEL_FUNDING;
case MUTUAL_CLOSE:
return TX_CHANNEL_CLOSE;
case OUR_UNILATERAL:
return TX_CHANNEL_UNILATERAL;
case THEIR_HTLC_FULFILL_TO_US:
case OUR_HTLC_SUCCESS_TX:
return TX_CHANNEL_HTLC_SUCCESS;
case OUR_HTLC_TIMEOUT_TO_US:
case OUR_HTLC_TIMEOUT_TX:
return TX_CHANNEL_HTLC_TIMEOUT;
case OUR_DELAYED_RETURN_TO_WALLET:
case SELF:
return TX_CHANNEL_SWEEP;
case OUR_PENALTY_TX:
return TX_CHANNEL_PENALTY;
case THEIR_DELAYED_CHEAT:
return TX_CHANNEL_CHEAT | TX_THEIRS;
case THEIR_UNILATERAL:
case UNKNOWN_UNILATERAL:
case THEIR_REVOKED_UNILATERAL:
return TX_CHANNEL_UNILATERAL | TX_THEIRS;
case THEIR_HTLC_TIMEOUT_TO_THEM:
return TX_CHANNEL_HTLC_TIMEOUT | TX_THEIRS;
case OUR_HTLC_FULFILL_TO_THEM:
return TX_CHANNEL_HTLC_SUCCESS | TX_THEIRS;
case IGNORING_TINY_PAYMENT:
case UNKNOWN_TXTYPE:
return TX_UNKNOWN;
}
abort();
}
/** proposal_is_rbfable
*
* @brief returns true if the given proposal
* would be RBFed if the output it is tracking
* increases in depth without being spent.
*/
static bool proposal_is_rbfable(const struct proposed_resolution *proposal)
{
/* Future onchain resolutions, such as anchored commitments, might
* want to RBF as well.