forked from ElementsProject/lightning
-
Notifications
You must be signed in to change notification settings - Fork 0
/
openingd.c
1480 lines (1320 loc) · 47.9 KB
/
openingd.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
/*~ Welcome to the opening daemon: gateway to channels!
*
* This daemon handles a single peer. It's happy to trade gossip with the
* peer until either lightningd asks it to fund a channel, or the peer itself
* asks to fund a channel. Then it goes through with the channel opening
* negotiations. It's important to note that until this negotiation is complete,
* there's nothing permanent about the channel: lightningd will only have to
* commit to the database once openingd succeeds.
*/
#include <bitcoin/block.h>
#include <bitcoin/chainparams.h>
#include <bitcoin/privkey.h>
#include <bitcoin/psbt.h>
#include <bitcoin/script.h>
#include <ccan/array_size/array_size.h>
#include <ccan/breakpoint/breakpoint.h>
#include <ccan/cast/cast.h>
#include <ccan/fdpass/fdpass.h>
#include <ccan/mem/mem.h>
#include <ccan/tal/str/str.h>
#include <common/crypto_sync.h>
#include <common/derive_basepoints.h>
#include <common/features.h>
#include <common/fee_states.h>
#include <common/gossip_rcvd_filter.h>
#include <common/gossip_store.h>
#include <common/initial_channel.h>
#include <common/initial_commit_tx.h>
#include <common/key_derive.h>
#include <common/memleak.h>
#include <common/overflows.h>
#include <common/peer_billboard.h>
#include <common/peer_failed.h>
#include <common/peer_status_wiregen.h>
#include <common/penalty_base.h>
#include <common/read_peer_msg.h>
#include <common/shutdown_scriptpubkey.h>
#include <common/status.h>
#include <common/subdaemon.h>
#include <common/type_to_string.h>
#include <common/version.h>
#include <common/wire_error.h>
#include <errno.h>
#include <gossipd/gossipd_peerd_wiregen.h>
#include <hsmd/hsmd_wiregen.h>
#include <inttypes.h>
#include <openingd/common.h>
#include <openingd/openingd_wiregen.h>
#include <poll.h>
#include <secp256k1.h>
#include <stdio.h>
#include <wally_bip32.h>
#include <wire/common_wiregen.h>
#include <wire/peer_wire.h>
#include <wire/wire.h>
#include <wire/wire_sync.h>
/* stdin == lightningd, 3 == peer, 4 == gossipd, 5 = gossip_store, 6 = hsmd */
#define REQ_FD STDIN_FILENO
#define HSM_FD 6
#if DEVELOPER
/* If --dev-force-tmp-channel-id is set, it ends up here */
static struct channel_id *dev_force_tmp_channel_id;
#endif /* DEVELOPER */
/* Global state structure. This is only for the one specific peer and channel */
struct state {
struct per_peer_state *pps;
/* Features they offered */
u8 *their_features;
/* Constraints on a channel they open. */
u32 minimum_depth;
u32 min_feerate, max_feerate;
struct amount_msat min_effective_htlc_capacity;
/* Limits on what remote config we accept. */
u32 max_to_self_delay;
/* These are the points lightningd told us to use when accepting or
* opening a channel. */
struct basepoints our_points;
struct pubkey our_funding_pubkey;
/* Information we need between funding_start and funding_complete */
struct basepoints their_points;
struct pubkey their_funding_pubkey;
/* hsmd gives us our first per-commitment point, and peer tells us
* theirs */
struct pubkey first_per_commitment_point[NUM_SIDES];
/* Initially temporary, then final channel id. */
struct channel_id channel_id;
/* Funding and feerate: set by opening peer. */
struct amount_sat funding;
struct amount_msat push_msat;
u32 feerate_per_kw;
struct bitcoin_txid funding_txid;
u16 funding_txout;
/* If non-NULL, this is the scriptpubkey we/they *must* close with */
u8 *upfront_shutdown_script[NUM_SIDES];
/* This is a cluster of fields in open_channel and accept_channel which
* indicate the restrictions each side places on the channel. */
struct channel_config localconf, remoteconf;
/* The channel structure, as defined in common/initial_channel.h. While
* the structure has room for HTLCs, those routines are channeld-specific
* as initial channels never have HTLCs. */
struct channel *channel;
bool option_static_remotekey;
bool option_anchor_outputs;
struct feature_set *our_features;
};
/*~ If we can't agree on parameters, we fail to open the channel. If we're
* the opener, we need to tell lightningd, otherwise it never really notices. */
static void negotiation_aborted(struct state *state, bool am_opener,
const char *why)
{
status_debug("aborted opening negotiation: %s", why);
/*~ The "billboard" (exposed as "status" in the JSON listpeers RPC
* call) is a transient per-channel area which indicates important
* information about what is happening. It has a "permanent" area for
* each state, which can be used to indicate what went wrong in that
* state (such as here), and a single transient area for current
* status. */
peer_billboard(true, why);
/* If necessary, tell master that funding failed. */
if (am_opener) {
u8 *msg = towire_openingd_funder_failed(NULL, why);
wire_sync_write(REQ_FD, take(msg));
}
/* Default is no shutdown_scriptpubkey: free any leftover ones. */
state->upfront_shutdown_script[LOCAL]
= tal_free(state->upfront_shutdown_script[LOCAL]);
state->upfront_shutdown_script[REMOTE]
= tal_free(state->upfront_shutdown_script[REMOTE]);
/*~ Reset state. We keep gossipping with them, even though this open
* failed. */
memset(&state->channel_id, 0, sizeof(state->channel_id));
state->channel = tal_free(state->channel);
}
/*~ For negotiation failures: we tell them the parameter we didn't like. */
static void negotiation_failed(struct state *state, bool am_opener,
const char *fmt, ...)
{
va_list ap;
const char *errmsg;
u8 *msg;
va_start(ap, fmt);
errmsg = tal_vfmt(tmpctx, fmt, ap);
va_end(ap);
msg = towire_errorfmt(NULL, &state->channel_id,
"You gave bad parameters: %s", errmsg);
sync_crypto_write(state->pps, take(msg));
negotiation_aborted(state, am_opener, errmsg);
}
/* We always set channel_reserve_satoshis to 1%, rounded down. */
static void set_reserve(struct state *state, const struct amount_sat dust_limit)
{
state->localconf.channel_reserve = amount_sat_div(state->funding, 100);
/* BOLT #2:
*
* The sending node:
*...
* - MUST set `channel_reserve_satoshis` greater than or equal to
* `dust_limit_satoshis` from the `open_channel` message.
*/
if (amount_sat_greater(dust_limit,
state->localconf.channel_reserve))
state->localconf.channel_reserve
= dust_limit;
}
/*~ Handle random messages we might get during opening negotiation, (eg. gossip)
* returning the first non-handled one, or NULL if we aborted negotiation. */
static u8 *opening_negotiate_msg(const tal_t *ctx, struct state *state,
bool am_opener)
{
/* This is an event loop of its own. That's generally considered poor
* form, but we use it in a very limited way. */
for (;;) {
u8 *msg;
bool from_gossipd;
char *err;
bool warning;
struct channel_id actual;
/* The event loop is responsible for freeing tmpctx, so our
* temporary allocations don't grow unbounded. */
clean_tmpctx();
/* This helper routine polls both the peer and gossipd. */
msg = peer_or_gossip_sync_read(ctx, state->pps, &from_gossipd);
/* Use standard helper for gossip msgs (forwards, if it's an
* error, exits). */
if (from_gossipd) {
handle_gossip_msg(state->pps, take(msg));
continue;
}
/* Some messages go straight to gossipd. */
if (is_msg_for_gossipd(msg)) {
gossip_rcvd_filter_add(state->pps->grf, msg);
wire_sync_write(state->pps->gossip_fd, take(msg));
continue;
}
/* BOLT #1:
*
* A receiving node:
* - upon receiving a message of _odd_, unknown type:
* - MUST ignore the received message.
*/
if (is_unknown_msg_discardable(msg))
continue;
/* Might be a timestamp filter request: handle. */
if (handle_timestamp_filter(state->pps, msg))
continue;
/* A helper which decodes an error. */
if (is_peer_error(tmpctx, msg, &state->channel_id,
&err, &warning)) {
/* BOLT #1:
*
* - if no existing channel is referred to by the
* message:
* - MUST ignore the message.
*/
/* In this case, is_peer_error returns true, but sets
* err to NULL */
if (!err) {
tal_free(msg);
continue;
}
negotiation_aborted(state, am_opener,
tal_fmt(tmpctx, "They sent %s",
err));
/* Return NULL so caller knows to stop negotiating. */
return NULL;
}
/*~ We do not support multiple "live" channels, though the
* protocol has a "channel_id" field in all non-gossip messages
* so it's possible. Our one-process-one-channel mechanism
* keeps things simple: if we wanted to change this, we would
* probably be best with another daemon to de-multiplex them;
* this could be connectd itself, in fact. */
if (is_wrong_channel(msg, &state->channel_id, &actual)) {
status_debug("Rejecting %s for unknown channel_id %s",
peer_wire_name(fromwire_peektype(msg)),
type_to_string(tmpctx, struct channel_id,
&actual));
sync_crypto_write(state->pps,
take(towire_errorfmt(NULL, &actual,
"Multiple channels"
" unsupported")));
tal_free(msg);
continue;
}
/* If we get here, it's an interesting message. */
return msg;
}
}
static bool setup_channel_funder(struct state *state)
{
/*~ For symmetry, we calculate our own reserve even though lightningd
* could do it for the we-are-funding case. */
set_reserve(state, state->localconf.dust_limit);
/*~ Grab a random ID until the funding tx is created (we can't do that
* until we know their funding_pubkey) */
temporary_channel_id(&state->channel_id);
#if DEVELOPER
/* --dev-force-tmp-channel-id specified */
if (dev_force_tmp_channel_id)
state->channel_id = *dev_force_tmp_channel_id;
#endif
/* BOLT #2:
*
* The sending node:
*...
* - if both nodes advertised `option_support_large_channel`:
* - MAY set `funding_satoshis` greater than or equal to 2^24 satoshi.
* - otherwise:
* - MUST set `funding_satoshis` to less than 2^24 satoshi.
*/
if (!feature_negotiated(state->our_features,
state->their_features, OPT_LARGE_CHANNELS)
&& amount_sat_greater(state->funding, chainparams->max_funding)) {
status_failed(STATUS_FAIL_MASTER_IO,
"funding_satoshis must be < %s, not %s",
type_to_string(tmpctx, struct amount_sat,
&chainparams->max_funding),
type_to_string(tmpctx, struct amount_sat,
&state->funding));
return false;
}
return true;
}
static void set_remote_upfront_shutdown(struct state *state,
u8 *shutdown_scriptpubkey STEALS)
{
bool anysegwit = feature_negotiated(state->our_features,
state->their_features,
OPT_SHUTDOWN_ANYSEGWIT);
state->upfront_shutdown_script[REMOTE]
= tal_steal(state, shutdown_scriptpubkey);
if (shutdown_scriptpubkey
&& !valid_shutdown_scriptpubkey(shutdown_scriptpubkey, anysegwit))
peer_failed_err(state->pps,
&state->channel_id,
"Unacceptable upfront_shutdown_script %s",
tal_hex(tmpctx, shutdown_scriptpubkey));
}
/* We start the 'open a channel' negotation with the supplied peer, but
* stop when we get to the part where we need the funding txid */
static u8 *funder_channel_start(struct state *state, u8 channel_flags)
{
u8 *msg;
u8 *funding_output_script;
struct channel_id id_in;
struct tlv_open_channel_tlvs *open_tlvs;
struct tlv_accept_channel_tlvs *accept_tlvs;
char *err_reason;
if (!setup_channel_funder(state))
return NULL;
if (!state->upfront_shutdown_script[LOCAL])
state->upfront_shutdown_script[LOCAL]
= no_upfront_shutdown_script(state,
state->our_features,
state->their_features);
open_tlvs = tlv_open_channel_tlvs_new(tmpctx);
open_tlvs->upfront_shutdown_script
= state->upfront_shutdown_script[LOCAL];
msg = towire_open_channel(NULL,
&chainparams->genesis_blockhash,
&state->channel_id,
state->funding,
state->push_msat,
state->localconf.dust_limit,
state->localconf.max_htlc_value_in_flight,
state->localconf.channel_reserve,
state->localconf.htlc_minimum,
state->feerate_per_kw,
state->localconf.to_self_delay,
state->localconf.max_accepted_htlcs,
&state->our_funding_pubkey,
&state->our_points.revocation,
&state->our_points.payment,
&state->our_points.delayed_payment,
&state->our_points.htlc,
&state->first_per_commitment_point[LOCAL],
channel_flags,
open_tlvs);
sync_crypto_write(state->pps, take(msg));
/* This is usually a very transient state... */
peer_billboard(false,
"Funding channel start: offered, now waiting for accept_channel");
/* ... since their reply should be immediate. */
msg = opening_negotiate_msg(tmpctx, state, true);
if (!msg)
return NULL;
/* BOLT #2:
*
* The receiving node MUST fail the channel if:
*...
* - `funding_pubkey`, `revocation_basepoint`, `htlc_basepoint`,
* `payment_basepoint`, or `delayed_payment_basepoint` are not
* valid secp256k1 pubkeys in compressed format.
*/
accept_tlvs = tlv_accept_channel_tlvs_new(tmpctx);
if (!fromwire_accept_channel(msg, &id_in,
&state->remoteconf.dust_limit,
&state->remoteconf.max_htlc_value_in_flight,
&state->remoteconf.channel_reserve,
&state->remoteconf.htlc_minimum,
&state->minimum_depth,
&state->remoteconf.to_self_delay,
&state->remoteconf.max_accepted_htlcs,
&state->their_funding_pubkey,
&state->their_points.revocation,
&state->their_points.payment,
&state->their_points.delayed_payment,
&state->their_points.htlc,
&state->first_per_commitment_point[REMOTE],
accept_tlvs)) {
peer_failed_err(state->pps,
&state->channel_id,
"Parsing accept_channel %s", tal_hex(msg, msg));
}
set_remote_upfront_shutdown(state, accept_tlvs->upfront_shutdown_script);
/* BOLT #2:
*
* The `temporary_channel_id` MUST be the same as the
* `temporary_channel_id` in the `open_channel` message. */
if (!channel_id_eq(&id_in, &state->channel_id))
/* In this case we exit, since we don't know what's going on. */
peer_failed_err(state->pps, &id_in,
"accept_channel ids don't match: sent %s got %s",
type_to_string(msg, struct channel_id, &id_in),
type_to_string(msg, struct channel_id,
&state->channel_id));
if (amount_sat_greater(state->remoteconf.dust_limit,
state->localconf.channel_reserve)) {
negotiation_failed(state, true,
"dust limit %s"
" would be above our reserve %s",
type_to_string(tmpctx, struct amount_sat,
&state->remoteconf.dust_limit),
type_to_string(tmpctx, struct amount_sat,
&state->localconf.channel_reserve));
return NULL;
}
if (!check_config_bounds(tmpctx, state->funding,
state->feerate_per_kw,
state->max_to_self_delay,
state->min_effective_htlc_capacity,
&state->remoteconf,
&state->localconf,
true,
state->option_anchor_outputs,
&err_reason)) {
negotiation_failed(state, true, "%s", err_reason);
return NULL;
}
funding_output_script =
scriptpubkey_p2wsh(tmpctx,
bitcoin_redeem_2of2(tmpctx,
&state->our_funding_pubkey,
&state->their_funding_pubkey));
/* Update the billboard with our infos */
peer_billboard(false,
"Funding channel start: awaiting funding_txid with output to %s",
tal_hex(tmpctx, funding_output_script));
return towire_openingd_funder_start_reply(state,
funding_output_script,
feature_negotiated(
state->our_features,
state->their_features,
OPT_UPFRONT_SHUTDOWN_SCRIPT));
}
static bool funder_finalize_channel_setup(struct state *state,
struct amount_msat local_msat,
struct bitcoin_signature *sig,
struct bitcoin_tx **tx,
struct penalty_base **pbase)
{
u8 *msg;
struct channel_id id_in;
const u8 *wscript;
struct channel_id cid;
char *err_reason;
struct wally_tx_output *direct_outputs[NUM_SIDES];
/*~ Now we can initialize the `struct channel`. This represents
* the current channel state and is how we can generate the current
* commitment transaction.
*
* The routines to support `struct channel` are split into a common
* part (common/initial_channel) which doesn't support HTLCs and is
* enough for us here, and the complete channel support required by
* `channeld` which lives in channeld/full_channel. */
derive_channel_id(&cid,
&state->funding_txid, state->funding_txout);
state->channel = new_initial_channel(state,
&cid,
&state->funding_txid,
state->funding_txout,
state->minimum_depth,
state->funding,
local_msat,
take(new_fee_states(NULL, LOCAL,
&state->feerate_per_kw)),
&state->localconf,
&state->remoteconf,
&state->our_points,
&state->their_points,
&state->our_funding_pubkey,
&state->their_funding_pubkey,
state->option_static_remotekey,
state->option_anchor_outputs,
/* Opener is local */
LOCAL);
/* We were supposed to do enough checks above, but just in case,
* new_initial_channel will fail to create absurd channels */
if (!state->channel)
peer_failed_err(state->pps,
&state->channel_id,
"could not create channel with given config");
/* BOLT #2:
*
* ### The `funding_created` Message
*
* This message describes the outpoint which the funder has created
* for the initial commitment transactions. After receiving the
* peer's signature, via `funding_signed`, it will broadcast the funding
* transaction.
*/
/* This gives us their first commitment transaction. */
*tx = initial_channel_tx(state, &wscript, state->channel,
&state->first_per_commitment_point[REMOTE],
REMOTE, direct_outputs, &err_reason);
if (!*tx) {
/* This should not happen: we should never create channels we
* can't afford the fees for after reserve. */
negotiation_failed(state, true,
"Could not meet their fees and reserve: %s", err_reason);
goto fail;
}
if (direct_outputs[LOCAL])
*pbase = penalty_base_new(state, 0, *tx, direct_outputs[LOCAL]);
else
*pbase = NULL;
/* We ask the HSM to sign their commitment transaction for us: it knows
* our funding key, it just needs the remote funding key to create the
* witness script. It also needs the amount of the funding output,
* as segwit signatures commit to that as well, even though it doesn't
* explicitly appear in the transaction itself. */
msg = towire_hsmd_sign_remote_commitment_tx(NULL,
*tx,
&state->channel->funding_pubkey[REMOTE],
&state->first_per_commitment_point[REMOTE],
state->channel->option_static_remotekey);
wire_sync_write(HSM_FD, take(msg));
msg = wire_sync_read(tmpctx, HSM_FD);
if (!fromwire_hsmd_sign_tx_reply(msg, sig))
status_failed(STATUS_FAIL_HSM_IO, "Bad sign_tx_reply %s",
tal_hex(tmpctx, msg));
/* You can tell this has been a problem before, since there's a debug
* message here: */
status_debug("signature %s on tx %s using key %s",
type_to_string(tmpctx, struct bitcoin_signature, sig),
type_to_string(tmpctx, struct bitcoin_tx, *tx),
type_to_string(tmpctx, struct pubkey,
&state->our_funding_pubkey));
/* Now we give our peer the signature for their first commitment
* transaction. */
msg = towire_funding_created(state, &state->channel_id,
&state->funding_txid,
state->funding_txout,
&sig->s);
sync_crypto_write(state->pps, msg);
/* BOLT #2:
*
* ### The `funding_signed` Message
*
* This message gives the funder the signature it needs for the first
* commitment transaction, so it can broadcast the transaction knowing
* that funds can be redeemed, if need be.
*/
peer_billboard(false,
"Funding channel: create first tx, now waiting for their signature");
/* Now they send us their signature for that first commitment
* transaction. */
msg = opening_negotiate_msg(tmpctx, state, true);
if (!msg)
goto fail;
sig->sighash_type = SIGHASH_ALL;
if (!fromwire_funding_signed(msg, &id_in, &sig->s))
peer_failed_err(state->pps, &state->channel_id,
"Parsing funding_signed: %s", tal_hex(msg, msg));
/* BOLT #2:
*
* This message introduces the `channel_id` to identify the channel.
* It's derived from the funding transaction by combining the
* `funding_txid` and the `funding_output_index`, using big-endian
* exclusive-OR (i.e. `funding_output_index` alters the last 2
* bytes).
*/
/*~ Back in Milan, we chose to allow multiple channels between peers in
* the protocol. I insisted that we multiplex these over the same
* socket, and (even though I didn't plan on implementing it anytime
* soon) that we put it into the first version of the protocol
* because it would be painful to add in later.
*
* My logic seemed sound: we treat new connections as an implication
* that the old connection has disconnected, which happens more often
* than you'd hope on modern networks. However, supporting multiple
* channels via multiple connections would be far easier for us to
* support with our (introduced-since) separate daemon model.
*
* Let this be a lesson: beware premature specification, even if you
* suspect "we'll need it later!". */
state->channel_id = cid;
if (!channel_id_eq(&id_in, &state->channel_id))
peer_failed_err(state->pps, &id_in,
"funding_signed ids don't match: expected %s got %s",
type_to_string(msg, struct channel_id,
&state->channel_id),
type_to_string(msg, struct channel_id, &id_in));
/* BOLT #2:
*
* The recipient:
* - if `signature` is incorrect OR non-compliant with LOW-S-standard rule...:
* - MUST fail the channel
*/
/* So we create *our* initial commitment transaction, and check the
* signature they sent against that. */
*tx = initial_channel_tx(state, &wscript, state->channel,
&state->first_per_commitment_point[LOCAL],
LOCAL, direct_outputs, &err_reason);
if (!*tx) {
negotiation_failed(state, true,
"Could not meet our fees and reserve: %s", err_reason);
goto fail;
}
if (!check_tx_sig(*tx, 0, NULL, wscript, &state->their_funding_pubkey, sig)) {
peer_failed_err(state->pps, &state->channel_id,
"Bad signature %s on tx %s using key %s",
type_to_string(tmpctx, struct bitcoin_signature,
sig),
type_to_string(tmpctx, struct bitcoin_tx, *tx),
type_to_string(tmpctx, struct pubkey,
&state->their_funding_pubkey));
}
/* We save their sig to our first commitment tx */
if (!psbt_input_set_signature((*tx)->psbt, 0,
&state->their_funding_pubkey,
sig))
status_failed(STATUS_FAIL_INTERNAL_ERROR,
"Unable to set signature internally");
peer_billboard(false, "Funding channel: opening negotiation succeeded");
return true;
fail:
tal_free(wscript);
return false;
}
static u8 *funder_channel_complete(struct state *state)
{
/* Remote commitment tx */
struct bitcoin_tx *tx;
struct bitcoin_signature sig;
struct amount_msat local_msat;
struct penalty_base *pbase;
/* Update the billboard about what we're doing*/
peer_billboard(false,
"Funding channel con't: continuing with funding_txid %s",
type_to_string(tmpctx, struct bitcoin_txid, &state->funding_txid));
/* We recalculate the local_msat from cached values; should
* succeed because we checked it earlier */
if (!amount_sat_sub_msat(&local_msat, state->funding, state->push_msat))
status_failed(STATUS_FAIL_INTERNAL_ERROR,
"push_msat %s > funding %s?",
type_to_string(tmpctx, struct amount_msat,
&state->push_msat),
type_to_string(tmpctx, struct amount_sat,
&state->funding));
if (!funder_finalize_channel_setup(state, local_msat, &sig, &tx,
&pbase))
return NULL;
return towire_openingd_funder_reply(state,
&state->remoteconf,
tx,
pbase,
&sig,
state->pps,
&state->their_points.revocation,
&state->their_points.payment,
&state->their_points.htlc,
&state->their_points.delayed_payment,
&state->first_per_commitment_point[REMOTE],
state->minimum_depth,
&state->their_funding_pubkey,
&state->funding_txid,
state->funding_txout,
state->feerate_per_kw,
state->localconf.channel_reserve,
state->upfront_shutdown_script[REMOTE]);
}
/*~ The peer sent us an `open_channel`, that means we're the fundee. */
static u8 *fundee_channel(struct state *state, const u8 *open_channel_msg)
{
struct channel_id id_in;
struct basepoints theirs;
struct pubkey their_funding_pubkey;
struct bitcoin_signature theirsig, sig;
struct bitcoin_tx *local_commit, *remote_commit;
struct bitcoin_blkid chain_hash;
u8 *msg;
const u8 *wscript;
u8 channel_flags;
char* err_reason;
struct wally_tx_output *direct_outputs[NUM_SIDES];
struct penalty_base *pbase;
struct tlv_accept_channel_tlvs *accept_tlvs;
struct tlv_open_channel_tlvs *open_tlvs
= tlv_open_channel_tlvs_new(tmpctx);
/* BOLT #2:
*
* The receiving node MUST fail the channel if:
*...
* - `funding_pubkey`, `revocation_basepoint`, `htlc_basepoint`,
* `payment_basepoint`, or `delayed_payment_basepoint` are not valid
* secp256k1 pubkeys in compressed format.
*/
if (!fromwire_open_channel(open_channel_msg, &chain_hash,
&state->channel_id,
&state->funding,
&state->push_msat,
&state->remoteconf.dust_limit,
&state->remoteconf.max_htlc_value_in_flight,
&state->remoteconf.channel_reserve,
&state->remoteconf.htlc_minimum,
&state->feerate_per_kw,
&state->remoteconf.to_self_delay,
&state->remoteconf.max_accepted_htlcs,
&their_funding_pubkey,
&theirs.revocation,
&theirs.payment,
&theirs.delayed_payment,
&theirs.htlc,
&state->first_per_commitment_point[REMOTE],
&channel_flags,
open_tlvs))
peer_failed_err(state->pps,
&state->channel_id,
"Parsing open_channel %s", tal_hex(tmpctx, open_channel_msg));
set_remote_upfront_shutdown(state, open_tlvs->upfront_shutdown_script);
/* BOLT #2:
*
* The receiving node MUST fail the channel if:
* - the `chain_hash` value is set to a hash of a chain
* that is unknown to the receiver.
*/
if (!bitcoin_blkid_eq(&chain_hash, &chainparams->genesis_blockhash)) {
negotiation_failed(state, false,
"Unknown chain-hash %s",
type_to_string(tmpctx,
struct bitcoin_blkid,
&chain_hash));
return NULL;
}
/* BOLT #2:
*
* The receiving node MUST fail the channel if:
*...
* - `funding_satoshis` is greater than or equal to 2^24 and the receiver does not support
* `option_support_large_channel`. */
/* We choose to require *negotiation*, not just support! */
if (!feature_negotiated(state->our_features, state->their_features,
OPT_LARGE_CHANNELS)
&& amount_sat_greater(state->funding, chainparams->max_funding)) {
negotiation_failed(state, false,
"funding_satoshis %s too large",
type_to_string(tmpctx, struct amount_sat,
&state->funding));
return NULL;
}
/* BOLT #2:
*
* The receiving node MUST fail the channel if:
* ...
* - `push_msat` is greater than `funding_satoshis` * 1000.
*/
if (amount_msat_greater_sat(state->push_msat, state->funding)) {
peer_failed_err(state->pps, &state->channel_id,
"Their push_msat %s"
" would be too large for funding_satoshis %s",
type_to_string(tmpctx, struct amount_msat,
&state->push_msat),
type_to_string(tmpctx, struct amount_sat,
&state->funding));
return NULL;
}
/* BOLT #2:
*
* The receiving node MUST fail the channel if:
*...
* - it considers `feerate_per_kw` too small for timely processing or
* unreasonably large.
*/
if (state->feerate_per_kw < state->min_feerate) {
negotiation_failed(state, false,
"feerate_per_kw %u below minimum %u",
state->feerate_per_kw, state->min_feerate);
return NULL;
}
if (state->feerate_per_kw > state->max_feerate) {
negotiation_failed(state, false,
"feerate_per_kw %u above maximum %u",
state->feerate_per_kw, state->max_feerate);
return NULL;
}
/* This reserves 1% of the channel (rounded up) */
set_reserve(state, state->remoteconf.dust_limit);
/* BOLT #2:
*
* The sender:
*...
* - MUST set `channel_reserve_satoshis` greater than or equal to
* `dust_limit_satoshis` from the `open_channel` message.
* - MUST set `dust_limit_satoshis` less than or equal to
* `channel_reserve_satoshis` from the `open_channel` message.
*/
if (amount_sat_greater(state->remoteconf.dust_limit,
state->localconf.channel_reserve)) {
negotiation_failed(state, false,
"Our channel reserve %s"
" would be below their dust %s",
type_to_string(tmpctx, struct amount_sat,
&state->localconf.channel_reserve),
type_to_string(tmpctx, struct amount_sat,
&state->remoteconf.dust_limit));
return NULL;
}
if (amount_sat_greater(state->localconf.dust_limit,
state->remoteconf.channel_reserve)) {
negotiation_failed(state, false,
"Our dust limit %s"
" would be above their reserve %s",
type_to_string(tmpctx, struct amount_sat,
&state->localconf.dust_limit),
type_to_string(tmpctx, struct amount_sat,
&state->remoteconf.channel_reserve));
return NULL;
}
/* These checks are the same whether we're opener or accepter... */
if (!check_config_bounds(tmpctx, state->funding,
state->feerate_per_kw,
state->max_to_self_delay,
state->min_effective_htlc_capacity,
&state->remoteconf,
&state->localconf,
false,
state->option_anchor_outputs,
&err_reason)) {
negotiation_failed(state, false, "%s", err_reason);
return NULL;
}
/* Check with lightningd that we can accept this? In particular,
* if we have an existing channel, we don't support it. */
msg = towire_openingd_got_offer(NULL,
state->funding,
state->push_msat,
state->remoteconf.dust_limit,
state->remoteconf.max_htlc_value_in_flight,
state->remoteconf.channel_reserve,
state->remoteconf.htlc_minimum,
state->feerate_per_kw,
state->remoteconf.to_self_delay,
state->remoteconf.max_accepted_htlcs,
channel_flags,
state->upfront_shutdown_script[REMOTE]);
wire_sync_write(REQ_FD, take(msg));
msg = wire_sync_read(tmpctx, REQ_FD);
/* We don't allocate off tmpctx, because that's freed inside
* opening_negotiate_msg */
if (!fromwire_openingd_got_offer_reply(state, msg, &err_reason,
&state->upfront_shutdown_script[LOCAL]))
master_badmsg(WIRE_OPENINGD_GOT_OFFER_REPLY, msg);
/* If they give us a reason to reject, do so. */
if (err_reason) {
u8 *errmsg = towire_errorfmt(NULL, &state->channel_id,
"%s", err_reason);
sync_crypto_write(state->pps, take(errmsg));
tal_free(err_reason);
return NULL;
}
if (!state->upfront_shutdown_script[LOCAL])
state->upfront_shutdown_script[LOCAL]
= no_upfront_shutdown_script(state,
state->our_features,
state->their_features);
/* OK, we accept! */
accept_tlvs = tlv_accept_channel_tlvs_new(tmpctx);
accept_tlvs->upfront_shutdown_script
= state->upfront_shutdown_script[LOCAL];
msg = towire_accept_channel(NULL, &state->channel_id,
state->localconf.dust_limit,
state->localconf.max_htlc_value_in_flight,
state->localconf.channel_reserve,
state->localconf.htlc_minimum,
state->minimum_depth,
state->localconf.to_self_delay,
state->localconf.max_accepted_htlcs,
&state->our_funding_pubkey,
&state->our_points.revocation,
&state->our_points.payment,
&state->our_points.delayed_payment,
&state->our_points.htlc,
&state->first_per_commitment_point[LOCAL],
accept_tlvs);
sync_crypto_write(state->pps, take(msg));
peer_billboard(false,
"Incoming channel: accepted, now waiting for them to create funding tx");
/* This is a loop which handles gossip until we get a non-gossip msg */
msg = opening_negotiate_msg(tmpctx, state, false);
if (!msg)
return NULL;
/* The message should be "funding_created" which tells us what funding
* tx they generated; the sighash type is implied, so we set it here. */
theirsig.sighash_type = SIGHASH_ALL;
if (!fromwire_funding_created(msg, &id_in,
&state->funding_txid,
&state->funding_txout,
&theirsig.s))
peer_failed_err(state->pps, &state->channel_id,
"Parsing funding_created");
/* BOLT #2:
*
* The `temporary_channel_id` MUST be the same as the
* `temporary_channel_id` in the `open_channel` message.
*/
if (!channel_id_eq(&id_in, &state->channel_id))
peer_failed_err(state->pps, &id_in,
"funding_created ids don't match: sent %s got %s",
type_to_string(msg, struct channel_id,
&state->channel_id),
type_to_string(msg, struct channel_id, &id_in));
/* Now we can create the channel structure. */
state->channel = new_initial_channel(state,
&state->channel_id,
&state->funding_txid,