-
Notifications
You must be signed in to change notification settings - Fork 913
/
Copy pathchanneld.c
6337 lines (5484 loc) · 197 KB
/
channeld.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
/* Main channel operation daemon: runs from channel_ready to shutdown_complete.
*
* We're fairly synchronous: our main loop looks for master or
* peer requests and services them synchronously.
*
* The exceptions are:
* 1. When we've asked the master something: in that case, we queue
* non-response packets for later processing while we await the reply.
* 2. We queue and send non-blocking responses to peers: if both peers were
* reading and writing synchronously we could deadlock if we hit buffer
* limits, unlikely as that is.
*/
#include "config.h"
#include <bitcoin/script.h>
#include <ccan/asort/asort.h>
#include <ccan/cast/cast.h>
#include <ccan/mem/mem.h>
#include <ccan/tal/str/str.h>
#include <channeld/channeld.h>
#include <channeld/channeld_wiregen.h>
#include <channeld/full_channel.h>
#include <channeld/inflight.h>
#include <channeld/splice.h>
#include <channeld/watchtower.h>
#include <common/billboard.h>
#include <common/ecdh_hsmd.h>
#include <common/gossip_store.h>
#include <common/hsm_capable.h>
#include <common/hsm_version.h>
#include <common/interactivetx.h>
#include <common/key_derive.h>
#include <common/memleak.h>
#include <common/msg_queue.h>
#include <common/onionreply.h>
#include <common/peer_billboard.h>
#include <common/peer_failed.h>
#include <common/peer_io.h>
#include <common/per_peer_state.h>
#include <common/psbt_internal.h>
#include <common/psbt_open.h>
#include <common/read_peer_msg.h>
#include <common/status.h>
#include <common/subdaemon.h>
#include <common/timeout.h>
#include <common/wire_error.h>
#include <errno.h>
#include <fcntl.h>
#include <hsmd/hsmd_wiregen.h>
#include <stdio.h>
#include <wally_bip32.h>
#include <wire/peer_wire.h>
#include <wire/wire_sync.h>
/* stdin == requests, 3 == peer, 4 = HSM */
#define MASTER_FD STDIN_FILENO
#define HSM_FD 4
#define VALID_STFU_MESSAGE(msg) \
((msg) == WIRE_SPLICE || \
(msg) == WIRE_SPLICE_ACK || \
(msg) == WIRE_TX_ABORT)
#define SAT_MIN(a, b) (amount_sat_less((a), (b)) ? (a) : (b))
struct peer {
struct per_peer_state *pps;
bool channel_ready[NUM_SIDES];
u64 next_index[NUM_SIDES];
/* --developer? */
bool developer;
/* Features peer supports. */
u8 *their_features;
/* Features we support. */
struct feature_set *our_features;
/* What (additional) messages the HSM accepts */
u32 *hsm_capabilities;
/* Tolerable amounts for feerate (only relevant for fundee). */
u32 feerate_min, feerate_max;
/* Feerate to be used when creating penalty transactions. */
u32 feerate_penalty;
/* Local next per-commit point. */
struct pubkey next_local_per_commit;
/* Remote's current per-commit point. */
struct pubkey remote_per_commit;
/* Remotes's last per-commitment point: we keep this to check
* revoke_and_ack's `per_commitment_secret` is correct and for
* splices. */
struct pubkey old_remote_per_commit;
/* Their sig for current commit. */
struct bitcoin_signature their_commit_sig;
/* BOLT #2:
*
* A sending node:
*...
* - for the first HTLC it offers:
* - MUST set `id` to 0.
*/
u64 htlc_id;
struct channel_id channel_id;
struct channel *channel;
/* Messages from master: we queue them since we might be
* waiting for a specific reply. */
struct msg_queue *from_master;
struct timers timers;
struct oneshot *commit_timer;
u32 commit_msec;
/* The feerate we want. */
u32 desired_feerate;
/* Current blockheight */
u32 our_blockheight;
/* FIXME: Remove this. */
struct short_channel_id short_channel_ids[NUM_SIDES];
/* Local scid alias */
struct short_channel_id local_alias;
/* The scriptpubkey to use for shutting down. */
u32 *final_index;
struct ext_key *final_ext_key;
u8 *final_scriptpubkey;
/* If master told us to shut down */
bool send_shutdown;
/* Has shutdown been sent by each side? */
bool shutdown_sent[NUM_SIDES];
/* If master told us to send wrong_funding */
struct bitcoin_outpoint *shutdown_wrong_funding;
/* Do we want quiescence?
* Note: This flag is needed seperately from `stfu_sent` so we can
* detect the entering "stfu" mode. */
bool want_stfu;
/* Which side is considered the initiator? */
enum side stfu_initiator;
/* Has stfu been sent by each side? */
bool stfu_sent[NUM_SIDES];
/* After STFU mode is enabled, wait for a single message flag */
bool stfu_wait_single_msg;
/* Updates master asked, which we've deferred while quiescing */
struct msg_queue *update_queue;
/* Callback for when when stfu is negotiated successfully */
void (*on_stfu_success)(struct peer*);
struct splice_state *splice_state;
struct splicing *splicing;
/* If set, don't fire commit counter when this hits 0 */
u32 *dev_disable_commit;
/* Information used for reestablishment. */
bool last_was_revoke;
struct changed_htlc *last_sent_commit;
u64 revocations_received;
u8 channel_flags;
/* Make sure timestamps move forward. */
u32 last_update_timestamp;
/* Additional confirmations need for local lockin. */
u32 depth_togo;
/* Non-empty if they specified a fixed shutdown script */
u8 *remote_upfront_shutdown_script;
/* Empty commitments. Spec violation, but a minor one. */
u64 last_empty_commitment;
/* Penalty bases for this channel / peer. */
struct penalty_base **pbases;
/* We allow a 'tx-sigs' message between reconnect + channel_ready */
bool tx_sigs_allowed;
/* --experimental-upgrade-protocol */
bool experimental_upgrade;
};
static void start_commit_timer(struct peer *peer);
static void billboard_update(const struct peer *peer)
{
const char *update = billboard_message(tmpctx, peer->channel_ready,
NULL,
peer->shutdown_sent,
peer->depth_togo,
num_channel_htlcs(peer->channel));
peer_billboard(false, update);
}
const u8 *hsm_req(const tal_t *ctx, const u8 *req TAKES)
{
u8 *msg;
/* hsmd goes away at shutdown. That's OK. */
if (!wire_sync_write(HSM_FD, req))
exit(0);
msg = wire_sync_read(ctx, HSM_FD);
if (!msg)
exit(0);
return msg;
}
static bool is_stfu_active(const struct peer *peer)
{
return peer->stfu_sent[LOCAL] && peer->stfu_sent[REMOTE];
}
static void end_stfu_mode(struct peer *peer)
{
peer->want_stfu = false;
peer->stfu_sent[LOCAL] = peer->stfu_sent[REMOTE] = false;
peer->stfu_wait_single_msg = false;
peer->on_stfu_success = NULL;
status_debug("Left STFU mode.");
}
static bool maybe_send_stfu(struct peer *peer)
{
if (!peer->want_stfu)
return false;
if (pending_updates(peer->channel, LOCAL, false)) {
status_info("Pending updates prevent us from STFU mode at this"
" time.");
return false;
}
else if (!peer->stfu_sent[LOCAL]) {
status_debug("Sending peer that we want to STFU.");
u8 *msg = towire_stfu(NULL, &peer->channel_id,
peer->stfu_initiator == LOCAL);
peer_write(peer->pps, take(msg));
peer->stfu_sent[LOCAL] = true;
}
if (peer->stfu_sent[LOCAL] && peer->stfu_sent[REMOTE]) {
/* Prevent STFU mode being inadvertantly activated twice during
* splice. This occurs because the commit -> revoke_and_ack
* cycle calls into `maybe_send_stfu`. The `want_stfu` flag is
* to prevent triggering the entering of stfu events twice. */
peer->want_stfu = false;
status_unusual("STFU complete: we are quiescent");
wire_sync_write(MASTER_FD,
towire_channeld_dev_quiesce_reply(tmpctx));
peer->stfu_wait_single_msg = true;
status_unusual("STFU complete: setting stfu_wait_single_msg = true");
if (peer->on_stfu_success) {
peer->on_stfu_success(peer);
peer->on_stfu_success = NULL;
}
}
return true;
}
/* Durring reestablish, STFU mode is assumed if continuing a splice */
static void assume_stfu_mode(struct peer *peer)
{
peer->stfu_sent[LOCAL] = peer->stfu_sent[REMOTE] = true;
}
static void handle_stfu(struct peer *peer, const u8 *stfu)
{
struct channel_id channel_id;
u8 remote_initiated;
if (!feature_negotiated(peer->our_features,
peer->their_features,
OPT_QUIESCE))
peer_failed_warn(peer->pps, &peer->channel_id,
"stfu not supported");
if (!fromwire_stfu(stfu, &channel_id, &remote_initiated))
peer_failed_warn(peer->pps, &peer->channel_id,
"Bad stfu %s", tal_hex(peer, stfu));
if (!channel_id_eq(&channel_id, &peer->channel_id)) {
peer_failed_err(peer->pps, &channel_id,
"Wrong stfu channel_id: expected %s, got %s",
fmt_channel_id(tmpctx, &peer->channel_id),
fmt_channel_id(tmpctx, &channel_id));
}
/* Sanity check */
if (pending_updates(peer->channel, REMOTE, false))
peer_failed_warn(peer->pps, &peer->channel_id,
"STFU but you still have updates pending?");
if (!peer->want_stfu) {
peer->want_stfu = true;
if (!remote_initiated)
peer_failed_warn(peer->pps, &peer->channel_id,
"Unsolicited STFU but you said"
" you didn't initiate?");
peer->stfu_initiator = REMOTE;
status_debug("STFU initiator was remote.");
} else {
/* BOLT #2:
*
* If both sides send `stfu` simultaneously, they will both
* set `initiator` to `1`, in which case the "initiator" is
* arbitrarily considered to be the channel funder (the sender
* of `open_channel`).
*/
if (remote_initiated) {
status_debug("Dual STFU intiation tiebreaker. Setting initiator to %s",
peer->channel->opener == LOCAL ? "LOCAL" : "REMOTE");
peer->stfu_initiator = peer->channel->opener;
} else {
status_debug("STFU initiator local.");
}
}
/* BOLT #2:
* The receiver of `stfu`:
* - if it has sent `stfu` then:
* - MUST now consider the channel to be quiescent
* - otherwise:
* - SHOULD NOT send any more update messages.
* - MUST reply with `stfu` once it can do so.
*/
peer->stfu_sent[REMOTE] = true;
maybe_send_stfu(peer);
}
/* Returns true if we queued this for later handling (steals if true) */
static bool handle_master_request_later(struct peer *peer, const u8 *msg)
{
if (is_stfu_active(peer)) {
msg_enqueue(peer->update_queue, take(msg));
return true;
}
return false;
}
/* Compare, with false if either is NULL */
static bool match_type(const u8 *t1, const u8 *t2)
{
/* Missing fields are possible. */
if (!t1 || !t2)
return false;
return featurebits_eq(t1, t2);
}
static void set_channel_type(struct channel *channel, const u8 *type)
{
const struct channel_type *cur = channel->type;
if (featurebits_eq(cur->features, type))
return;
/* We only allow one upgrade at the moment, so that's it. */
assert(!channel_has(channel, OPT_STATIC_REMOTEKEY));
assert(feature_offered(type, OPT_STATIC_REMOTEKEY));
/* Do upgrade, tell master. */
tal_free(channel->type);
channel->type = channel_type_from(channel, type);
status_unusual("Upgraded channel to [%s]",
fmt_featurebits(tmpctx, type));
wire_sync_write(MASTER_FD,
take(towire_channeld_upgraded(NULL, channel->type)));
}
static void lock_signer_outpoint(const struct bitcoin_outpoint *outpoint)
{
const u8 *msg;
bool is_buried = false;
/* FIXME(vincenzopalazzo): Sleeping in a deamon of cln should be never fine
* howerver the core deamon of cln will never trigger the sleep.
*
* I think that the correct solution for this is a timer base solution, but this
* required a little bit of refactoring */
do {
/* Make sure the hsmd agrees that this outpoint is
* sufficiently buried. */
msg = towire_hsmd_check_outpoint(NULL, &outpoint->txid, outpoint->n);
msg = hsm_req(tmpctx, take(msg));
if (!fromwire_hsmd_check_outpoint_reply(msg, &is_buried))
status_failed(STATUS_FAIL_HSM_IO,
"Bad hsmd_check_outpoint_reply: %s",
tal_hex(tmpctx, msg));
/* the signer should have a shorter buried height requirement so
* it almost always will be ready ahead of us.*/
if (!is_buried)
sleep(10);
} while (!is_buried);
/* tell the signer that we are now locked */
msg = towire_hsmd_lock_outpoint(NULL, &outpoint->txid, outpoint->n);
msg = hsm_req(tmpctx, take(msg));
if (!fromwire_hsmd_lock_outpoint_reply(msg))
status_failed(STATUS_FAIL_HSM_IO,
"Bad hsmd_lock_outpoint_reply: %s",
tal_hex(tmpctx, msg));
}
/* Call this method when channel_ready status are changed. */
static void check_mutual_channel_ready(const struct peer *peer)
{
if (peer->channel_ready[LOCAL] && peer->channel_ready[REMOTE])
lock_signer_outpoint(&peer->channel->funding);
}
/* Call this method when splice_locked status are changed. If both sides have
* splice_locked'ed than this function consumes the `splice_locked_ready` values
* and considers the channel funding to be switched to the splice tx. */
static void check_mutual_splice_locked(struct peer *peer)
{
u8 *msg;
const char *error;
struct inflight *inflight;
/* If both sides haven't `splice_locked` we're not ready */
if (!peer->splice_state->locked_ready[LOCAL]
|| !peer->splice_state->locked_ready[REMOTE])
return;
if (short_channel_id_eq(peer->short_channel_ids[LOCAL],
peer->splice_state->short_channel_id))
peer_failed_warn(peer->pps, &peer->channel_id,
"Duplicate splice_locked events detected");
peer->splice_state->await_commitment_succcess = true;
/* This splice_locked event is used, so reset the flags to false */
peer->splice_state->locked_ready[LOCAL] = false;
peer->splice_state->locked_ready[REMOTE] = false;
peer->splice_state->last_short_channel_id = peer->short_channel_ids[LOCAL];
peer->short_channel_ids[LOCAL] = peer->splice_state->short_channel_id;
peer->short_channel_ids[REMOTE] = peer->splice_state->short_channel_id;
peer->channel->view[LOCAL].lowest_splice_amnt[LOCAL] = 0;
peer->channel->view[LOCAL].lowest_splice_amnt[REMOTE] = 0;
peer->channel->view[REMOTE].lowest_splice_amnt[LOCAL] = 0;
peer->channel->view[REMOTE].lowest_splice_amnt[REMOTE] = 0;
status_debug("mutual splice_locked, scid LOCAL & REMOTE updated to: %s",
fmt_short_channel_id(tmpctx,
peer->splice_state->short_channel_id));
inflight = NULL;
for (size_t i = 0; i < tal_count(peer->splice_state->inflights); i++)
if (bitcoin_txid_eq(&peer->splice_state->inflights[i]->outpoint.txid,
&peer->splice_state->locked_txid))
inflight = peer->splice_state->inflights[i];
if (!inflight)
peer_failed_warn(peer->pps, &peer->channel_id,
"Unable to find inflight txid amoung %zu"
" inflights. new funding txid: %s",
tal_count(peer->splice_state->inflights),
fmt_bitcoin_txid(tmpctx,
&peer->splice_state->locked_txid));
status_debug("mutual splice_locked, updating change from: %s",
fmt_channel(tmpctx, peer->channel));
error = channel_update_funding(peer->channel, &inflight->outpoint,
inflight->amnt,
inflight->splice_amnt);
if (error)
peer_failed_warn(peer->pps, &peer->channel_id,
"Splice lock unable to update funding. %s",
error);
peer->channel->funding_pubkey[REMOTE] = inflight->remote_funding;
status_debug("mutual splice_locked, channel updated to: %s",
fmt_channel(tmpctx, peer->channel));
/* ensure the signer is locking at the same time */
lock_signer_outpoint(&inflight->outpoint);
msg = towire_channeld_got_splice_locked(NULL, inflight->amnt,
inflight->splice_amnt,
&inflight->outpoint.txid);
wire_sync_write(MASTER_FD, take(msg));
billboard_update(peer);
peer->splice_state->inflights = tal_free(peer->splice_state->inflights);
peer->splice_state->count = 0;
}
/* Our peer told us they saw our splice confirm on chain with `splice_locked`.
* If we see it to we jump into tansitioning to post-splice, otherwise we mark
* a flag and wait until we see it on chain too. */
static void handle_peer_splice_locked(struct peer *peer, const u8 *msg)
{
struct channel_id chanid;
if (!fromwire_splice_locked(msg, &chanid))
peer_failed_warn(peer->pps, &peer->channel_id,
"Bad splice_locked %s", tal_hex(msg, msg));
if (!channel_id_eq(&chanid, &peer->channel_id))
peer_failed_err(peer->pps, &chanid,
"Wrong splice lock channel id in %s "
"(expected %s)",
tal_hex(tmpctx, msg),
fmt_channel_id(msg, &peer->channel_id));
/* If we've `mutual_splice_locked` but our peer hasn't, we can ignore
* this message harmlessly */
if (!tal_count(peer->splice_state->inflights)) {
status_info("Peer sent redundant splice_locked, ignoring");
return;
}
peer->splice_state->locked_ready[REMOTE] = true;
check_mutual_splice_locked(peer);
}
static void handle_peer_channel_ready(struct peer *peer, const u8 *msg)
{
struct channel_id chanid;
struct tlv_channel_ready_tlvs *tlvs;
/* BOLT #2:
*
* A node:
*...
* - upon reconnection:
* - MUST ignore any redundant `channel_ready` it receives.
*/
if (peer->channel_ready[REMOTE])
return;
/* Too late, we're shutting down! */
if (peer->shutdown_sent[LOCAL])
return;
peer->old_remote_per_commit = peer->remote_per_commit;
if (!fromwire_channel_ready(msg, msg, &chanid,
&peer->remote_per_commit, &tlvs))
peer_failed_warn(peer->pps, &peer->channel_id,
"Bad channel_ready %s", tal_hex(msg, msg));
if (!channel_id_eq(&chanid, &peer->channel_id))
peer_failed_err(peer->pps, &chanid,
"Wrong channel id in %s (expected %s)",
tal_hex(tmpctx, msg),
fmt_channel_id(msg, &peer->channel_id));
peer->tx_sigs_allowed = false;
peer->channel_ready[REMOTE] = true;
check_mutual_channel_ready(peer);
if (tlvs->short_channel_id != NULL) {
status_debug(
"Peer told us that they'll use alias=%s for this channel",
fmt_short_channel_id(tmpctx, *tlvs->short_channel_id));
peer->short_channel_ids[REMOTE] = *tlvs->short_channel_id;
}
wire_sync_write(MASTER_FD,
take(towire_channeld_got_channel_ready(
NULL, &peer->remote_per_commit, tlvs->short_channel_id)));
billboard_update(peer);
}
static void handle_peer_announcement_signatures(struct peer *peer, const u8 *msg)
{
struct channel_id chanid;
struct short_channel_id remote_scid;
secp256k1_ecdsa_signature remote_node_sig, remote_bitcoin_sig;
if (!fromwire_announcement_signatures(msg,
&chanid,
&remote_scid,
&remote_node_sig,
&remote_bitcoin_sig))
peer_failed_warn(peer->pps, &peer->channel_id,
"Bad announcement_signatures %s",
tal_hex(msg, msg));
wire_sync_write(MASTER_FD,
take(towire_channeld_got_announcement(NULL,
remote_scid,
&remote_node_sig,
&remote_bitcoin_sig)));
}
static void handle_peer_add_htlc(struct peer *peer, const u8 *msg)
{
struct channel_id channel_id;
u64 id;
struct amount_msat amount;
u32 cltv_expiry;
struct sha256 payment_hash;
u8 onion_routing_packet[TOTAL_PACKET_SIZE(ROUTING_INFO_SIZE)];
enum channel_add_err add_err;
struct htlc *htlc;
struct tlv_update_add_htlc_tlvs *tlvs;
if (!fromwire_update_add_htlc(msg, msg, &channel_id, &id, &amount,
&payment_hash, &cltv_expiry,
onion_routing_packet, &tlvs)) {
peer_failed_warn(peer->pps, &peer->channel_id,
"Bad peer_add_htlc %s", tal_hex(msg, msg));
}
add_err = channel_add_htlc(peer->channel, REMOTE, id, amount,
cltv_expiry, &payment_hash,
onion_routing_packet, tlvs->blinded_path, &htlc, NULL,
/* We don't immediately fail incoming htlcs,
* instead we wait and fail them after
* they've been committed */
false);
if (add_err != CHANNEL_ERR_ADD_OK)
peer_failed_warn(peer->pps, &peer->channel_id,
"Bad peer_add_htlc: %s",
channel_add_err_name(add_err));
}
/* We don't get upset if they're outside the range, as long as they're
* improving (or at least, not getting worse!). */
static bool feerate_same_or_better(const struct channel *channel,
u32 feerate, u32 feerate_min, u32 feerate_max)
{
u32 current = channel_feerate(channel, LOCAL);
/* Too low? But is it going upwards? */
if (feerate < feerate_min)
return feerate >= current;
if (feerate > feerate_max)
return feerate <= current;
return true;
}
static void handle_peer_feechange(struct peer *peer, const u8 *msg)
{
struct channel_id channel_id;
u32 feerate;
if (!fromwire_update_fee(msg, &channel_id, &feerate)) {
peer_failed_warn(peer->pps, &peer->channel_id,
"Bad update_fee %s", tal_hex(msg, msg));
}
/* BOLT #2:
*
* A receiving node:
*...
* - if the sender is not responsible for paying the Bitcoin fee:
* - MUST send a `warning` and close the connection, or send an
* `error` and fail the channel.
*/
if (peer->channel->opener != REMOTE)
peer_failed_warn(peer->pps, &peer->channel_id,
"update_fee from non-opener?");
status_debug("update_fee %u, range %u-%u",
feerate, peer->feerate_min, peer->feerate_max);
/* BOLT #2:
*
* A receiving node:
* - if the `update_fee` is too low for timely processing, OR is
* unreasonably large:
* - MUST send a `warning` and close the connection, or send an
* `error` and fail the channel.
*/
if (!feerate_same_or_better(peer->channel, feerate,
peer->feerate_min, peer->feerate_max))
peer_failed_warn(peer->pps, &peer->channel_id,
"update_fee %u outside range %u-%u"
" (currently %u)",
feerate,
peer->feerate_min, peer->feerate_max,
channel_feerate(peer->channel, LOCAL));
/* BOLT #2:
*
* - if the sender cannot afford the new fee rate on the receiving
* node's current commitment transaction:
* - SHOULD send a `warning` and close the connection, or send an
* `error` and fail the channel.
* - but MAY delay this check until the `update_fee` is committed.
*/
if (!channel_update_feerate(peer->channel, feerate))
peer_failed_warn(peer->pps, &peer->channel_id,
"update_fee %u unaffordable",
feerate);
status_debug("peer updated fee to %u", feerate);
}
static void handle_peer_blockheight_change(struct peer *peer, const u8 *msg)
{
struct channel_id channel_id;
u32 blockheight, current;
if (!fromwire_update_blockheight(msg, &channel_id, &blockheight))
peer_failed_warn(peer->pps, &peer->channel_id,
"Bad update_blockheight %s",
tal_hex(msg, msg));
/* BOLT- #2:
* A receiving node:
* ...
* - if the sender is not the initiator:
* - MUST fail the channel.
*/
if (peer->channel->opener != REMOTE)
peer_failed_warn(peer->pps, &peer->channel_id,
"update_blockheight from non-opener?");
current = get_blockheight(peer->channel->blockheight_states,
peer->channel->opener, LOCAL);
status_debug("update_blockheight %u. last update height %u,"
" our current height %u",
blockheight, current, peer->our_blockheight);
/* BOLT- #2:
* A receiving node:
* - if the `update_blockheight` is less than the last
* received `blockheight`:
* - SHOULD fail the channel.
* ...
* - if `blockheight` is more than 1008 blocks behind
* the current blockheight:
* - SHOULD fail the channel
*/
/* Overflow check */
if (blockheight + 1008 < blockheight)
peer_failed_warn(peer->pps, &peer->channel_id,
"blockheight + 1008 overflow (%u)",
blockheight);
/* If they're behind the last one they sent, we just warn and
* reconnect, as they might be catching up */
/* FIXME: track for how long they send backwards blockheight? */
if (blockheight < current)
peer_failed_warn(peer->pps, &peer->channel_id,
"update_blockheight %u older than previous %u",
blockheight, current);
/* BOLT- #2:
* A receiving node:
* ...
* - if `blockheight` is more than 1008 blocks behind
* the current blockheight:
* - SHOULD fail the channel
*/
assert(blockheight < blockheight + 1008);
if (blockheight + 1008 < peer->our_blockheight)
peer_failed_err(peer->pps, &peer->channel_id,
"update_blockheight %u outside"
" permissible range", blockheight);
channel_update_blockheight(peer->channel, blockheight);
status_debug("peer updated blockheight to %u", blockheight);
}
static struct changed_htlc *changed_htlc_arr(const tal_t *ctx,
const struct htlc **changed_htlcs)
{
struct changed_htlc *changed;
size_t i;
changed = tal_arr(ctx, struct changed_htlc, tal_count(changed_htlcs));
for (i = 0; i < tal_count(changed_htlcs); i++) {
changed[i].id = changed_htlcs[i]->id;
changed[i].newstate = changed_htlcs[i]->state;
}
return changed;
}
static u8 *sending_commitsig_msg(const tal_t *ctx,
u64 remote_commit_index,
struct penalty_base *pbase,
const struct fee_states *fee_states,
const struct height_states *blockheight_states,
const struct htlc **changed_htlcs)
{
struct changed_htlc *changed;
u8 *msg;
/* We tell master what (of our) HTLCs peer will now be
* committed to. */
changed = changed_htlc_arr(tmpctx, changed_htlcs);
msg = towire_channeld_sending_commitsig(ctx, remote_commit_index,
pbase, fee_states,
blockheight_states, changed);
return msg;
}
static bool shutdown_complete(const struct peer *peer)
{
return peer->shutdown_sent[LOCAL]
&& peer->shutdown_sent[REMOTE]
&& num_channel_htlcs(peer->channel) == 0
/* We could be awaiting revoke-and-ack for a feechange */
&& peer->revocations_received == peer->next_index[REMOTE] - 1;
}
/* BOLT #2:
*
* A sending node:
*...
* - if there are updates pending on the receiving node's commitment
* transaction:
* - MUST NOT send a `shutdown`.
*/
/* So we only call this after reestablish or immediately after sending commit */
static void maybe_send_shutdown(struct peer *peer)
{
u8 *msg;
struct tlv_shutdown_tlvs *tlvs;
if (!peer->send_shutdown)
return;
/* DTODO: Ensure 'shutdown' rules around splice are followed once those
* rules get settled on spec */
if (peer->shutdown_wrong_funding) {
tlvs = tlv_shutdown_tlvs_new(tmpctx);
tlvs->wrong_funding
= tal(tlvs, struct tlv_shutdown_tlvs_wrong_funding);
tlvs->wrong_funding->txid = peer->shutdown_wrong_funding->txid;
tlvs->wrong_funding->outnum = peer->shutdown_wrong_funding->n;
} else
tlvs = NULL;
msg = towire_shutdown(NULL, &peer->channel_id, peer->final_scriptpubkey,
tlvs);
peer_write(peer->pps, take(msg));
peer->send_shutdown = false;
peer->shutdown_sent[LOCAL] = true;
billboard_update(peer);
}
static void send_shutdown_complete(struct peer *peer)
{
/* Now we can tell master shutdown is complete. */
wire_sync_write(MASTER_FD,
take(towire_channeld_shutdown_complete(NULL)));
per_peer_state_fdpass_send(MASTER_FD, peer->pps);
/* Give master a chance to pass the fd along */
sleep(1);
close(MASTER_FD);
}
/* This queues other traffic from the fd until we get reply. */
static u8 *master_wait_sync_reply(const tal_t *ctx,
struct peer *peer,
const u8 *msg,
int replytype)
{
u8 *reply;
status_debug("Sending master %u", fromwire_peektype(msg));
if (!wire_sync_write(MASTER_FD, msg))
status_failed(STATUS_FAIL_INTERNAL_ERROR,
"Could not set sync write to master: %s",
strerror(errno));
status_debug("... , awaiting %u", replytype);
for (;;) {
int type;
reply = wire_sync_read(ctx, MASTER_FD);
if (!reply)
status_failed(STATUS_FAIL_MASTER_IO,
"Could not set sync read from master: %s",
strerror(errno));
type = fromwire_peektype(reply);
if (type == replytype) {
status_debug("Got it!");
break;
}
status_debug("Nope, got %u instead", type);
msg_enqueue(peer->from_master, take(reply));
}
return reply;
}
/* Collect the htlcs for call to hsmd. */
static struct simple_htlc **collect_htlcs(const tal_t *ctx, const struct htlc **htlc_map)
{
struct simple_htlc **htlcs;
htlcs = tal_arr(ctx, struct simple_htlc *, 0);
size_t num_entries = tal_count(htlc_map);
for (size_t ndx = 0; ndx < num_entries; ++ndx) {
struct htlc const *hh = htlc_map[ndx];
if (hh) {
struct simple_htlc *simple =
new_simple_htlc(htlcs,
htlc_state_owner(hh->state),
hh->amount,
&hh->rhash,
hh->expiry.locktime);
tal_arr_expand(&htlcs, simple);
}
}
return htlcs;
}
/* Returns HTLC sigs, sets commit_sig. Also used for making commitsigs for each
* splice awaiting on-chain confirmation. */
static struct bitcoin_signature *calc_commitsigs(const tal_t *ctx,
const struct peer *peer,
struct bitcoin_tx **txs,
const u8 *funding_wscript,
const struct htlc **htlc_map,
u64 commit_index,
const struct pubkey *remote_per_commit,
struct bitcoin_signature *commit_sig,
struct pubkey remote_funding_pubkey)
{
struct simple_htlc **htlcs;
size_t i;
struct pubkey local_htlckey;
const u8 *msg;
struct bitcoin_signature *htlc_sigs;
htlcs = collect_htlcs(tmpctx, htlc_map);
msg = towire_hsmd_sign_remote_commitment_tx(NULL, txs[0],
&remote_funding_pubkey,
remote_per_commit,
channel_has(peer->channel,
OPT_STATIC_REMOTEKEY),
commit_index,
(const struct simple_htlc **) htlcs,
channel_feerate(peer->channel, REMOTE));
msg = hsm_req(tmpctx, take(msg));
if (!fromwire_hsmd_sign_tx_reply(msg, commit_sig))
status_failed(STATUS_FAIL_HSM_IO,
"Reading sign_remote_commitment_tx reply: %s",
tal_hex(tmpctx, msg));
status_debug("Creating commit_sig signature %"PRIu64" %s for tx %s wscript %s key %s",
commit_index,
fmt_bitcoin_signature(tmpctx, commit_sig),
fmt_bitcoin_tx(tmpctx, txs[0]),
tal_hex(tmpctx, funding_wscript),
fmt_pubkey(tmpctx, &peer->channel->funding_pubkey[LOCAL]));
dump_htlcs(peer->channel, "Sending commit_sig");
if (!derive_simple_key(&peer->channel->basepoints[LOCAL].htlc,
remote_per_commit,
&local_htlckey))
status_failed(STATUS_FAIL_INTERNAL_ERROR,
"Deriving local_htlckey");
/* BOLT #2:
*
* A sending node:
*...
* - MUST include one `htlc_signature` for every HTLC transaction
* corresponding to the ordering of the commitment transaction
*/
htlc_sigs = tal_arr(ctx, struct bitcoin_signature, tal_count(txs) - 1);
for (i = 0; i < tal_count(htlc_sigs); i++) {
u8 *wscript;
wscript = bitcoin_tx_output_get_witscript(tmpctx, txs[0],
txs[i+1]->wtx->inputs[0].index);
msg = towire_hsmd_sign_remote_htlc_tx(NULL, txs[i + 1], wscript,
remote_per_commit,