forked from ElementsProject/lightning
-
Notifications
You must be signed in to change notification settings - Fork 0
/
onchain.c
2314 lines (2057 loc) · 68.8 KB
/
onchain.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 <bitcoin/script.h>
#include <ccan/crypto/shachain/shachain.h>
#include <ccan/mem/mem.h>
#include <ccan/structeq/structeq.h>
#include <ccan/tal/str/str.h>
#include <common/derive_basepoints.h>
#include <common/htlc_tx.h>
#include <common/initial_commit_tx.h>
#include <common/key_derive.h>
#include <common/keyset.h>
#include <common/peer_billboard.h>
#include <common/status.h>
#include <common/subdaemon.h>
#include <common/type_to_string.h>
#include <common/utils.h>
#include <common/version.h>
#include <errno.h>
#include <inttypes.h>
#include <lightningd/channel_state.h>
#include <onchaind/gen_onchain_wire.h>
#include <onchaind/onchain_types.h>
#include <stdio.h>
#include <unistd.h>
#include <wire/wire_sync.h>
#include "gen_onchain_types_names.h"
/* stdin == requests */
#define REQ_FD STDIN_FILENO
/* Required in various places: keys for commitment transaction. */
static const struct keyset *keyset;
/* The feerate to use when we generate transactions. */
static u32 feerate_per_kw;
/* 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 u64 dust_limit_satoshis;
/* 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;
/* Private keys for spending HTLC outputs via HTLC txs, delayed, and directly. */
static struct privkey htlc_privkey, delayed_payment_privkey, payment_privkey;
/* Private keys for spending HTLC for penalty (only if they cheated). */
static struct privkey *revocation_privkey;
/* 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;
/* 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_txid txid;
u32 tx_blockheight;
/* FIXME: Convert all depths to blocknums, then just get new blk msgs */
u32 depth;
u32 outnum;
u64 satoshi;
enum output_type output_type;
/* If it is an HTLC, these are non-NULL */
const struct htlc_stub *htlc;
const u8 *wscript;
/* If it's an HTLC off our unilateral, this is their sig for htlc_tx */
const secp256k1_ecdsa_signature *remote_htlc_sig;
/* Our proposed solution (if any) */
struct proposed_resolution *proposal;
/* If it is resolved. */
struct resolution *resolved;
};
/* We vary feerate until signature they offered matches. */
static u64 grind_htlc_tx_fee(struct bitcoin_tx *tx,
const secp256k1_ecdsa_signature *remotesig,
const u8 *wscript,
u64 multiplier)
{
u64 prev_fee = UINT64_MAX;
u64 input_amount = *tx->input[0].amount;
for (u64 i = min_possible_feerate; i <= max_possible_feerate; i++) {
/* BOLT #3:
*
* The fee for an HTLC-timeout transaction:
* - MUST BE calculated to match:
* 1. Multiply `feerate_per_kw` by 663 and divide by 1000
* (rounding down).
*
* The fee for an HTLC-success transaction:
* - MUST BE calculated to match:
* 1. Multiply `feerate_per_kw` by 703 and divide by 1000
* (rounding down).
*/
u64 fee = i * multiplier / 1000;
if (fee > input_amount)
break;
/* Minor optimization: don't check same fee twice */
if (fee == prev_fee)
continue;
prev_fee = fee;
tx->output[0].amount = input_amount - fee;
if (!check_tx_sig(tx, 0, NULL, wscript,
&keyset->other_htlc_key, remotesig))
continue;
return fee;
}
status_failed(STATUS_FAIL_INTERNAL_ERROR,
"grind_fee failed from %u - %u"
" for tx %s, inputamount %"PRIu64", signature %s, wscript %s, multiplier %"PRIu64,
min_possible_feerate, max_possible_feerate,
type_to_string(tmpctx, struct bitcoin_tx, tx),
input_amount,
type_to_string(tmpctx, secp256k1_ecdsa_signature, remotesig),
tal_hex(tmpctx, wscript),
multiplier);
}
static void set_htlc_timeout_fee(struct bitcoin_tx *tx,
const secp256k1_ecdsa_signature *remotesig,
const u8 *wscript)
{
static u64 fee = UINT64_MAX;
/* BOLT #3:
*
* The fee for an HTLC-timeout transaction:
* - MUST BE calculated to match:
* 1. Multiply `feerate_per_kw` by 663 and divide by 1000 (rounding
* down).
*/
if (fee == UINT64_MAX) {
fee = grind_htlc_tx_fee(tx, remotesig, wscript, 663);
return;
}
tx->output[0].amount = *tx->input[0].amount - fee;
if (check_tx_sig(tx, 0, NULL, wscript,
&keyset->other_htlc_key, remotesig))
return;
status_failed(STATUS_FAIL_INTERNAL_ERROR,
"htlc_timeout_fee %"PRIu64" failed sigcheck "
" for tx %s, signature %s, wscript %s",
fee,
type_to_string(tmpctx, struct bitcoin_tx, tx),
type_to_string(tmpctx, secp256k1_ecdsa_signature, remotesig),
tal_hex(tmpctx, wscript));
}
static void set_htlc_success_fee(struct bitcoin_tx *tx,
const secp256k1_ecdsa_signature *remotesig,
const u8 *wscript)
{
static u64 fee = UINT64_MAX;
/* BOLT #3:
*
* The fee for an HTLC-success transaction:
* - MUST BE calculated to match:
* 1. Multiply `feerate_per_kw` by 703 and divide by 1000
* (rounding down).
*/
if (fee == UINT64_MAX) {
fee = grind_htlc_tx_fee(tx, remotesig, wscript, 703);
return;
}
tx->output[0].amount = *tx->input[0].amount - fee;
if (check_tx_sig(tx, 0, NULL, wscript,
&keyset->other_htlc_key, remotesig))
return;
status_failed(STATUS_FAIL_INTERNAL_ERROR,
"htlc_success_fee %"PRIu64" failed sigcheck "
" for tx %s, signature %s, wscript %s",
fee,
type_to_string(tmpctx, struct bitcoin_tx, tx),
type_to_string(tmpctx, secp256k1_ecdsa_signature, remotesig),
tal_hex(tmpctx, wscript));
}
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";
}
/*
* 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,
struct tracked_output *out,
u32 to_self_delay,
u32 locktime,
const void *elem, size_t elemsize,
const u8 *wscript,
const struct privkey *privkey,
const struct pubkey *pubkey,
enum tx_type *tx_type)
{
struct bitcoin_tx *tx;
u64 fee;
secp256k1_ecdsa_signature sig;
tx = bitcoin_tx(ctx, 1, 1);
tx->lock_time = locktime;
tx->input[0].sequence_number = to_self_delay;
tx->input[0].txid = out->txid;
tx->input[0].index = out->outnum;
tx->input[0].amount = tal_dup(tx->input, u64, &out->satoshi);
tx->output[0].amount = out->satoshi;
tx->output[0].script = scriptpubkey_p2wpkh(tx->output,
&our_wallet_pubkey);
/* Worst-case sig is 73 bytes */
fee = feerate_per_kw * (measure_tx_weight(tx)
+ 1 + 3 + 73 + 0 + tal_len(wscript))
/ 1000;
/* Result is trivial? Spent to OP_RETURN to avoid leaving dust. */
if (tx->output[0].amount < dust_limit_satoshis + fee) {
tx->output[0].amount = 0;
tx->output[0].script = scriptpubkey_opreturn(tx->output);
*tx_type = DONATING_TO_MINERS;
} else
tx->output[0].amount -= fee;
sign_tx_input(tx, 0, NULL, wscript, privkey, pubkey, &sig);
tx->input[0].witness = bitcoin_witness_sig_and_element(tx->input,
&sig,
elem, elemsize,
wscript);
return tx;
}
static struct tracked_output *
new_tracked_output(struct tracked_output ***outs,
const struct bitcoin_txid *txid,
u32 tx_blockheight,
enum tx_type tx_type,
u32 outnum,
u64 satoshi,
enum output_type output_type,
const struct htlc_stub *htlc,
const u8 *wscript,
const secp256k1_ecdsa_signature *remote_htlc_sig)
{
size_t n = tal_count(*outs);
struct tracked_output *out = tal(*outs, struct tracked_output);
status_trace("Tracking output %u of %s: %s/%s",
outnum,
type_to_string(tmpctx, struct bitcoin_txid, txid),
tx_type_name(tx_type),
output_type_name(output_type));
out->tx_type = tx_type;
out->txid = *txid;
out->tx_blockheight = tx_blockheight;
out->depth = 0;
out->outnum = outnum;
out->satoshi = satoshi;
out->output_type = output_type;
out->proposal = NULL;
out->resolved = NULL;
out->htlc = htlc;
out->wscript = wscript;
out->remote_htlc_sig = remote_htlc_sig;
tal_resize(outs, n+1);
(*outs)[n] = out;
return out;
}
static void ignore_output(struct tracked_output *out)
{
status_trace("Ignoring output %u of %s: %s/%s",
out->outnum,
type_to_string(tmpctx, struct bitcoin_txid, &out->txid),
tx_type_name(out->tx_type),
output_type_name(out->output_type));
out->resolved = tal(out, struct resolution);
out->resolved->txid = out->txid;
out->resolved->depth = 0;
out->resolved->tx_type = SELF;
}
static void proposal_meets_depth(struct tracked_output *out)
{
/* If we simply wanted to ignore it after some depth */
if (!out->proposal->tx) {
ignore_output(out);
return;
}
status_trace("Broadcasting %s (%s) to resolve %s/%s",
tx_type_name(out->proposal->tx_type),
type_to_string(tmpctx, struct bitcoin_tx, out->proposal->tx),
tx_type_name(out->tx_type),
output_type_name(out->output_type));
wire_sync_write(REQ_FD,
take(towire_onchain_broadcast_tx(NULL,
out->proposal->tx)));
/* We will get a callback when it's in a block. */
}
static void propose_resolution(struct tracked_output *out,
const struct bitcoin_tx *tx,
unsigned int depth_required,
enum tx_type tx_type)
{
status_trace("Propose handling %s/%s by %s (%s) after %u blocks",
tx_type_name(out->tx_type),
output_type_name(out->output_type),
tx_type_name(tx_type),
tx ? type_to_string(tmpctx, struct bitcoin_tx, tx):"IGNORING",
depth_required);
out->proposal = tal(out, struct proposed_resolution);
out->proposal->tx = tal_steal(out->proposal, tx);
out->proposal->depth_required = depth_required;
out->proposal->tx_type = tx_type;
if (depth_required == 0)
proposal_meets_depth(out);
}
static void propose_resolution_at_block(struct tracked_output *out,
const struct bitcoin_tx *tx,
unsigned int block_required,
enum tx_type tx_type)
{
u32 depth;
/* Expiry could be in the past! */
if (block_required < out->tx_blockheight)
depth = 0;
else /* Note that out->tx_blockheight is already at depth 1 */
depth = block_required - out->tx_blockheight + 1;
propose_resolution(out, tx, depth, tx_type);
}
static bool is_valid_sig(const u8 *e)
{
secp256k1_ecdsa_signature sig;
size_t len = tal_len(e);
/* Last byte is sighash flags */
if (len < 1)
return false;
return signature_from_der(e, len-1, &sig);
}
/* We ignore things which look like signatures. */
static bool input_similar(const struct bitcoin_tx_input *i1,
const struct bitcoin_tx_input *i2)
{
if (!structeq(&i1->txid, &i2->txid))
return false;
if (i1->index != i2->index)
return false;
if (!scripteq(i1->script, i2->script))
return false;
if (i1->sequence_number != i2->sequence_number)
return false;
if (tal_count(i1->witness) != tal_count(i2->witness))
return false;
for (size_t i = 0; i < tal_count(i1->witness); i++) {
if (scripteq(i1->witness[i], i2->witness[i]))
continue;
if (is_valid_sig(i1->witness[i]) && is_valid_sig(i2->witness[i]))
continue;
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 bitcoin_tx *tx)
{
/* If there's no TX associated, it's not us. */
if (!out->proposal->tx)
return false;
out->resolved = tal(out, struct resolution);
/* Our proposal can change as feerates change. Input
* comparison (ignoring signatures) works pretty well.
*
* FIXME: Better would be to compare outputs, but they weren't
* saved to db correctly until now. (COMPAT_V052)
*/
if (tal_count(tx->input) != tal_count(out->proposal->tx->input))
return false;
for (size_t i = 0; i < tal_count(tx->input); i++) {
if (!input_similar(tx->input + i, out->proposal->tx->input + i))
return false;
}
bitcoin_txid(tx, &out->resolved->txid);
status_trace("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;
/* Don't need proposal any more */
out->proposal = tal_free(out->proposal);
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_trace("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 bitcoin_tx *tx)
{
out->resolved = tal(out, struct resolution);
bitcoin_txid(tx, &out->resolved->txid);
out->resolved->depth = 0;
out->resolved->tx_type = UNKNOWN_TXTYPE;
/* FIXME: we need a louder warning! */
status_trace("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_tx, tx));
}
static u64 unmask_commit_number(const struct bitcoin_tx *tx,
enum side funder,
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 transaction number is obscured by
* `XOR` with the lower 48 bits of...
*/
obscurer = commit_number_obscurer(keys[funder], keys[!funder]);
/* BOLT #3:
*
* * locktime: upper 8 bits are 0x20, lower 24 bits are the
* lower 24 bits of the obscured commitment transaction
* number.
*...
* * `txin[0]` sequence: upper 8 bits are 0x80, lower 24 bits
* are upper 24 bits of the obscured commitment
* transaction number.
*/
return ((tx->lock_time & 0x00FFFFFF)
| (tx->input[0].sequence_number & (u64)0x00FFFFFF) << 24)
^ obscurer;
}
static bool is_mutual_close(const struct bitcoin_tx *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->output); i++) {
/* To be paranoid, we only let each one match once. */
if (scripteq(tx->output[i].script, local_scriptpubkey)
&& !local_matched)
local_matched = true;
else if (scripteq(tx->output[i].script, 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 structeq(txid, our_broadcast_txid);
}
/* BOLT #5:
*
* Outputs which are *resolved* are considered *irrevocably resolved*
* once their *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;
}
static u32 prop_blockheight(const struct tracked_output *out)
{
return out->tx_blockheight + 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)
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:%u) using %s",
num_not_irrevocably_resolved(outs),
output_type_name(best->output_type),
type_to_string(tmpctx, struct bitcoin_txid,
&best->txid),
best->outnum,
tx_type_name(best->proposal->tx_type));
} else {
peer_billboard(false,
"%u outputs unresolved: in %u blocks will spend %s (%s:%u) 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_txid,
&best->txid),
best->outnum,
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_tx(const struct bitcoin_tx *tx)
{
u8 *msg;
struct bitcoin_txid txid;
bitcoin_txid(tx, &txid);
msg = towire_onchain_unwatch_tx(tx, &txid);
wire_sync_write(REQ_FD, take(msg));
}
static void handle_htlc_onchain_fulfill(struct tracked_output *out,
const struct bitcoin_tx *tx)
{
const u8 *witness_preimage;
struct preimage preimage;
struct sha256 sha;
struct ripemd160 ripemd;
/* Our HTLC, they filled (must be an HTLC-success tx). */
if (out->tx_type == THEIR_UNILATERAL) {
/* BOLT #3:
*
* ## HTLC-Timeout and HTLC-Success Transactions
*
* ... `txin[0]` witness stack: `0 <remotehtlcsig> <localhtlcsig>
* <payment_preimage>` for HTLC-Success
*/
if (tal_count(tx->input[0].witness) != 5) /* +1 for wscript */
status_failed(STATUS_FAIL_INTERNAL_ERROR,
"%s/%s spent with weird witness %zu",
tx_type_name(out->tx_type),
output_type_name(out->output_type),
tal_count(tx->input[0].witness));
witness_preimage = tx->input[0].witness[3];
} else if (out->tx_type == OUR_UNILATERAL) {
/* BOLT #3:
*
* The remote node can redeem the HTLC with the witness:
*
* <remotehtlcsig> <payment_preimage>
*/
if (tal_count(tx->input[0].witness) != 3) /* +1 for wscript */
status_failed(STATUS_FAIL_INTERNAL_ERROR,
"%s/%s spent with weird witness %zu",
tx_type_name(out->tx_type),
output_type_name(out->output_type),
tal_count(tx->input[0].witness));
witness_preimage = tx->input[0].witness[1];
} else
status_failed(STATUS_FAIL_INTERNAL_ERROR,
"onchain_fulfill for %s/%s?",
tx_type_name(out->tx_type),
output_type_name(out->output_type));
if (tal_len(witness_preimage) != sizeof(preimage))
status_failed(STATUS_FAIL_INTERNAL_ERROR,
"%s/%s spent with bad witness length %zu",
tx_type_name(out->tx_type),
output_type_name(out->output_type),
tal_len(witness_preimage));
memcpy(&preimage, witness_preimage, sizeof(preimage));
sha256(&sha, &preimage, sizeof(preimage));
ripemd160(&ripemd, &sha, sizeof(sha));
if (!structeq(&ripemd, &out->htlc->ripemd))
status_failed(STATUS_FAIL_INTERNAL_ERROR,
"%s/%s spent with bad preimage %s (ripemd not %s)",
tx_type_name(out->tx_type),
output_type_name(out->output_type),
type_to_string(tmpctx, struct preimage, &preimage),
type_to_string(tmpctx, struct ripemd160,
&out->htlc->ripemd));
/* Tell master we found a preimage. */
status_trace("%s/%s gave us preimage %s",
tx_type_name(out->tx_type),
output_type_name(out->output_type),
type_to_string(tmpctx, struct preimage, &preimage));
wire_sync_write(REQ_FD,
take(towire_onchain_extracted_preimage(NULL,
&preimage)));
}
static void resolve_htlc_tx(struct tracked_output ***outs,
size_t out_index,
const struct bitcoin_tx *htlc_tx,
const struct bitcoin_txid *htlc_txid,
u32 tx_blockheight)
{
struct tracked_output *out;
struct bitcoin_tx *tx;
enum tx_type tx_type = OUR_DELAYED_RETURN_TO_WALLET;
u8 *wscript = bitcoin_wscript_htlc_tx(htlc_tx, to_self_delay[LOCAL],
&keyset->self_revocation_key,
&keyset->self_delayed_payment_key);
/* BOLT #5:
*
* A node SHOULD resolve its own HTLC transaction output by spending
* it to a convenient address. A node MUST wait until the
* `OP_CHECKSEQUENCEVERIFY` delay has passed (as specified by the
* other node's `open_channel` `to_self_delay` field) before spending
* the output.
*/
out = new_tracked_output(outs, htlc_txid, tx_blockheight,
(*outs)[out_index]->resolved->tx_type,
0, htlc_tx->output[0].amount,
DELAYED_OUTPUT_TO_US,
NULL, NULL, NULL);
/* BOLT #3:
*
* ## HTLC-Timeout and HTLC-Success Transactions
*
* These HTLC transactions are almost identical, except the
* HTLC-Timeout transaction is timelocked.
*
* ... to collect the output the local node uses an input with
* nSequence `to_self_delay` and a witness stack `<local_delayedsig>
* 0`
*/
tx = tx_to_us(*outs, out, to_self_delay[LOCAL], 0, NULL, 0,
wscript,
&delayed_payment_privkey,
&keyset->self_delayed_payment_key,
&tx_type);
propose_resolution(out, tx, to_self_delay[LOCAL], tx_type);
}
/* BOLT #5:
*
* 5. _B's HTLC-timeout transaction_: The node MUST *resolve* this by
* spending using the revocation key.
*/
/* BOLT #5:
*
* 6. _B's HTLC-success transaction_: The node MUST *resolve* this by
* spending using the revocation key. The node SHOULD extract
* the payment preimage from the transaction input witness if not
* already known.
*/
static void steal_htlc_tx(struct tracked_output *out)
{
struct bitcoin_tx *tx;
enum tx_type tx_type = OUR_PENALTY_TX;
/* BOLT #3:
*
* To spend this via penalty, the remote node uses a witness stack
* `<revocationsig> 1`
*/
tx = tx_to_us(out, out, 0xFFFFFFFF, 0,
&ONE, sizeof(ONE),
out->wscript,
revocation_privkey,
&keyset->self_revocation_key,
&tx_type);
propose_resolution(out, tx, 0, tx_type);
}
/* An output has been spent: see if it resolves something we care about. */
static void output_spent(struct tracked_output ***outs,
const struct bitcoin_tx *tx,
u32 input_num,
u32 tx_blockheight)
{
struct bitcoin_txid txid;
bitcoin_txid(tx, &txid);
for (size_t i = 0; i < tal_count(*outs); i++) {
struct tracked_output *out = (*outs)[i];
if (out->resolved)
continue;
if (tx->input[input_num].index != out->outnum)
continue;
if (!structeq(&tx->input[input_num].txid, &out->txid))
continue;
/* Was this our resolution? */
if (resolved_by_proposal(out, tx)) {
/* If it's our htlc tx, we need to resolve that, too. */
if (out->resolved->tx_type == OUR_HTLC_SUCCESS_TX
|| out->resolved->tx_type == OUR_HTLC_TIMEOUT_TX)
resolve_htlc_tx(outs, i, tx, &txid,
tx_blockheight);
return;
}
switch (out->output_type) {
case OUTPUT_TO_US:
case DELAYED_OUTPUT_TO_US:
unknown_spend(out, tx);
break;
case THEIR_HTLC:
if (out->tx_type == THEIR_REVOKED_UNILATERAL) {
steal_htlc_tx(out);
} else {
/* We ignore this timeout tx, since we should
* resolve by ignoring once we reach depth. */
}
break;
case OUR_HTLC:
/* The only way they can spend this: fulfill; even
* if it's revoked: */
/* BOLT #5:
*
* 6. _B's HTLC-success transaction_: ... The node
* SHOULD extract the payment preimage from the
* transaction input witness if not already known.
*/
handle_htlc_onchain_fulfill(out, tx);
if (out->tx_type == THEIR_REVOKED_UNILATERAL)
steal_htlc_tx(out);
else {
/* BOLT #5:
*
* If the HTLC output is spent using the
* payment preimage, the HTLC output is
* considered *irrevocably resolved*, and the
* node MUST extract the payment preimage from
* the transaction input witness.
*/
ignore_output(out);
}
break;
case FUNDING_OUTPUT:
/* Master should be restarting us, as this implies
* that our old tx was unspent. */
status_failed(STATUS_FAIL_INTERNAL_ERROR,
"Funding output spent again!");
/* Um, we don't track these! */
case OUTPUT_TO_THEM:
case DELAYED_OUTPUT_TO_THEM:
status_failed(STATUS_FAIL_INTERNAL_ERROR,
"Tracked spend of %s/%s?",
tx_type_name(out->tx_type),
output_type_name(out->output_type));
}
return;
}
/* Not interesting to us, so unwatch the tx and all its outputs */
status_trace("Notified about tx %s output %u spend, but we don't care",
type_to_string(tmpctx, struct bitcoin_txid,
&tx->input[input_num].txid),
tx->input[input_num].index);
unwatch_tx(tx);
}
static void update_resolution_depth(struct tracked_output *out, u32 depth)
{
bool reached_reasonable_depth;
status_trace("%s/%s->%s depth %u",
tx_type_name(out->tx_type),
output_type_name(out->output_type),
tx_type_name(out->resolved->tx_type),
depth);
/* We only set this once. */
reached_reasonable_depth = (out->resolved->depth < reasonable_depth
&& depth >= reasonable_depth);
/* BOLT #5:
*
* If the HTLC output has *timed out* and not been *resolved*,
* the node MUST *resolve* the output and MUST fail the
* corresponding incoming HTLC (if any) once the resolving
* transaction has reached reasonable depth. */
if ((out->resolved->tx_type == OUR_HTLC_TIMEOUT_TX
|| out->resolved->tx_type == OUR_HTLC_TIMEOUT_TO_US)
&& reached_reasonable_depth) {
u8 *msg;
status_trace("%s/%s reached reasonable depth %u",
tx_type_name(out->tx_type),
output_type_name(out->output_type),
depth);
msg = towire_onchain_htlc_timeout(out, out->htlc);
wire_sync_write(REQ_FD, take(msg));
}
out->resolved->depth = depth;
}
static void tx_new_depth(struct tracked_output **outs,
const struct bitcoin_txid *txid, u32 depth)
{
size_t i;
/* Special handling for commitment tx reaching depth */
if (structeq(&outs[0]->resolved->txid, txid)
&& depth >= reasonable_depth
&& missing_htlc_msgs) {
status_trace("Sending %zu missing htlc messages",
tal_count(missing_htlc_msgs));
for (i = 0; i < tal_count(missing_htlc_msgs); i++)
wire_sync_write(REQ_FD, missing_htlc_msgs[i]);
/* Don't do it again. */
missing_htlc_msgs = tal_free(missing_htlc_msgs);
}
for (i = 0; i < tal_count(outs); i++) {
/* Update output depth. */
if (structeq(&outs[i]->txid, txid))
outs[i]->depth = depth;
/* Is this tx resolving an output? */
if (outs[i]->resolved) {
if (structeq(&outs[i]->resolved->txid, txid)) {
update_resolution_depth(outs[i], depth);
}
continue;
}
/* Otherwise, is this something we have a pending
* resolution for? */
if (outs[i]->proposal
&& structeq(&outs[i]->txid, txid)
&& depth >= outs[i]->proposal->depth_required) {
proposal_meets_depth(outs[i]);
}
}
}
/* BOLT #5:
*
* If the node receives (or already knows) a payment preimage for an