forked from ElementsProject/lightning
-
Notifications
You must be signed in to change notification settings - Fork 0
/
channel_control.c
1218 lines (1066 loc) · 36 KB
/
channel_control.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "config.h"
#include <ccan/cast/cast.h>
#include <channeld/channeld_wiregen.h>
#include <common/json_command.h>
#include <common/json_param.h>
#include <common/json_stream.h>
#include <common/memleak.h>
#include <common/shutdown_scriptpubkey.h>
#include <common/type_to_string.h>
#include <common/wire_error.h>
#include <connectd/connectd_wiregen.h>
#include <errno.h>
#include <hsmd/capabilities.h>
#include <lightningd/chaintopology.h>
#include <lightningd/channel.h>
#include <lightningd/channel_control.h>
#include <lightningd/closing_control.h>
#include <lightningd/coin_mvts.h>
#include <lightningd/dual_open_control.h>
#include <lightningd/gossip_control.h>
#include <lightningd/hsm_control.h>
#include <lightningd/notification.h>
#include <lightningd/peer_control.h>
#include <lightningd/peer_fd.h>
#include <wally_bip32.h>
static void update_feerates(struct lightningd *ld, struct channel *channel)
{
u8 *msg;
u32 feerate = unilateral_feerate(ld->topology);
/* Nothing to do if we don't know feerate. */
if (!feerate)
return;
log_debug(ld->log,
"update_feerates: feerate = %u, min=%u, max=%u, penalty=%u",
feerate,
feerate_min(ld, NULL),
feerate_max(ld, NULL),
try_get_feerate(ld->topology, FEERATE_PENALTY));
msg = towire_channeld_feerates(NULL, feerate,
feerate_min(ld, NULL),
feerate_max(ld, NULL),
try_get_feerate(ld->topology, FEERATE_PENALTY));
subd_send_msg(channel->owner, take(msg));
}
static void try_update_feerates(struct lightningd *ld, struct channel *channel)
{
/* No point until funding locked in */
if (!channel_fees_can_change(channel))
return;
/* Can't if no daemon listening. */
if (!channel->owner)
return;
update_feerates(ld, channel);
}
static void try_update_blockheight(struct lightningd *ld,
struct channel *channel,
u32 blockheight)
{
u8 *msg;
log_debug(channel->log, "attempting update blockheight %s",
type_to_string(tmpctx, struct channel_id, &channel->cid));
/* If they're offline, check that we're not too far behind anyway */
if (!channel->owner) {
if (channel->opener == REMOTE
&& channel->lease_expiry > 0) {
u32 peer_height
= get_blockheight(channel->blockheight_states,
channel->opener, REMOTE);
/* Lease no longer active, we don't (really) care */
if (peer_height >= channel->lease_expiry)
return;
assert(peer_height + 1008 > peer_height);
if (peer_height + 1008 < blockheight)
channel_fail_permanent(channel,
REASON_PROTOCOL,
"Offline peer is too"
" far behind,"
" terminating leased"
" channel. Our current"
" %u, theirs %u",
blockheight,
peer_height);
}
return;
}
/* If we're not opened/locked in yet, don't send update */
if (!channel_fees_can_change(channel))
return;
/* We don't update the blockheight for non-leased chans */
if (channel->lease_expiry == 0)
return;
log_debug(ld->log, "update_blockheight: height = %u", blockheight);
msg = towire_channeld_blockheight(NULL, blockheight);
subd_send_msg(channel->owner, take(msg));
}
void notify_feerate_change(struct lightningd *ld)
{
struct peer *peer;
/* FIXME: We should notify onchaind about NORMAL fee change in case
* it's going to generate more txs. */
list_for_each(&ld->peers, peer, list) {
struct channel *channel;
list_for_each(&peer->channels, channel, list)
try_update_feerates(ld, channel);
}
/* FIXME: We choose not to drop to chain if we can't contact
* peer. We *could* do so, however. */
}
void channel_record_open(struct channel *channel, u32 blockheight, bool record_push)
{
struct chain_coin_mvt *mvt;
struct amount_msat start_balance;
bool is_pushed = !amount_msat_zero(channel->push);
bool is_leased = channel->lease_expiry > 0;
/* If funds were pushed, add/sub them from the starting balance */
if (channel->opener == LOCAL) {
if (!amount_msat_add(&start_balance,
channel->our_msat, channel->push))
fatal("Unable to add push_msat (%s) + our_msat (%s)",
type_to_string(tmpctx, struct amount_msat,
&channel->push),
type_to_string(tmpctx, struct amount_msat,
&channel->our_msat));
} else {
if (!amount_msat_sub(&start_balance,
channel->our_msat, channel->push))
fatal("Unable to sub our_msat (%s) - push (%s)",
type_to_string(tmpctx, struct amount_msat,
&channel->our_msat),
type_to_string(tmpctx, struct amount_msat,
&channel->push));
}
/* If it's not in a block yet, send a proposal */
if (blockheight > 0)
mvt = new_coin_channel_open(tmpctx,
&channel->cid,
&channel->funding,
&channel->peer->id,
blockheight,
start_balance,
channel->funding_sats,
channel->opener == LOCAL,
is_leased);
else
mvt = new_coin_channel_open_proposed(tmpctx,
&channel->cid,
&channel->funding,
&channel->peer->id,
start_balance,
channel->funding_sats,
channel->opener == LOCAL,
is_leased);
notify_chain_mvt(channel->peer->ld, mvt);
/* If we pushed sats, *now* record them */
if (is_pushed && record_push)
notify_channel_mvt(channel->peer->ld,
new_coin_channel_push(tmpctx, &channel->cid,
channel->push,
is_leased ? LEASE_FEE : PUSHED,
channel->opener == REMOTE));
}
static void lockin_complete(struct channel *channel)
{
if (!channel->scid &&
(!channel->alias[REMOTE] || !channel->alias[LOCAL])) {
log_debug(channel->log, "Attempted lockin, but neither scid "
"nor aliases are set, ignoring");
return;
}
/* We set this once they're locked in. */
assert(channel->remote_channel_ready);
/* We might have already started shutting down */
if (channel->state != CHANNELD_AWAITING_LOCKIN) {
log_debug(channel->log, "Lockin complete, but state %s",
channel_state_name(channel));
return;
}
channel_set_state(channel,
CHANNELD_AWAITING_LOCKIN,
CHANNELD_NORMAL,
REASON_UNKNOWN,
"Lockin complete");
/* Fees might have changed (and we use IMMEDIATE once we're funded),
* so update now. */
try_update_feerates(channel->peer->ld, channel);
try_update_blockheight(channel->peer->ld, channel,
get_block_height(channel->peer->ld->topology));
/* Emit an event for the channel open (or channel proposal if blockheight
* is zero) */
channel_record_open(channel,
channel->scid ?
short_channel_id_blocknum(channel->scid) : 0,
true);
}
bool channel_on_channel_ready(struct channel *channel,
struct pubkey *next_per_commitment_point)
{
if (channel->remote_channel_ready) {
channel_internal_error(channel,
"channel_got_channel_ready twice");
return false;
}
update_per_commit_point(channel, next_per_commitment_point);
log_debug(channel->log, "Got channel_ready");
channel->remote_channel_ready = true;
return true;
}
/* We were informed by channeld that channel is ready (reached mindepth) */
static void peer_got_channel_ready(struct channel *channel, const u8 *msg)
{
struct pubkey next_per_commitment_point;
struct short_channel_id *alias_remote;
if (!fromwire_channeld_got_channel_ready(tmpctx,
msg, &next_per_commitment_point, &alias_remote)) {
channel_internal_error(channel,
"bad channel_got_channel_ready %s",
tal_hex(channel, msg));
return;
}
if (!channel_on_channel_ready(channel, &next_per_commitment_point))
return;
if (channel->alias[REMOTE] == NULL)
channel->alias[REMOTE] = tal_steal(channel, alias_remote);
/* Remember that we got the lockin */
wallet_channel_save(channel->peer->ld->wallet, channel);
if (channel->depth >= channel->minimum_depth)
lockin_complete(channel);
}
static void peer_got_announcement(struct channel *channel, const u8 *msg)
{
secp256k1_ecdsa_signature remote_ann_node_sig;
secp256k1_ecdsa_signature remote_ann_bitcoin_sig;
if (!fromwire_channeld_got_announcement(msg,
&remote_ann_node_sig,
&remote_ann_bitcoin_sig)) {
channel_internal_error(channel,
"bad channel_got_announcement %s",
tal_hex(tmpctx, msg));
return;
}
wallet_announcement_save(channel->peer->ld->wallet, channel->dbid,
&remote_ann_node_sig,
&remote_ann_bitcoin_sig);
}
static void peer_got_shutdown(struct channel *channel, const u8 *msg)
{
u8 *scriptpubkey;
struct lightningd *ld = channel->peer->ld;
struct bitcoin_outpoint *wrong_funding;
bool anysegwit = feature_negotiated(ld->our_features,
channel->peer->their_features,
OPT_SHUTDOWN_ANYSEGWIT);
bool anchors = feature_negotiated(ld->our_features,
channel->peer->their_features,
OPT_ANCHOR_OUTPUTS)
|| feature_negotiated(ld->our_features,
channel->peer->their_features,
OPT_ANCHORS_ZERO_FEE_HTLC_TX);
if (!fromwire_channeld_got_shutdown(channel, msg, &scriptpubkey,
&wrong_funding)) {
channel_internal_error(channel, "bad channel_got_shutdown %s",
tal_hex(msg, msg));
return;
}
/* BOLT #2:
* A receiving node:
*...
* - if the `scriptpubkey` is not in one of the above forms:
* - SHOULD send a `warning`.
*/
if (!valid_shutdown_scriptpubkey(scriptpubkey, anysegwit, anchors)) {
u8 *warning = towire_warningfmt(NULL,
&channel->cid,
"Bad shutdown scriptpubkey %s",
tal_hex(tmpctx, scriptpubkey));
/* Get connectd to send warning, and then allow reconnect. */
subd_send_msg(ld->connectd,
take(towire_connectd_peer_final_msg(NULL,
&channel->peer->id,
channel->peer->connectd_counter,
warning)));
channel_fail_transient(channel, "Bad shutdown scriptpubkey %s",
tal_hex(tmpctx, scriptpubkey));
return;
}
/* FIXME: Add to spec that we must allow repeated shutdown! */
tal_free(channel->shutdown_scriptpubkey[REMOTE]);
channel->shutdown_scriptpubkey[REMOTE] = scriptpubkey;
/* If we weren't already shutting down, we are now */
if (channel->state != CHANNELD_SHUTTING_DOWN)
channel_set_state(channel,
channel->state,
CHANNELD_SHUTTING_DOWN,
REASON_REMOTE,
"Peer closes channel");
/* If we set it, that's what we want. Otherwise use their preference.
* We can't have both, since only opener can set this! */
if (!channel->shutdown_wrong_funding)
channel->shutdown_wrong_funding = wrong_funding;
/* We now watch the "wrong" funding, in case we spend it. */
channel_watch_wrong_funding(ld, channel);
/* TODO(cdecker) Selectively save updated fields to DB */
wallet_channel_save(ld->wallet, channel);
}
void channel_fallen_behind(struct channel *channel, const u8 *msg)
{
/* per_commitment_point is NULL if option_static_remotekey, but we
* use its presence as a flag so set it any valid key in that case. */
if (!channel->future_per_commitment_point) {
struct pubkey *any = tal(channel, struct pubkey);
if (!pubkey_from_node_id(any, &channel->peer->ld->id))
fatal("Our own id invalid?");
channel->future_per_commitment_point = any;
}
/* Peer sees this, so send a generic msg about unilateral close. */
channel_fail_permanent(channel,
REASON_LOCAL,
"Awaiting unilateral close");
}
static void
channel_fail_fallen_behind(struct channel *channel, const u8 *msg)
{
if (!fromwire_channeld_fail_fallen_behind(channel, msg,
cast_const2(struct pubkey **,
&channel->future_per_commitment_point))) {
channel_internal_error(channel,
"bad channel_fail_fallen_behind %s",
tal_hex(tmpctx, msg));
return;
}
channel_fallen_behind(channel, msg);
}
static void peer_start_closingd_after_shutdown(struct channel *channel,
const u8 *msg,
const int *fds)
{
struct peer_fd *peer_fd;
if (!fromwire_channeld_shutdown_complete(msg)) {
channel_internal_error(channel, "bad shutdown_complete: %s",
tal_hex(msg, msg));
return;
}
peer_fd = new_peer_fd_arr(msg, fds);
/* This sets channel->owner, closes down channeld. */
peer_start_closingd(channel, peer_fd);
/* We might have reconnected, so already be here. */
if (!channel_closed(channel)
&& channel->state != CLOSINGD_SIGEXCHANGE)
channel_set_state(channel,
CHANNELD_SHUTTING_DOWN,
CLOSINGD_SIGEXCHANGE,
REASON_UNKNOWN,
"Start closingd");
}
static void forget(struct channel *channel)
{
struct command **forgets = tal_steal(tmpctx, channel->forgets);
channel->forgets = tal_arr(channel, struct command *, 0);
/* Forget the channel. */
delete_channel(channel);
for (size_t i = 0; i < tal_count(forgets); i++) {
assert(!forgets[i]->json_stream);
struct json_stream *response;
response = json_stream_success(forgets[i]);
json_add_string(response, "cancelled",
"Channel open canceled by RPC(after"
" fundchannel_complete)");
was_pending(command_success(forgets[i], response));
}
tal_free(forgets);
}
static void handle_error_channel(struct channel *channel,
const u8 *msg)
{
if (!fromwire_channeld_send_error_reply(msg)) {
channel_internal_error(channel, "bad send_error_reply: %s",
tal_hex(tmpctx, msg));
return;
}
forget(channel);
}
static void handle_local_private_channel(struct channel *channel, const u8 *msg)
{
struct amount_sat capacity;
u8 *features;
if (!fromwire_channeld_local_private_channel(msg, msg, &capacity,
&features)) {
channel_internal_error(channel,
"bad channeld_local_private_channel %s",
tal_hex(channel, msg));
return;
}
tell_gossipd_local_private_channel(channel->peer->ld, channel,
capacity, features);
}
static void forget_channel(struct channel *channel, const char *why)
{
channel->error = towire_errorfmt(channel, &channel->cid, "%s", why);
/* If the peer is connected, we let them know. Otherwise
* we just directly remove the channel */
if (channel->owner)
subd_send_msg(channel->owner,
take(towire_channeld_send_error(NULL, why)));
else
forget(channel);
}
#if EXPERIMENTAL_FEATURES
static void handle_channel_upgrade(struct channel *channel,
const u8 *msg)
{
struct channel_type *newtype;
if (!fromwire_channeld_upgraded(msg, msg, &newtype)) {
channel_internal_error(channel, "bad handle_channel_upgrade: %s",
tal_hex(tmpctx, msg));
return;
}
/* You can currently only upgrade to turn on option_static_remotekey:
* if they somehow thought anything else we need to close channel! */
if (channel->static_remotekey_start[LOCAL] != 0x7FFFFFFFFFFFFFFFULL) {
channel_internal_error(channel,
"channel_upgrade already static_remotekey? %s",
tal_hex(tmpctx, msg));
return;
}
if (!channel_type_eq(newtype, channel_type_static_remotekey(tmpctx))) {
channel_internal_error(channel,
"channel_upgrade must be static_remotekey, not %s",
fmt_featurebits(tmpctx, newtype->features));
return;
}
tal_free(channel->type);
channel->type = channel_type_dup(channel, newtype);
channel->static_remotekey_start[LOCAL] = channel->next_index[LOCAL];
channel->static_remotekey_start[REMOTE] = channel->next_index[REMOTE];
log_debug(channel->log,
"option_static_remotekey enabled at %"PRIu64"/%"PRIu64,
channel->static_remotekey_start[LOCAL],
channel->static_remotekey_start[REMOTE]);
wallet_channel_save(channel->peer->ld->wallet, channel);
}
#endif /* EXPERIMENTAL_FEATURES */
static unsigned channel_msg(struct subd *sd, const u8 *msg, const int *fds)
{
enum channeld_wire t = fromwire_peektype(msg);
switch (t) {
case WIRE_CHANNELD_SENDING_COMMITSIG:
peer_sending_commitsig(sd->channel, msg);
break;
case WIRE_CHANNELD_GOT_COMMITSIG:
peer_got_commitsig(sd->channel, msg);
break;
case WIRE_CHANNELD_GOT_REVOKE:
peer_got_revoke(sd->channel, msg);
break;
case WIRE_CHANNELD_GOT_CHANNEL_READY:
peer_got_channel_ready(sd->channel, msg);
break;
case WIRE_CHANNELD_GOT_ANNOUNCEMENT:
peer_got_announcement(sd->channel, msg);
break;
case WIRE_CHANNELD_GOT_SHUTDOWN:
peer_got_shutdown(sd->channel, msg);
break;
case WIRE_CHANNELD_SHUTDOWN_COMPLETE:
/* We expect 1 fd. */
if (!fds)
return 1;
peer_start_closingd_after_shutdown(sd->channel, msg, fds);
break;
case WIRE_CHANNELD_FAIL_FALLEN_BEHIND:
channel_fail_fallen_behind(sd->channel, msg);
break;
case WIRE_CHANNELD_SEND_ERROR_REPLY:
handle_error_channel(sd->channel, msg);
break;
case WIRE_CHANNELD_USED_CHANNEL_UPDATE:
/* This tells gossipd we used it. */
get_channel_update(sd->channel);
break;
case WIRE_CHANNELD_LOCAL_CHANNEL_UPDATE:
tell_gossipd_local_channel_update(sd->ld, sd->channel, msg);
break;
case WIRE_CHANNELD_LOCAL_CHANNEL_ANNOUNCEMENT:
tell_gossipd_local_channel_announce(sd->ld, sd->channel, msg);
break;
case WIRE_CHANNELD_LOCAL_PRIVATE_CHANNEL:
handle_local_private_channel(sd->channel, msg);
break;
#if EXPERIMENTAL_FEATURES
case WIRE_CHANNELD_UPGRADED:
handle_channel_upgrade(sd->channel, msg);
break;
#else
case WIRE_CHANNELD_UPGRADED:
#endif
/* And we never get these from channeld. */
case WIRE_CHANNELD_INIT:
case WIRE_CHANNELD_FUNDING_DEPTH:
case WIRE_CHANNELD_OFFER_HTLC:
case WIRE_CHANNELD_FULFILL_HTLC:
case WIRE_CHANNELD_FAIL_HTLC:
case WIRE_CHANNELD_GOT_COMMITSIG_REPLY:
case WIRE_CHANNELD_GOT_REVOKE_REPLY:
case WIRE_CHANNELD_SENDING_COMMITSIG_REPLY:
case WIRE_CHANNELD_SEND_SHUTDOWN:
case WIRE_CHANNELD_DEV_REENABLE_COMMIT:
case WIRE_CHANNELD_FEERATES:
case WIRE_CHANNELD_BLOCKHEIGHT:
case WIRE_CHANNELD_CONFIG_CHANNEL:
case WIRE_CHANNELD_CHANNEL_UPDATE:
case WIRE_CHANNELD_DEV_MEMLEAK:
case WIRE_CHANNELD_DEV_QUIESCE:
/* Replies go to requests. */
case WIRE_CHANNELD_OFFER_HTLC_REPLY:
case WIRE_CHANNELD_DEV_REENABLE_COMMIT_REPLY:
case WIRE_CHANNELD_DEV_MEMLEAK_REPLY:
case WIRE_CHANNELD_SEND_ERROR:
case WIRE_CHANNELD_DEV_QUIESCE_REPLY:
break;
}
return 0;
}
bool peer_start_channeld(struct channel *channel,
struct peer_fd *peer_fd,
const u8 *fwd_msg,
bool reconnected,
bool reestablish_only)
{
u8 *initmsg;
int hsmfd;
const struct existing_htlc **htlcs;
struct short_channel_id scid;
u64 num_revocations;
struct lightningd *ld = channel->peer->ld;
const struct config *cfg = &ld->config;
bool reached_announce_depth;
struct secret last_remote_per_commit_secret;
secp256k1_ecdsa_signature *remote_ann_node_sig, *remote_ann_bitcoin_sig;
struct penalty_base *pbases;
hsmfd = hsm_get_client_fd(ld, &channel->peer->id,
channel->dbid,
HSM_CAP_SIGN_GOSSIP
| HSM_CAP_ECDH
| HSM_CAP_COMMITMENT_POINT
| HSM_CAP_SIGN_REMOTE_TX
| HSM_CAP_SIGN_ONCHAIN_TX);
channel_set_owner(channel,
new_channel_subd(channel, ld,
"lightning_channeld",
channel,
&channel->peer->id,
channel->log, true,
channeld_wire_name,
channel_msg,
channel_errmsg,
channel_set_billboard,
take(&peer_fd->fd),
take(&hsmfd), NULL));
if (!channel->owner) {
log_broken(channel->log, "Could not subdaemon channel: %s",
strerror(errno));
/* Disconnect it. */
subd_send_msg(ld->connectd,
take(towire_connectd_discard_peer(NULL, &channel->peer->id,
channel->peer->connectd_counter)));
return false;
}
htlcs = peer_htlcs(tmpctx, channel);
if (channel->scid) {
scid = *channel->scid;
reached_announce_depth
= is_scid_depth_announceable(&scid,
get_block_height(ld->topology));
log_debug(channel->log, "Already have funding locked in%s",
reached_announce_depth
? " (and ready to announce)" : "");
} else {
log_debug(channel->log, "Waiting for funding confirmations");
memset(&scid, 0, sizeof(scid));
reached_announce_depth = false;
}
num_revocations = revocations_received(&channel->their_shachain.chain);
/* BOLT #2:
* - if `next_revocation_number` equals 0:
* - MUST set `your_last_per_commitment_secret` to all zeroes
* - otherwise:
* - MUST set `your_last_per_commitment_secret` to the last
* `per_commitment_secret` it received
*/
if (num_revocations == 0)
memset(&last_remote_per_commit_secret, 0,
sizeof(last_remote_per_commit_secret));
else if (!shachain_get_secret(&channel->their_shachain.chain,
num_revocations-1,
&last_remote_per_commit_secret)) {
channel_fail_permanent(channel,
REASON_LOCAL,
"Could not get revocation secret %"PRIu64,
num_revocations-1);
return false;
}
/* Warn once. */
if (ld->config.ignore_fee_limits)
log_debug(channel->log, "Ignoring fee limits!");
if (!wallet_remote_ann_sigs_load(tmpctx, channel->peer->ld->wallet,
channel->dbid,
&remote_ann_node_sig,
&remote_ann_bitcoin_sig)) {
channel_internal_error(channel,
"Could not load remote announcement"
" signatures");
return false;
}
pbases = wallet_penalty_base_load_for_channel(
tmpctx, channel->peer->ld->wallet, channel->dbid);
struct ext_key final_ext_key;
if (bip32_key_from_parent(
ld->wallet->bip32_base,
channel->final_key_idx,
BIP32_FLAG_KEY_PUBLIC,
&final_ext_key) != WALLY_OK) {
channel_internal_error(channel,
"Could not derive final_ext_key %"PRIu64,
channel->final_key_idx);
return false;
}
initmsg = towire_channeld_init(tmpctx,
chainparams,
ld->our_features,
&channel->cid,
&channel->funding,
channel->funding_sats,
channel->minimum_depth,
get_block_height(ld->topology),
channel->blockheight_states,
channel->lease_expiry,
&channel->our_config,
&channel->channel_info.their_config,
channel->fee_states,
feerate_min(ld, NULL),
feerate_max(ld, NULL),
try_get_feerate(ld->topology, FEERATE_PENALTY),
&channel->last_sig,
&channel->channel_info.remote_fundingkey,
&channel->channel_info.theirbase,
&channel->channel_info.remote_per_commit,
&channel->channel_info.old_remote_per_commit,
channel->opener,
channel->feerate_base,
channel->feerate_ppm,
channel->htlc_minimum_msat,
channel->htlc_maximum_msat,
channel->our_msat,
&channel->local_basepoints,
&channel->local_funding_pubkey,
&ld->id,
&channel->peer->id,
cfg->commit_time_ms,
cfg->cltv_expiry_delta,
channel->last_was_revoke,
channel->last_sent_commit,
channel->next_index[LOCAL],
channel->next_index[REMOTE],
num_revocations,
channel->next_htlc_id,
htlcs,
channel->scid != NULL,
channel->remote_channel_ready,
&scid,
reconnected,
/* Anything that indicates we are or have
* shut down */
channel->state == CHANNELD_SHUTTING_DOWN
|| channel->state == CLOSINGD_SIGEXCHANGE
|| channel_closed(channel),
channel->shutdown_scriptpubkey[REMOTE] != NULL,
channel->final_key_idx,
&final_ext_key,
channel->shutdown_scriptpubkey[LOCAL],
channel->channel_flags,
fwd_msg,
reached_announce_depth,
&last_remote_per_commit_secret,
channel->peer->their_features,
channel->remote_upfront_shutdown_script,
remote_ann_node_sig,
remote_ann_bitcoin_sig,
channel->type,
IFDEV(ld->dev_fast_gossip, false),
IFDEV(ld->dev_disable_commit == -1
? NULL
: (u32 *)&ld->dev_disable_commit,
NULL),
pbases,
reestablish_only,
channel->channel_update);
/* We don't expect a response: we are triggered by funding_depth_cb. */
subd_send_msg(channel->owner, take(initmsg));
/* On restart, feerate and blockheight
* might not be what we expect: adjust now. */
if (channel->opener == LOCAL) {
try_update_feerates(ld, channel);
try_update_blockheight(ld, channel,
get_block_height(ld->topology));
}
/* Artificial confirmation event for zeroconf */
subd_send_msg(channel->owner,
take(towire_channeld_funding_depth(
NULL, channel->scid, channel->alias[LOCAL], 0)));
return true;
}
bool channel_tell_depth(struct lightningd *ld,
struct channel *channel,
const struct bitcoin_txid *txid,
u32 depth)
{
const char *txidstr;
txidstr = type_to_string(tmpctx, struct bitcoin_txid, txid);
channel->depth = depth;
if (!channel->owner) {
log_debug(channel->log,
"Funding tx %s confirmed, but peer disconnected",
txidstr);
return false;
}
if (streq(channel->owner->name, "dualopend")) {
if (channel->state != DUALOPEND_AWAITING_LOCKIN) {
log_debug(channel->log,
"Funding tx %s confirmed, but peer in"
" state %s",
txidstr, channel_state_name(channel));
return true;
}
log_debug(channel->log,
"Funding tx %s confirmed, telling peer", txidstr);
dualopen_tell_depth(channel->owner, channel,
txid, depth);
return true;
} else if (channel->state != CHANNELD_AWAITING_LOCKIN
&& channel->state != CHANNELD_NORMAL) {
/* If not awaiting lockin/announce, it doesn't
* care any more */
log_debug(channel->log,
"Funding tx %s confirmed, but peer in state %s",
txidstr, channel_state_name(channel));
return true;
}
subd_send_msg(channel->owner,
take(towire_channeld_funding_depth(
NULL, channel->scid, channel->alias[LOCAL], depth)));
if (channel->remote_channel_ready &&
channel->state == CHANNELD_AWAITING_LOCKIN &&
depth >= channel->minimum_depth) {
lockin_complete(channel);
} else if (depth == 1 && channel->minimum_depth == 0) {
/* If we have a zeroconf channel, i.e., no scid yet
* but have exchange `channel_ready` messages, then we
* need to fire a second time, in order to trigger the
* `coin_movement` event. This is a subset of the
* `lockin_complete` function below. */
assert(channel->scid != NULL);
/* Fees might have changed (and we use IMMEDIATE once we're
* funded), so update now. */
try_update_feerates(channel->peer->ld, channel);
try_update_blockheight(
channel->peer->ld, channel,
get_block_height(channel->peer->ld->topology));
/* Emit channel_open event */
channel_record_open(channel,
short_channel_id_blocknum(channel->scid),
false);
}
return true;
}
/* Check if we are the fundee of this channel, the channel
* funding transaction is still not yet seen onchain, and
* it has been too long since the channel was first opened.
* If so, we should forget the channel. */
static bool
is_fundee_should_forget(struct lightningd *ld,
struct channel *channel,
u32 block_height)
{
/* BOLT #2:
*
* A non-funding node (fundee):
* - SHOULD forget the channel if it does not see the
* correct funding transaction after a timeout of 2016 blocks.
*/
u32 max_funding_unconfirmed = IFDEV(ld->dev_max_funding_unconfirmed, 2016);
/* Only applies if we are fundee. */
if (channel->opener == LOCAL)
return false;
/* Does not apply if we already saw the funding tx. */
if (channel->scid)
return false;
/* Not even reached previous starting blocknum.
* (e.g. if --rescan option is used) */
if (block_height < channel->first_blocknum)
return false;
/* Timeout in blocks not yet reached. */
if (block_height - channel->first_blocknum < max_funding_unconfirmed)
return false;
/* If we've got funds in the channel, don't forget it */
if (!amount_sat_zero(channel->our_funds))
return false;
/* Ah forget it! */
return true;
}
/* Notify all channels of new blocks. */
void channel_notify_new_block(struct lightningd *ld,
u32 block_height)
{
struct peer *peer;
struct channel *channel;
struct channel **to_forget = tal_arr(NULL, struct channel *, 0);
size_t i;
list_for_each (&ld->peers, peer, list) {
list_for_each (&peer->channels, channel, list) {
if (channel_unsaved(channel))
continue;
if (is_fundee_should_forget(ld, channel, block_height)) {
tal_arr_expand(&to_forget, channel);
} else
/* Let channels know about new blocks,
* required for lease updates */
try_update_blockheight(ld, channel,
block_height);
}
}
/* Need to forget in a separate loop, else the above
* nested loops may crash due to the last channel of
* a peer also deleting the peer, making the inner
* loop crash.
* list_for_each_safe does not work because it is not
* just the freeing of the channel that occurs, but the
* potential destruction of the peer that invalidates
* memory the inner loop is accessing. */
for (i = 0; i < tal_count(to_forget); ++i) {
channel = to_forget[i];
/* Report it first. */
log_unusual(channel->log,
"Forgetting channel: "
"It has been %"PRIu32" blocks without the "
"funding transaction %s getting deeply "
"confirmed. "
"We are fundee and can forget channel without "
"loss of funds.",
block_height - channel->first_blocknum,
type_to_string(tmpctx, struct bitcoin_txid,
&channel->funding.txid));
/* FIXME: Send an error packet for this case! */
/* And forget it. */
delete_channel(channel);
}
tal_free(to_forget);
}
/* Since this could vanish while we're checking with bitcoind, we need to save
* the details and re-lookup.
*
* channel_id *should* be unique, but it can be set by the counterparty, so
* we cannot rely on that! */
struct channel_to_cancel {
struct node_id peer;
struct channel_id cid;
};
static void process_check_funding_broadcast(struct bitcoind *bitcoind,
const struct bitcoin_tx_output *txout,
void *arg)
{
struct channel_to_cancel *cc = arg;
struct peer *peer;
struct channel *cancel;
/* Peer could have errored out while we were waiting */
peer = peer_by_id(bitcoind->ld, &cc->peer);
if (!peer)
goto cleanup;