-
Notifications
You must be signed in to change notification settings - Fork 901
/
peer_control.c
1788 lines (1569 loc) · 52.1 KB
/
peer_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 "lightningd.h"
#include "peer_control.h"
#include "subd.h"
#include <arpa/inet.h>
#include <bitcoin/feerate.h>
#include <bitcoin/script.h>
#include <bitcoin/tx.h>
#include <ccan/array_size/array_size.h>
#include <ccan/io/io.h>
#include <ccan/noerr/noerr.h>
#include <ccan/str/str.h>
#include <ccan/take/take.h>
#include <ccan/tal/str/str.h>
#include <channeld/gen_channel_wire.h>
#include <common/dev_disconnect.h>
#include <common/features.h>
#include <common/initial_commit_tx.h>
#include <common/json_command.h>
#include <common/json_helpers.h>
#include <common/jsonrpc_errors.h>
#include <common/key_derive.h>
#include <common/param.h>
#include <common/status.h>
#include <common/timeout.h>
#include <common/version.h>
#include <common/wire_error.h>
#include <connectd/gen_connect_wire.h>
#include <errno.h>
#include <fcntl.h>
#include <hsmd/gen_hsm_wire.h>
#include <inttypes.h>
#include <lightningd/bitcoind.h>
#include <lightningd/chaintopology.h>
#include <lightningd/channel_control.h>
#include <lightningd/closing_control.h>
#include <lightningd/connect_control.h>
#include <lightningd/hsm_control.h>
#include <lightningd/json.h>
#include <lightningd/jsonrpc.h>
#include <lightningd/log.h>
#include <lightningd/memdump.h>
#include <lightningd/notification.h>
#include <lightningd/onchain_control.h>
#include <lightningd/opening_control.h>
#include <lightningd/options.h>
#include <lightningd/peer_htlcs.h>
#include <lightningd/plugin_hook.h>
#include <unistd.h>
#include <wally_bip32.h>
#include <wire/gen_onion_wire.h>
#include <wire/wire_sync.h>
struct close_command {
/* Inside struct lightningd close_commands. */
struct list_node list;
/* Command structure. This is the parent of the close command. */
struct command *cmd;
/* Channel being closed. */
struct channel *channel;
/* Should we force the close on timeout? */
bool force;
};
static void destroy_peer(struct peer *peer)
{
list_del_from(&peer->ld->peers, &peer->list);
}
/* We copy per-peer entries above --log-level into the main log. */
static void copy_to_parent_log(const char *prefix,
enum log_level level,
bool continued,
const struct timeabs *time UNUSED,
const char *str,
const u8 *io,
struct log *parent_log)
{
if (level == LOG_IO_IN || level == LOG_IO_OUT)
log_io(parent_log, level, prefix, io, tal_count(io));
else if (continued)
log_add(parent_log, "%s ... %s", prefix, str);
else
log_(parent_log, level, "%s %s", prefix, str);
}
static void peer_update_features(struct peer *peer,
const u8 *globalfeatures TAKES,
const u8 *localfeatures TAKES)
{
tal_free(peer->globalfeatures);
tal_free(peer->localfeatures);
peer->globalfeatures = tal_dup_arr(peer, u8,
globalfeatures,
tal_count(globalfeatures), 0);
peer->localfeatures = tal_dup_arr(peer, u8,
localfeatures,
tal_count(localfeatures), 0);
}
struct peer *new_peer(struct lightningd *ld, u64 dbid,
const struct pubkey *id,
const struct wireaddr_internal *addr)
{
/* We are owned by our channels, and freed manually by destroy_channel */
struct peer *peer = tal(NULL, struct peer);
peer->ld = ld;
peer->dbid = dbid;
peer->id = *id;
peer->uncommitted_channel = NULL;
peer->addr = *addr;
peer->globalfeatures = peer->localfeatures = NULL;
list_head_init(&peer->channels);
peer->direction = get_channel_direction(&peer->ld->id, &peer->id);
#if DEVELOPER
peer->ignore_htlcs = false;
#endif
/* Max 128k per peer. */
peer->log_book = new_log_book(128*1024, get_log_level(ld->log_book));
set_log_outfn(peer->log_book, copy_to_parent_log, ld->log);
list_add_tail(&ld->peers, &peer->list);
tal_add_destructor(peer, destroy_peer);
return peer;
}
static void delete_peer(struct peer *peer)
{
assert(list_empty(&peer->channels));
assert(!peer->uncommitted_channel);
/* If it only ever existed because of uncommitted channel, it won't
* be in the database */
if (peer->dbid != 0)
wallet_peer_delete(peer->ld->wallet, peer->dbid);
tal_free(peer);
}
/* Last one out deletes peer. */
void maybe_delete_peer(struct peer *peer)
{
if (!list_empty(&peer->channels))
return;
if (peer->uncommitted_channel) {
/* This isn't sufficient to keep it in db! */
if (peer->dbid != 0) {
wallet_peer_delete(peer->ld->wallet, peer->dbid);
peer->dbid = 0;
}
return;
}
delete_peer(peer);
}
struct peer *find_peer_by_dbid(struct lightningd *ld, u64 dbid)
{
struct peer *p;
list_for_each(&ld->peers, p, list)
if (p->dbid == dbid)
return p;
return NULL;
}
struct peer *peer_by_id(struct lightningd *ld, const struct pubkey *id)
{
struct peer *p;
list_for_each(&ld->peers, p, list)
if (pubkey_eq(&p->id, id))
return p;
return NULL;
}
struct peer *peer_from_json(struct lightningd *ld,
const char *buffer,
const jsmntok_t *peeridtok)
{
struct pubkey peerid;
if (!json_to_pubkey(buffer, peeridtok, &peerid))
return NULL;
return peer_by_id(ld, &peerid);
}
u8 *p2wpkh_for_keyidx(const tal_t *ctx, struct lightningd *ld, u64 keyidx)
{
struct pubkey shutdownkey;
if (!bip32_pubkey(ld->wallet->bip32_base, &shutdownkey, keyidx))
return NULL;
return scriptpubkey_p2wpkh(ctx, &shutdownkey);
}
static void sign_last_tx(struct channel *channel)
{
struct lightningd *ld = channel->peer->ld;
struct bitcoin_signature sig;
u8 *msg;
assert(!channel->last_tx->input[0].witness);
msg = towire_hsm_sign_commitment_tx(tmpctx,
&channel->peer->id,
channel->dbid,
channel->last_tx,
&channel->channel_info
.remote_fundingkey,
channel->funding);
if (!wire_sync_write(ld->hsm_fd, take(msg)))
fatal("Could not write to HSM: %s", strerror(errno));
msg = wire_sync_read(tmpctx, ld->hsm_fd);
if (!fromwire_hsm_sign_commitment_tx_reply(msg, &sig))
fatal("HSM gave bad sign_commitment_tx_reply %s",
tal_hex(tmpctx, msg));
channel->last_tx->input[0].witness
= bitcoin_witness_2of2(channel->last_tx->input,
&channel->last_sig,
&sig,
&channel->channel_info.remote_fundingkey,
&channel->local_funding_pubkey);
}
static void remove_sig(struct bitcoin_tx *signed_tx)
{
signed_tx->input[0].witness = tal_free(signed_tx->input[0].witness);
}
/* Resolve a single close command. */
static void
resolve_one_close_command(struct close_command *cc, bool cooperative)
{
struct json_stream *result = json_stream_success(cc->cmd);
u8 *tx = linearize_tx(result, cc->channel->last_tx);
struct bitcoin_txid txid;
bitcoin_txid(cc->channel->last_tx, &txid);
json_object_start(result, NULL);
json_add_hex_talarr(result, "tx", tx);
json_add_txid(result, "txid", &txid);
if (cooperative)
json_add_string(result, "type", "mutual");
else
json_add_string(result, "type", "unilateral");
json_object_end(result);
was_pending(command_success(cc->cmd, result));
}
/* Resolve a close command for a channel that will be closed soon. */
static void
resolve_close_command(struct lightningd *ld, struct channel *channel,
bool cooperative)
{
struct close_command *cc;
struct close_command *n;
list_for_each_safe (&ld->close_commands, cc, n, list) {
if (cc->channel != channel)
continue;
resolve_one_close_command(cc, cooperative);
}
}
/* Destroy the close command structure in reaction to the
* channel being destroyed. */
static void
destroy_close_command_on_channel_destroy(struct channel *_ UNUSED,
struct close_command *cc)
{
/* The cc has the command as parent, so resolving the
* command destroys the cc and triggers destroy_close_command.
* Clear the cc->channel first so that we will not try to
* remove a destructor. */
cc->channel = NULL;
was_pending(command_fail(cc->cmd, LIGHTNINGD,
"Channel forgotten before proper close."));
}
/* Destroy the close command structure. */
static void
destroy_close_command(struct close_command *cc)
{
list_del(&cc->list);
/* If destroy_close_command_on_channel_destroy was
* triggered beforehand, it will have cleared
* the channel field, preventing us from removing it
* from an already-destroyed channel. */
if (!cc->channel)
return;
tal_del_destructor2(cc->channel,
&destroy_close_command_on_channel_destroy,
cc);
}
/* Handle timeout. */
static void
close_command_timeout(struct close_command *cc)
{
if (cc->force)
/* This will trigger drop_to_chain, which will trigger
* resolution of the command and destruction of the
* close_command. */
channel_fail_permanent(cc->channel,
"Forcibly closed by 'close' command timeout");
else
/* Fail the command directly, which will resolve the
* command and destroy the close_command. */
was_pending(command_fail(cc->cmd, LIGHTNINGD,
"Channel close negotiation not finished "
"before timeout"));
}
/* Construct a close command structure and add to ld. */
static void
register_close_command(struct lightningd *ld,
struct command *cmd,
struct channel *channel,
unsigned int timeout,
bool force)
{
struct close_command *cc;
assert(channel);
cc = tal(cmd, struct close_command);
list_add_tail(&ld->close_commands, &cc->list);
cc->cmd = cmd;
cc->channel = channel;
cc->force = force;
tal_add_destructor(cc, &destroy_close_command);
tal_add_destructor2(channel,
&destroy_close_command_on_channel_destroy,
cc);
new_reltimer(&ld->timers, cc, time_from_sec(timeout),
&close_command_timeout, cc);
}
void drop_to_chain(struct lightningd *ld, struct channel *channel,
bool cooperative)
{
/* BOLT #2:
*
* - if `next_remote_revocation_number` is greater than expected
* above, AND `your_last_per_commitment_secret` is correct for that
* `next_remote_revocation_number` minus 1:
* - MUST NOT broadcast its commitment transaction.
*/
if (channel->future_per_commitment_point && !cooperative) {
log_broken(channel->log,
"Cannot broadcast our commitment tx:"
" they have a future one");
} else {
sign_last_tx(channel);
/* Keep broadcasting until we say stop (can fail due to dup,
* if they beat us to the broadcast). */
broadcast_tx(ld->topology, channel, channel->last_tx, NULL);
remove_sig(channel->last_tx);
}
resolve_close_command(ld, channel, cooperative);
}
void channel_errmsg(struct channel *channel,
int peer_fd, int gossip_fd,
const struct crypto_state *cs,
const struct channel_id *channel_id UNUSED,
const char *desc,
const u8 *err_for_them)
{
/* No peer fd means a subd crash or disconnection. */
if (peer_fd == -1) {
channel_fail_transient(channel, "%s: %s",
channel->owner->name, desc);
return;
}
/* Do we have an error to send? */
if (err_for_them && !channel->error)
channel->error = tal_dup_arr(channel, u8,
err_for_them,
tal_count(err_for_them), 0);
/* Make sure channel_fail_permanent doesn't tell connectd we died! */
channel->connected = false;
notify_disconnect(channel->peer->ld, &channel->peer->id);
/* BOLT #1:
*
* A sending node:
*...
* - when `channel_id` is 0:
* - MUST fail all channels with the receiving node.
* - MUST close the connection.
*/
/* FIXME: Close if it's an all-channels error sent or rcvd */
/* BOLT #1:
*
* A sending node:
* - when sending `error`:
* - MUST fail the channel referred to by the error message.
*...
* The receiving node:
* - upon receiving `error`:
* - MUST fail the channel referred to by the error message,
* if that channel is with the sending node.
*/
channel_fail_permanent(channel, "%s: %s ERROR %s",
channel->owner->name,
err_for_them ? "sent" : "received", desc);
}
/* Possible outcomes returned by the `connected` hook. */
enum peer_connected_hook_result {
PEER_CONNECTED_CONTINUE,
PEER_CONNECTED_DISCONNECT,
};
struct peer_connected_hook_payload {
struct lightningd *ld;
struct crypto_state crypto_state;
struct channel *channel;
struct wireaddr_internal addr;
struct peer *peer;
int peer_fd;
int gossip_fd;
};
struct peer_connected_hook_response {
enum peer_connected_hook_result result;
};
static void json_add_htlcs(struct lightningd *ld,
struct json_stream *response,
const struct channel *channel)
{
/* FIXME: make per-channel htlc maps! */
const struct htlc_in *hin;
struct htlc_in_map_iter ini;
const struct htlc_out *hout;
struct htlc_out_map_iter outi;
/* FIXME: Add more fields. */
json_array_start(response, "htlcs");
for (hin = htlc_in_map_first(&ld->htlcs_in, &ini);
hin;
hin = htlc_in_map_next(&ld->htlcs_in, &ini)) {
if (hin->key.channel != channel)
continue;
json_object_start(response, NULL);
json_add_string(response, "direction", "in");
json_add_u64(response, "id", hin->key.id);
json_add_amount_msat(response, hin->msat,
"msatoshi", "amount_msat");
json_add_u64(response, "expiry", hin->cltv_expiry);
json_add_hex(response, "payment_hash",
&hin->payment_hash, sizeof(hin->payment_hash));
json_add_string(response, "state",
htlc_state_name(hin->hstate));
json_object_end(response);
}
for (hout = htlc_out_map_first(&ld->htlcs_out, &outi);
hout;
hout = htlc_out_map_next(&ld->htlcs_out, &outi)) {
if (hout->key.channel != channel)
continue;
json_object_start(response, NULL);
json_add_string(response, "direction", "out");
json_add_u64(response, "id", hout->key.id);
json_add_amount_msat(response, hout->msat,
"msatoshi", "amount_msat");
json_add_u64(response, "expiry", hout->cltv_expiry);
json_add_hex(response, "payment_hash",
&hout->payment_hash, sizeof(hout->payment_hash));
json_add_string(response, "state",
htlc_state_name(hout->hstate));
json_object_end(response);
}
json_array_end(response);
}
/* We do this replication manually because it's an array. */
static void json_add_sat_only(struct json_stream *result,
const char *fieldname,
struct amount_sat sat)
{
struct amount_msat msat;
if (amount_sat_to_msat(&msat, sat))
json_add_member(result, fieldname, "\"%s\"",
type_to_string(tmpctx, struct amount_msat, &msat));
}
static void json_add_channel(struct lightningd *ld,
struct json_stream *response, const char *key,
const struct channel *channel)
{
struct channel_id cid;
struct channel_stats channel_stats;
struct amount_msat spendable, funding_msat;
struct peer *p = channel->peer;
json_object_start(response, key);
json_add_string(response, "state", channel_state_name(channel));
if (channel->last_tx) {
struct bitcoin_txid txid;
bitcoin_txid(channel->last_tx, &txid);
json_add_txid(response, "scratch_txid", &txid);
}
if (channel->owner)
json_add_string(response, "owner", channel->owner->name);
if (channel->scid) {
json_add_short_channel_id(response, "short_channel_id",
channel->scid);
json_add_num(response, "direction",
pubkey_idx(&ld->id, &channel->peer->id));
}
derive_channel_id(&cid, &channel->funding_txid,
channel->funding_outnum);
json_add_string(response, "channel_id",
type_to_string(tmpctx, struct channel_id, &cid));
json_add_txid(response, "funding_txid", &channel->funding_txid);
json_add_bool(
response, "private",
!(channel->channel_flags & CHANNEL_FLAGS_ANNOUNCE_CHANNEL));
// FIXME @conscott : Modify this when dual-funded channels
// are implemented
json_object_start(response, "funding_allocation_msat");
if (channel->funder == LOCAL) {
json_add_u64(response, pubkey_to_hexstr(tmpctx, &p->id), 0);
json_add_u64(response, pubkey_to_hexstr(tmpctx, &ld->id),
channel->funding.satoshis * 1000); /* Raw: raw JSON field */
} else {
json_add_u64(response, pubkey_to_hexstr(tmpctx, &ld->id), 0);
json_add_u64(response, pubkey_to_hexstr(tmpctx, &p->id),
channel->funding.satoshis * 1000); /* Raw: raw JSON field */
}
json_object_end(response);
json_object_start(response, "funding_msat");
if (channel->funder == LOCAL) {
json_add_sat_only(response,
pubkey_to_hexstr(tmpctx, &p->id),
AMOUNT_SAT(0));
json_add_sat_only(response,
pubkey_to_hexstr(tmpctx, &ld->id),
channel->funding);
} else {
json_add_sat_only(response,
pubkey_to_hexstr(tmpctx, &ld->id),
AMOUNT_SAT(0));
json_add_sat_only(response,
pubkey_to_hexstr(tmpctx, &p->id),
channel->funding);
}
json_object_end(response);
if (!amount_sat_to_msat(&funding_msat, channel->funding)) {
log_broken(channel->log,
"Overflow converting funding %s",
type_to_string(tmpctx, struct amount_sat,
&channel->funding));
funding_msat = AMOUNT_MSAT(0);
}
json_add_amount_msat(response, channel->our_msat,
"msatoshi_to_us", "to_us_msat");
json_add_amount_msat(response, channel->msat_to_us_min,
"msatoshi_to_us_min", "min_to_us_msat");
json_add_amount_msat(response, channel->msat_to_us_max,
"msatoshi_to_us_max", "max_to_us_msat");
json_add_amount_msat(response, funding_msat,
"msatoshi_total", "total_msat");
/* channel config */
json_add_amount_sat(response,
channel->our_config.dust_limit,
"dust_limit_satoshis", "dust_limit_msat");
json_add_amount_msat(response,
channel->our_config.max_htlc_value_in_flight,
"max_htlc_value_in_flight_msat",
"max_total_htlc_in_msat");
/* The `channel_reserve_satoshis` is imposed on
* the *other* side (see `channel_reserve_msat`
* function in, it uses `!side` to flip sides).
* So our configuration `channel_reserve_satoshis`
* is imposed on their side, while their
* configuration `channel_reserve_satoshis` is
* imposed on ours. */
json_add_amount_sat(response,
channel->our_config.channel_reserve,
"their_channel_reserve_satoshis",
"their_reserve_msat");
json_add_amount_sat(response,
channel->channel_info.their_config.channel_reserve,
"our_channel_reserve_satoshis",
"our_reserve_msat");
/* Compute how much we can send via this channel. */
if (!amount_msat_sub_sat(&spendable,
channel->our_msat,
channel->channel_info.their_config.channel_reserve))
spendable = AMOUNT_MSAT(0);
json_add_amount_msat(response, spendable,
"spendable_msatoshi", "spendable_msat");
json_add_amount_msat(response,
channel->our_config.htlc_minimum,
"htlc_minimum_msat",
"minimum_htlc_in_msat");
/* The `to_self_delay` is imposed on the *other*
* side, so our configuration `to_self_delay` is
* imposed on their side, while their configuration
* `to_self_delay` is imposed on ours. */
json_add_num(response, "their_to_self_delay",
channel->our_config.to_self_delay);
json_add_num(response, "our_to_self_delay",
channel->channel_info.their_config.to_self_delay);
json_add_num(response, "max_accepted_htlcs",
channel->our_config.max_accepted_htlcs);
json_array_start(response, "status");
for (size_t i = 0; i < ARRAY_SIZE(channel->billboard.permanent); i++) {
if (!channel->billboard.permanent[i])
continue;
json_add_string(response, NULL,
channel->billboard.permanent[i]);
}
if (channel->billboard.transient)
json_add_string(response, NULL, channel->billboard.transient);
json_array_end(response);
/* Provide channel statistics */
wallet_channel_stats_load(ld->wallet, channel->dbid, &channel_stats);
json_add_u64(response, "in_payments_offered",
channel_stats.in_payments_offered);
json_add_amount_msat(response,
channel_stats.in_msatoshi_offered,
"in_msatoshi_offered",
"in_offered_msat");
json_add_u64(response, "in_payments_fulfilled",
channel_stats.in_payments_fulfilled);
json_add_amount_msat(response,
channel_stats.in_msatoshi_fulfilled,
"in_msatoshi_fulfilled",
"in_fulfilled_msat");
json_add_u64(response, "out_payments_offered",
channel_stats.out_payments_offered);
json_add_amount_msat(response,
channel_stats.out_msatoshi_offered,
"out_msatoshi_offered",
"out_offered_msat");
json_add_u64(response, "out_payments_fulfilled",
channel_stats.out_payments_fulfilled);
json_add_amount_msat(response,
channel_stats.out_msatoshi_fulfilled,
"out_msatoshi_fulfilled",
"out_fulfilled_msat");
json_add_htlcs(ld, response, channel);
json_object_end(response);
}
static void
peer_connected_serialize(struct peer_connected_hook_payload *payload,
struct json_stream *stream)
{
const struct peer *p = payload->peer;
json_object_start(stream, "peer");
json_add_pubkey(stream, "id", &p->id);
json_add_string(
stream, "addr",
type_to_string(stream, struct wireaddr_internal, &payload->addr));
json_add_hex_talarr(stream, "globalfeatures", p->globalfeatures);
json_add_hex_talarr(stream, "localfeatures", p->localfeatures);
json_object_end(stream); /* .peer */
}
static struct peer_connected_hook_response *
peer_connected_deserialize(const tal_t *ctx, const char *buffer,
const jsmntok_t *toks)
{
const jsmntok_t *resulttok;
struct peer_connected_hook_response *resp;
resulttok = json_get_member(buffer, toks, "result");
if (!resulttok) {
return NULL;
}
resp = tal(ctx, struct peer_connected_hook_response);
if (json_tok_streq(buffer, resulttok, "continue"))
resp->result = PEER_CONNECTED_CONTINUE;
else if (json_tok_streq(buffer, resulttok, "disconnect"))
resp->result = PEER_CONNECTED_DISCONNECT;
else
fatal("Plugin returned an invalid response to the connected "
"hook: %s", buffer);
return resp;
}
static void
peer_connected_hook_cb(struct peer_connected_hook_payload *payload,
struct peer_connected_hook_response *response)
{
struct lightningd *ld = payload->ld;
struct crypto_state *cs = &payload->crypto_state;
struct channel *channel = payload->channel;
struct wireaddr_internal addr = payload->addr;
struct peer *peer = payload->peer;
int gossip_fd = payload->gossip_fd;
int peer_fd = payload->peer_fd;
u8 *error;
if (response && response->result == PEER_CONNECTED_DISCONNECT) {
close(peer_fd);
tal_free(payload);
return;
}
if (channel) {
log_debug(channel->log, "Peer has reconnected, state %s",
channel_state_name(channel));
/* If we have a canned error, deliver it now. */
if (channel->error) {
error = channel->error;
goto send_error;
}
#if DEVELOPER
if (dev_disconnect_permanent(ld)) {
channel_internal_error(channel,
"dev_disconnect permfail");
error = channel->error;
goto send_error;
}
#endif
switch (channel->state) {
case ONCHAIN:
case FUNDING_SPEND_SEEN:
case CLOSINGD_COMPLETE:
/* Channel is supposed to be active! */
abort();
/* We consider this "active" but we only send an error */
case AWAITING_UNILATERAL: {
struct channel_id cid;
derive_channel_id(&cid,
&channel->funding_txid,
channel->funding_outnum);
/* channel->error is not saved in db, so this can
* happen if we restart. */
error = towire_errorfmt(tmpctx, &cid,
"Awaiting unilateral close");
goto send_error;
}
case CHANNELD_AWAITING_LOCKIN:
case CHANNELD_NORMAL:
case CHANNELD_SHUTTING_DOWN:
assert(!channel->owner);
channel->peer->addr = addr;
peer_start_channeld(channel, cs,
peer_fd, gossip_fd, NULL,
true);
tal_free(payload);
return;
case CLOSINGD_SIGEXCHANGE:
assert(!channel->owner);
channel->peer->addr = addr;
peer_start_closingd(channel, cs,
peer_fd, gossip_fd,
true, NULL);
tal_free(payload);
return;
}
abort();
}
notify_connect(ld, &peer->id, &addr);
/* No err, all good. */
error = NULL;
send_error:
peer_start_openingd(peer, cs, peer_fd, gossip_fd, error);
tal_free(payload);
}
REGISTER_PLUGIN_HOOK(peer_connected, peer_connected_hook_cb,
struct peer_connected_hook_payload *,
peer_connected_serialize,
struct peer_connected_hook_payload *,
peer_connected_deserialize,
struct peer_connected_hook_response *);
/* Connectd tells us a peer has connected: it never hands us duplicates, since
* it holds them until we say peer_died. */
void peer_connected(struct lightningd *ld, const u8 *msg,
int peer_fd, int gossip_fd)
{
struct pubkey id;
u8 *globalfeatures, *localfeatures;
struct peer *peer;
struct peer_connected_hook_payload *hook_payload;
hook_payload = tal(NULL, struct peer_connected_hook_payload);
hook_payload->ld = ld;
hook_payload->gossip_fd = gossip_fd;
hook_payload->peer_fd = peer_fd;
if (!fromwire_connect_peer_connected(msg, msg,
&id, &hook_payload->addr, &hook_payload->crypto_state,
&globalfeatures, &localfeatures))
fatal("Connectd gave bad CONNECT_PEER_CONNECTED message %s",
tal_hex(msg, msg));
/* Complete any outstanding connect commands. */
connect_succeeded(ld, &id);
/* If we're already dealing with this peer, hand off to correct
* subdaemon. Otherwise, we'll hand to openingd to wait there. */
peer = peer_by_id(ld, &id);
if (!peer)
peer = new_peer(ld, 0, &id, &hook_payload->addr);
tal_steal(peer, hook_payload);
hook_payload->peer = peer;
peer_update_features(peer, globalfeatures, localfeatures);
/* Can't be opening, since we wouldn't have sent peer_disconnected. */
assert(!peer->uncommitted_channel);
hook_payload->channel = peer_active_channel(peer);
plugin_hook_call_peer_connected(ld, hook_payload, hook_payload);
}
static enum watch_result funding_lockin_cb(struct lightningd *ld,
struct channel *channel,
const struct bitcoin_txid *txid,
unsigned int depth)
{
const char *txidstr;
txidstr = type_to_string(channel, struct bitcoin_txid, txid);
log_debug(channel->log, "Funding tx %s depth %u of %u",
txidstr, depth, channel->minimum_depth);
tal_free(txidstr);
if (depth < channel->minimum_depth)
return KEEP_WATCHING;
/* If we restart, we could already have peer->scid from database */
if (!channel->scid) {
struct txlocator *loc;
loc = wallet_transaction_locate(tmpctx, ld->wallet, txid);
channel->scid = tal(channel, struct short_channel_id);
if (!mk_short_channel_id(channel->scid,
loc->blkheight, loc->index,
channel->funding_outnum)) {
channel_fail_permanent(channel, "Invalid funding scid %u:%u:%u",
loc->blkheight, loc->index,
channel->funding_outnum);
return DELETE_WATCH;
}
/* We've added scid, update */
wallet_channel_save(ld->wallet, channel);
}
/* Try to tell subdaemon */
if (!channel_tell_funding_locked(ld, channel, txid, depth))
return KEEP_WATCHING;
/* BOLT #7:
*
* A node:
* - if the `open_channel` message has the `announce_channel` bit set AND a `shutdown` message has not been sent:
* - MUST send the `announcement_signatures` message.
* - MUST NOT send `announcement_signatures` messages until `funding_locked`
* has been sent and received AND the funding transaction has at least six confirmations.
* - otherwise:
* - MUST NOT send the `announcement_signatures` message.
*/
if (!(channel->channel_flags & CHANNEL_FLAGS_ANNOUNCE_CHANNEL))
return DELETE_WATCH;
/* We keep telling it depth until we get to announce depth. */
if (depth < ANNOUNCE_MIN_DEPTH)
return KEEP_WATCHING;
return DELETE_WATCH;
}
static enum watch_result funding_spent(struct channel *channel,
const struct bitcoin_tx *tx,
size_t inputnum UNUSED,
const struct block *block)
{
struct bitcoin_txid txid;
bitcoin_txid(tx, &txid);
wallet_channeltxs_add(channel->peer->ld->wallet, channel,
WIRE_ONCHAIN_INIT, &txid, 0, block->height);
return onchaind_funding_spent(channel, tx, block->height);
}
void channel_watch_funding(struct lightningd *ld, struct channel *channel)
{
/* FIXME: Remove arg from cb? */
watch_txid(channel, ld->topology, channel,
&channel->funding_txid, funding_lockin_cb);
watch_txo(channel, ld->topology, channel,
&channel->funding_txid, channel->funding_outnum,
funding_spent);
}
static void json_add_peer(struct lightningd *ld,
struct json_stream *response,
struct peer *p,
const enum log_level *ll)
{
bool connected;
struct channel *channel;
json_object_start(response, NULL);
json_add_pubkey(response, "id", &p->id);
/* Channel is also connected if uncommitted channel */
if (p->uncommitted_channel)
connected = true;
else {
channel = peer_active_channel(p);
connected = channel && channel->connected;
}
json_add_bool(response, "connected", connected);
/* If it's not connected, features are unreliable: we don't
* store them in the database, and they would only reflect
* their features *last* time they connected. */
if (connected) {
json_array_start(response, "netaddr");
json_add_string(response, NULL,
type_to_string(response,
struct wireaddr_internal,
&p->addr));
json_array_end(response);
if (deprecated_apis) {
json_add_hex_talarr(response, "global_features",
p->globalfeatures);
json_add_hex_talarr(response, "local_features",
p->localfeatures);
}
json_add_hex_talarr(response, "globalfeatures",
p->globalfeatures);
json_add_hex_talarr(response, "localfeatures",
p->localfeatures);
}
json_array_start(response, "channels");
json_add_uncommitted_channel(response, p->uncommitted_channel);
list_for_each(&p->channels, channel, list)
json_add_channel(ld, response, NULL, channel);
json_array_end(response);
if (ll)
json_add_log(response, p->log_book, *ll);
json_object_end(response);
}
static struct command_result *json_listpeers(struct command *cmd,
const char *buffer,
const jsmntok_t *obj UNNEEDED,
const jsmntok_t *params)
{
enum log_level *ll;