forked from ElementsProject/lightning
-
Notifications
You must be signed in to change notification settings - Fork 0
/
peer.c
1845 lines (1569 loc) · 50.3 KB
/
peer.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 "bitcoind.h"
#include "close_tx.h"
#include "commit_tx.h"
#include "controlled_time.h"
#include "cryptopkt.h"
#include "dns.h"
#include "find_p2sh_out.h"
#include "jsonrpc.h"
#include "lightningd.h"
#include "log.h"
#include "names.h"
#include "peer.h"
#include "pseudorand.h"
#include "secrets.h"
#include "state.h"
#include "timeout.h"
#include <bitcoin/base58.h>
#include <bitcoin/script.h>
#include <bitcoin/tx.h>
#include <ccan/array_size/array_size.h>
#include <ccan/io/io.h>
#include <ccan/list/list.h>
#include <ccan/noerr/noerr.h>
#include <ccan/ptrint/ptrint.h>
#include <ccan/str/hex/hex.h>
#include <ccan/structeq/structeq.h>
#include <ccan/tal/str/str.h>
#include <ccan/tal/tal.h>
#include <errno.h>
#include <inttypes.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#define FIXME_STUB(peer) do { log_broken((peer)->dstate->base_log, "%s:%u: Implement %s!", __FILE__, __LINE__, __func__); abort(); } while(0)
struct json_connecting {
/* This owns us, so we're freed after command_fail or command_success */
struct command *cmd;
const char *name, *port;
u64 satoshis;
};
struct pending_cmd {
struct list_node list;
void (*dequeue)(struct peer *, void *arg);
void *arg;
};
static struct peer *find_peer(struct lightningd_state *dstate,
const char *buffer,
jsmntok_t *peeridtok)
{
struct pubkey peerid;
struct peer *peer;
if (!pubkey_from_hexstr(dstate->secpctx,
buffer + peeridtok->start,
peeridtok->end - peeridtok->start, &peerid))
return NULL;
list_for_each(&dstate->peers, peer, list) {
if (peer->state != STATE_INIT && pubkey_eq(&peer->id, &peerid))
return peer;
}
return NULL;
}
static struct json_result *null_response(const tal_t *ctx)
{
struct json_result *response;
response = new_json_result(ctx);
json_object_start(response, NULL);
json_object_end(response);
return response;
}
static void peer_cmd_complete(struct peer *peer, enum command_status status)
{
assert(peer->curr_cmd.cmd != INPUT_NONE);
/* If it's a json command, complete that now. */
if (peer->curr_cmd.jsoncmd) {
if (status == CMD_FAIL)
/* FIXME: y'know, details. */
command_fail(peer->curr_cmd.jsoncmd, "Failed");
else {
assert(status == CMD_SUCCESS);
command_success(peer->curr_cmd.jsoncmd,
null_response(peer->curr_cmd.jsoncmd));
}
}
peer->curr_cmd.cmd = INPUT_NONE;
}
static void set_current_command(struct peer *peer,
const enum state_input input,
void *idata,
struct command *jsoncmd)
{
assert(peer->curr_cmd.cmd == INPUT_NONE);
assert(input != INPUT_NONE);
peer->curr_cmd.cmd = input;
/* This is a union, so assign to any member. */
peer->curr_cmd.cmddata.pkt = idata;
peer->curr_cmd.jsoncmd = jsoncmd;
}
static void state_single(struct peer *peer,
const enum state_input input,
const union input *idata)
{
enum command_status status;
const struct bitcoin_tx *broadcast;
size_t old_outpkts = tal_count(peer->outpkt);
status = state(peer, input, idata, &broadcast);
log_debug(peer->log, "%s => %s",
input_name(input), state_name(peer->state));
switch (status) {
case CMD_NONE:
break;
case CMD_SUCCESS:
log_add(peer->log, " (command success)");
peer_cmd_complete(peer, CMD_SUCCESS);
break;
case CMD_FAIL:
log_add(peer->log, " (command FAIL)");
peer_cmd_complete(peer, CMD_FAIL);
break;
case CMD_REQUEUE:
log_add(peer->log, " (Command requeue)");
break;
}
if (tal_count(peer->outpkt) > old_outpkts) {
Pkt *outpkt = peer->outpkt[old_outpkts].pkt;
log_add(peer->log, " (out %s)", input_name(outpkt->pkt_case));
}
if (broadcast) {
struct sha256_double txid;
bitcoin_txid(broadcast, &txid);
/* FIXME: log_struct */
log_add(peer->log, " (tx %02x%02x%02x%02x...)",
txid.sha.u.u8[0], txid.sha.u.u8[1],
txid.sha.u.u8[2], txid.sha.u.u8[3]);
bitcoind_send_tx(peer->dstate, broadcast);
}
/* Start output if not running already; it will close conn. */
if (peer->cond == PEER_CLOSED)
io_wake(peer);
/* FIXME: Some of these should just result in this peer being killed? */
if (state_is_error(peer->state)) {
log_broken(peer->log, "Entered error state %s",
state_name(peer->state));
fatal("Peer entered error state");
}
/* Break out and free this peer if it's completely done. */
if (peer->state == STATE_CLOSED)
io_break(peer);
}
static void try_command(struct peer *peer)
{
/* If we can accept a command, and we have one queued, run it. */
while (peer->cond == PEER_CMD_OK
&& !list_empty(&peer->pending_cmd)) {
struct pending_cmd *pend = list_pop(&peer->pending_cmd,
struct pending_cmd, list);
assert(peer->curr_cmd.cmd == INPUT_NONE);
/* This can fail to enqueue a command! */
pend->dequeue(peer, pend->arg);
tal_free(pend);
if (peer->curr_cmd.cmd != INPUT_NONE) {
state_single(peer, peer->curr_cmd.cmd,
&peer->curr_cmd.cmddata);
}
}
}
#define queue_cmd(peer, cb, arg) \
queue_cmd_((peer), \
typesafe_cb_preargs(void, void *, \
(cb), (arg), \
struct peer *), \
(arg))
static void queue_cmd_(struct peer *peer,
void (*dequeue)(struct peer *peer, void *arg),
void *arg)
{
struct pending_cmd *pend = tal(peer, struct pending_cmd);
pend->dequeue = dequeue;
pend->arg = arg;
list_add_tail(&peer->pending_cmd, &pend->list);
try_command(peer);
};
/* All unrevoked commit txs must have no HTLCs in them. */
bool committed_to_htlcs(const struct peer *peer)
{
const struct commit_info *i;
/* Before anchor exchange, we don't even have cstate. */
if (!peer->us.commit || !peer->us.commit->cstate)
return false;
i = peer->us.commit;
while (i && !i->revocation_preimage) {
if (tal_count(i->cstate->a.htlcs))
return true;
if (tal_count(i->cstate->b.htlcs))
return true;
i = i->prev;
}
i = peer->them.commit;
while (i && !i->revocation_preimage) {
if (tal_count(i->cstate->a.htlcs))
return true;
if (tal_count(i->cstate->b.htlcs))
return true;
i = i->prev;
}
return false;
}
static void state_event(struct peer *peer,
const enum state_input input,
const union input *idata)
{
state_single(peer, input, idata);
if (peer->cleared != INPUT_NONE && !committed_to_htlcs(peer)) {
enum state_input all_done = peer->cleared;
peer->cleared = INPUT_NONE;
state_single(peer, all_done, NULL);
}
try_command(peer);
}
static struct io_plan *pkt_out(struct io_conn *conn, struct peer *peer)
{
struct out_pkt out;
size_t n = tal_count(peer->outpkt);
if (n == 0) {
/* We close the connection once we've sent everything. */
if (peer->cond == PEER_CLOSED)
return io_close(conn);
return io_out_wait(conn, peer, pkt_out, peer);
}
out = peer->outpkt[0];
memmove(peer->outpkt, peer->outpkt + 1, (sizeof(*peer->outpkt)*(n-1)));
tal_resize(&peer->outpkt, n-1);
return peer_write_packet(conn, peer, out.pkt, out.ack_cb, out.ack_arg,
pkt_out);
}
static struct io_plan *pkt_in(struct io_conn *conn, struct peer *peer)
{
union input idata;
const tal_t *ctx = tal(peer, char);
idata.pkt = tal_steal(ctx, peer->inpkt);
/* We ignore packets if they tell us to. */
if (peer->cond != PEER_CLOSED)
state_event(peer, peer->inpkt->pkt_case, &idata);
/* Free peer->inpkt unless stolen above. */
tal_free(ctx);
return peer_read_packet(conn, peer, pkt_in);
}
static void do_anchor_offer(struct peer *peer, void *unused)
{
set_current_command(peer, peer->us.offer_anchor, NULL, NULL);
}
/* Crypto is on, we are live. */
static struct io_plan *peer_crypto_on(struct io_conn *conn, struct peer *peer)
{
peer_secrets_init(peer);
peer_get_revocation_hash(peer, 0, &peer->us.next_revocation_hash);
assert(peer->state == STATE_INIT);
/* Using queue_cmd is overkill here, but it works. */
queue_cmd(peer, do_anchor_offer, NULL);
return io_duplex(conn,
peer_read_packet(conn, peer, pkt_in),
pkt_out(conn, peer));
}
static void destroy_peer(struct peer *peer)
{
if (peer->conn)
io_close(peer->conn);
list_del_from(&peer->dstate->peers, &peer->list);
}
static void peer_disconnect(struct io_conn *conn, struct peer *peer)
{
const struct bitcoin_tx *broadcast;
log_info(peer->log, "Disconnected");
/* No longer connected. */
peer->conn = NULL;
/* Not even set up yet? Simply free.*/
if (peer->state == STATE_INIT) {
tal_free(peer);
return;
}
/* FIXME: Try to reconnect. */
if (peer->cond == PEER_CLOSED)
return;
state(peer, INPUT_CONNECTION_LOST, NULL, &broadcast);
if (broadcast) {
struct sha256_double txid;
bitcoin_txid(broadcast, &txid);
/* FIXME: log_struct */
log_debug(peer->log, "INPUT_CONN_LOST: tx %02x%02x%02x%02x...",
txid.sha.u.u8[0], txid.sha.u.u8[1],
txid.sha.u.u8[2], txid.sha.u.u8[3]);
bitcoind_send_tx(peer->dstate, broadcast);
}
}
static struct peer *new_peer(struct lightningd_state *dstate,
struct io_conn *conn,
int addr_type, int addr_protocol,
enum state_input offer_anchor,
const char *in_or_out)
{
struct peer *peer = tal(dstate, struct peer);
assert(offer_anchor == CMD_OPEN_WITH_ANCHOR
|| offer_anchor == CMD_OPEN_WITHOUT_ANCHOR);
/* FIXME: Stop listening if too many peers? */
list_add(&dstate->peers, &peer->list);
peer->state = STATE_INIT;
peer->cond = PEER_CMD_OK;
peer->dstate = dstate;
peer->addr.type = addr_type;
peer->addr.protocol = addr_protocol;
peer->io_data = NULL;
peer->secrets = NULL;
list_head_init(&peer->watches);
peer->outpkt = tal_arr(peer, struct out_pkt, 0);
peer->curr_cmd.cmd = INPUT_NONE;
list_head_init(&peer->pending_cmd);
peer->commit_tx_counter = 0;
peer->close_watch_timeout = NULL;
peer->anchor.watches = NULL;
peer->cur_commit.watch = NULL;
peer->closing.their_sig = NULL;
peer->cleared = INPUT_NONE;
/* Make it different from other node (to catch bugs!), but a
* round number for simple eyeballing. */
peer->htlc_id_counter = pseudorand(1ULL << 32) * 1000;
/* If we free peer, conn should be closed, but can't be freed
* immediately so don't make peer a parent. */
peer->conn = conn;
io_set_finish(conn, peer_disconnect, peer);
peer->us.offer_anchor = offer_anchor;
if (!seconds_to_rel_locktime(dstate->config.rel_locktime,
&peer->us.locktime))
fatal("Invalid locktime configuration %u",
dstate->config.rel_locktime);
peer->us.mindepth = dstate->config.anchor_confirms;
peer->us.commit_fee_rate = dstate->config.commitment_fee_rate;
peer->us.commit = peer->them.commit = NULL;
peer->us.staging_cstate = peer->them.staging_cstate = NULL;
/* FIXME: Attach IO logging for this peer. */
tal_add_destructor(peer, destroy_peer);
peer->addr.addrlen = sizeof(peer->addr.saddr);
if (getpeername(io_conn_fd(conn), &peer->addr.saddr.s,
&peer->addr.addrlen) != 0) {
log_unusual(dstate->base_log,
"Could not get address for peer: %s",
strerror(errno));
return tal_free(peer);
}
peer->log = new_log(peer, dstate->log_record, "%s%s:%s:",
log_prefix(dstate->base_log), in_or_out,
netaddr_name(peer, &peer->addr));
return peer;
}
static struct io_plan *peer_connected_out(struct io_conn *conn,
struct lightningd_state *dstate,
struct json_connecting *connect)
{
/* Initiator currently funds channel */
struct peer *peer = new_peer(dstate, conn, SOCK_STREAM, IPPROTO_TCP,
CMD_OPEN_WITH_ANCHOR, "out");
if (!peer) {
command_fail(connect->cmd, "Failed to make peer for %s:%s",
connect->name, connect->port);
return io_close(conn);
}
log_info(peer->log, "Connected out to %s:%s",
connect->name, connect->port);
peer->anchor.satoshis = connect->satoshis;
command_success(connect->cmd, null_response(connect));
return peer_crypto_setup(conn, peer, peer_crypto_on);
}
static struct io_plan *peer_connected_in(struct io_conn *conn,
struct lightningd_state *dstate)
{
struct peer *peer = new_peer(dstate, conn, SOCK_STREAM, IPPROTO_TCP,
CMD_OPEN_WITHOUT_ANCHOR, "in");
if (!peer)
return io_close(conn);
log_info(peer->log, "Peer connected in");
return peer_crypto_setup(conn, peer, peer_crypto_on);
}
static int make_listen_fd(struct lightningd_state *dstate,
int domain, void *addr, socklen_t len)
{
int fd = socket(domain, SOCK_STREAM, 0);
if (fd < 0) {
log_debug(dstate->base_log, "Failed to create %u socket: %s",
domain, strerror(errno));
return -1;
}
if (!addr || bind(fd, addr, len) == 0) {
if (listen(fd, 5) == 0)
return fd;
log_unusual(dstate->base_log,
"Failed to listen on %u socket: %s",
domain, strerror(errno));
} else
log_debug(dstate->base_log, "Failed to bind on %u socket: %s",
domain, strerror(errno));
close_noerr(fd);
return -1;
}
void setup_listeners(struct lightningd_state *dstate, unsigned int portnum)
{
struct sockaddr_in addr;
struct sockaddr_in6 addr6;
socklen_t len;
int fd1, fd2;
u16 listen_port;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = INADDR_ANY;
addr.sin_port = htons(portnum);
addr6.sin6_family = AF_INET6;
addr6.sin6_addr = in6addr_any;
addr6.sin6_port = htons(portnum);
/* IPv6, since on Linux that (usually) binds to IPv4 too. */
fd1 = make_listen_fd(dstate, AF_INET6, portnum ? &addr6 : NULL,
sizeof(addr6));
if (fd1 >= 0) {
struct sockaddr_in6 in6;
len = sizeof(in6);
if (getsockname(fd1, (void *)&in6, &len) != 0) {
log_unusual(dstate->base_log,
"Failed get IPv6 sockname: %s",
strerror(errno));
close_noerr(fd1);
} else {
addr.sin_port = in6.sin6_port;
listen_port = ntohs(addr.sin_port);
log_info(dstate->base_log,
"Creating IPv6 listener on port %u",
listen_port);
io_new_listener(dstate, fd1, peer_connected_in, dstate);
}
}
/* Just in case, aim for the same port... */
fd2 = make_listen_fd(dstate, AF_INET,
addr.sin_port ? &addr : NULL, sizeof(addr));
if (fd2 >= 0) {
len = sizeof(addr);
if (getsockname(fd2, (void *)&addr, &len) != 0) {
log_unusual(dstate->base_log,
"Failed get IPv4 sockname: %s",
strerror(errno));
close_noerr(fd2);
} else {
listen_port = ntohs(addr.sin_port);
log_info(dstate->base_log,
"Creating IPv4 listener on port %u",
listen_port);
io_new_listener(dstate, fd2, peer_connected_in, dstate);
}
}
if (fd1 < 0 && fd2 < 0)
fatal("Could not bind to a network address");
}
static void peer_failed(struct lightningd_state *dstate,
struct json_connecting *connect)
{
/* FIXME: Better diagnostics! */
command_fail(connect->cmd, "Failed to connect to peer %s:%s",
connect->name, connect->port);
}
static void json_connect(struct command *cmd,
const char *buffer, const jsmntok_t *params)
{
struct json_connecting *connect;
jsmntok_t *host, *port, *satoshis;
if (!json_get_params(buffer, params,
"host", &host,
"port", &port,
"satoshis", &satoshis,
NULL)) {
command_fail(cmd, "Need host, port and satoshis");
return;
}
connect = tal(cmd, struct json_connecting);
connect->cmd = cmd;
connect->name = tal_strndup(connect, buffer + host->start,
host->end - host->start);
connect->port = tal_strndup(connect, buffer + port->start,
port->end - port->start);
if (!json_tok_u64(buffer, satoshis, &connect->satoshis))
command_fail(cmd, "'%.*s' is not a valid number",
(int)(satoshis->end - satoshis->start),
buffer + satoshis->start);
if (!dns_resolve_and_connect(cmd->dstate, connect->name, connect->port,
peer_connected_out, peer_failed, connect)) {
command_fail(cmd, "DNS failed");
return;
}
}
const struct json_command connect_command = {
"connect",
json_connect,
"Connect to a {host} at {port} offering anchor of {satoshis}",
"Returns an empty result on success"
};
struct anchor_watch {
struct peer *peer;
enum state_input depthok;
enum state_input timeout;
enum state_input unspent;
enum state_input theyspent;
enum state_input otherspent;
/* If timeout != INPUT_NONE, this is the timer. */
struct oneshot *timer;
};
static void anchor_depthchange(struct peer *peer, int depth,
const struct sha256_double *blkhash,
struct anchor_watch *w)
{
/* Still waiting for it to reach depth? */
if (w->depthok != INPUT_NONE) {
/* Beware sign! */
if (depth >= (int)peer->us.mindepth) {
enum state_input in = w->depthok;
w->depthok = INPUT_NONE;
/* We don't need the timeout timer any more. */
w->timer = tal_free(w->timer);
state_event(peer, in, NULL);
}
} else {
if (depth < 0 && w->unspent != INPUT_NONE) {
enum state_input in = w->unspent;
w->unspent = INPUT_NONE;
state_event(peer, in, NULL);
}
}
}
/* We don't compare scriptSigs: we don't know them anyway! */
static bool txmatch(const struct bitcoin_tx *txa, const struct bitcoin_tx *txb)
{
size_t i;
if (txa->version != txb->version
|| txa->input_count != txb->input_count
|| txa->output_count != txb->output_count
|| txa->lock_time != txb->lock_time)
return false;
for (i = 0; i < txa->input_count; i++) {
if (!structeq(&txa->input[i].txid, &txb->input[i].txid)
|| txa->input[i].index != txb->input[i].index
|| txa->input[i].sequence_number != txb->input[i].sequence_number)
return false;
}
for (i = 0; i < txa->output_count; i++) {
if (txa->output[i].amount != txb->output[i].amount
|| txa->output[i].script_length != txb->output[i].script_length
|| memcmp(txa->output[i].script, txb->output[i].script,
txa->output[i].script_length != 0))
return false;
}
return true;
}
/* We may have two possible "current" commits; this loop will check them both. */
static bool is_unrevoked_commit(const struct commit_info *ci,
const struct bitcoin_tx *tx)
{
while (ci && !ci->revocation_preimage) {
if (txmatch(ci->tx, tx))
return true;
ci = ci->prev;
}
return false;
}
/* A mutual close is a simple 2 output p2sh to the final addresses, but
* without knowing fee we can't determine order, so examine each output. */
static bool is_mutual_close(const struct peer *peer,
const struct bitcoin_tx *tx)
{
const u8 *ctx, *our_p2sh, *their_p2sh;
bool matches;
if (tx->output_count != 2)
return false;
if (!is_p2sh(tx->output[0].script, tx->output[0].script_length)
|| !is_p2sh(tx->output[1].script, tx->output[1].script_length))
return false;
/* FIXME: Cache these! */
ctx = tal(NULL, u8);
our_p2sh = scriptpubkey_p2sh(ctx,
bitcoin_redeem_single(tx, &peer->us.finalkey));
their_p2sh = scriptpubkey_p2sh(ctx,
bitcoin_redeem_single(tx, &peer->them.finalkey));
matches =
(memcmp(tx->output[0].script, our_p2sh, tal_count(our_p2sh)) == 0
&& memcmp(tx->output[1].script, their_p2sh, tal_count(their_p2sh)) == 0)
|| (memcmp(tx->output[0].script, their_p2sh, tal_count(their_p2sh)) == 0
&& memcmp(tx->output[1].script, our_p2sh, tal_count(our_p2sh)) == 0);
tal_free(ctx);
return matches;
}
static void close_depth_cb(struct peer *peer, int depth)
{
if (depth >= peer->dstate->config.forever_confirms) {
state_event(peer, BITCOIN_CLOSE_DONE, NULL);
}
}
/* We assume the tx is valid! Don't do a blockchain.info and feed this
* invalid transactions! */
static void anchor_spent(struct peer *peer,
const struct bitcoin_tx *tx,
struct anchor_watch *w)
{
union input idata;
/* FIXME: change type in idata? */
idata.btc = (struct bitcoin_event *)tx;
if (is_unrevoked_commit(peer->them.commit, tx))
state_event(peer, w->theyspent, &idata);
else if (is_mutual_close(peer, tx))
add_close_tx_watch(peer, peer, tx, close_depth_cb);
else
state_event(peer, w->otherspent, &idata);
}
static void anchor_timeout(struct anchor_watch *w)
{
assert(w == w->peer->anchor.watches);
state_event(w->peer, w->timeout, NULL);
/* Freeing this gets rid of the other watches, and timer, too. */
w->peer->anchor.watches = tal_free(w);
}
void peer_watch_anchor(struct peer *peer,
enum state_input depthok,
enum state_input timeout,
enum state_input unspent,
enum state_input theyspent,
enum state_input otherspent)
{
struct anchor_watch *w;
w = peer->anchor.watches = tal(peer, struct anchor_watch);
w->peer = peer;
w->depthok = depthok;
w->timeout = timeout;
w->unspent = unspent;
w->theyspent = theyspent;
w->otherspent = otherspent;
add_anchor_watch(w, peer, &peer->anchor.txid, peer->anchor.index,
anchor_depthchange,
anchor_spent,
w);
/* For anchor timeout, expect 20 minutes per block, +2 hours.
*
* Probability(no block in time N) = e^(-N/600).
* Thus for 1 block, P = e^(-(7200+1*1200)/600) = 0.83 in a million.
*
* Glenn Willen says, if we want to know how many 10-minute intervals for
* a 1 in a million chance of spurious failure for N blocks, put
* this into http://www.wolframalpha.com:
*
* e^(-x) * sum x^i / fact(i), i=0 to N < 1/1000000
*
* N=20: 51
* N=10: 35
* N=8: 31
* N=6: 28
* N=4: 24
* N=3: 22
* N=2: 20
*
* So, our formula of 12 + N*2 holds for N <= 20 at least.
*/
if (w->timeout != INPUT_NONE) {
w->timer = oneshot_timeout(peer->dstate, w,
7200 + 20*peer->us.mindepth,
anchor_timeout, w);
} else
w->timer = NULL;
}
void peer_unwatch_anchor_depth(struct peer *peer,
enum state_input depthok,
enum state_input timeout)
{
assert(peer->anchor.watches);
peer->anchor.watches = tal_free(peer->anchor.watches);
}
static void commit_tx_depth(struct peer *peer, int depth,
const struct sha256_double *blkhash,
ptrint_t *canspend)
{
log_debug(peer->log, "Commit tx reached depth %i", depth);
/* FIXME: Handle locktime in blocks, as well as seconds! */
/* Fell out of a block? */
if (depth < 0) {
/* Forget any old block. */
peer->cur_commit.start_time = 0;
memset(&peer->cur_commit.blockid, 0xFF,
sizeof(peer->cur_commit.blockid));
return;
}
/* In a new block? */
if (!structeq(blkhash, &peer->cur_commit.blockid)) {
peer->cur_commit.start_time = 0;
peer->cur_commit.blockid = *blkhash;
bitcoind_get_mediantime(peer->dstate, blkhash,
&peer->cur_commit.start_time);
return;
}
/* Don't yet know the median start time? */
if (!peer->cur_commit.start_time)
return;
/* FIXME: We should really use bitcoin time here. */
if (controlled_time().ts.tv_sec > peer->cur_commit.start_time
+ rel_locktime_to_seconds(&peer->them.locktime)) {
/* Free this watch; we're done */
peer->cur_commit.watch = tal_free(peer->cur_commit.watch);
state_event(peer, ptr2int(canspend), NULL);
}
}
/* FIXME: We tell bitcoind to watch all the outputs, which is overkill */
static void watch_tx_outputs(struct peer *peer, const struct bitcoin_tx *tx)
{
varint_t i;
for (i = 0; i < tx->output_count; i++) {
struct ripemd160 redeemhash;
if (!is_p2sh(tx->output[i].script, tx->output[i].script_length))
fatal("Unexpected non-p2sh output");
memcpy(&redeemhash, tx->output[i].script+2, sizeof(redeemhash));
bitcoind_watch_addr(peer->dstate, &redeemhash);
}
}
/* Watch the commit tx until our side is spendable. */
void peer_watch_delayed(struct peer *peer,
const struct bitcoin_tx *tx,
enum state_input canspend)
{
struct sha256_double txid;
/* We only ever spend the last one. */
assert(tx == peer->us.commit->tx);
bitcoin_txid(tx, &txid);
memset(&peer->cur_commit.blockid, 0xFF,
sizeof(peer->cur_commit.blockid));
peer->cur_commit.watch
= add_commit_tx_watch(tx, peer, &txid, commit_tx_depth,
int2ptr(canspend));
watch_tx_outputs(peer, tx);
}
static void spend_tx_done(struct peer *peer, int depth,
const struct sha256_double *blkhash,
ptrint_t *done)
{
log_debug(peer->log, "tx reached depth %i", depth);
if (depth >= (int)peer->dstate->config.forever_confirms)
state_event(peer, ptr2int(done), NULL);
}
uint64_t commit_tx_fee(const struct bitcoin_tx *commit, uint64_t anchor_satoshis)
{
uint64_t i, total = 0;
for (i = 0; i < commit->output_count; i++)
total += commit->output[i].amount;
assert(anchor_satoshis >= total);
return anchor_satoshis - total;
}
/* Watch this tx until it's buried enough to be forgotten. */
void peer_watch_tx(struct peer *peer,
const struct bitcoin_tx *tx,
enum state_input done)
{
struct sha256_double txid;
bitcoin_txid(tx, &txid);
log_debug(peer->log, "Watching tx %02x%02x%02x%02x...",
txid.sha.u.u8[0],
txid.sha.u.u8[1],
txid.sha.u.u8[2],
txid.sha.u.u8[3]);
add_commit_tx_watch(tx, peer, &txid, spend_tx_done, int2ptr(done));
}
struct bitcoin_tx *peer_create_close_tx(struct peer *peer, u64 fee)
{
struct channel_state cstate;
/* We don't need a deep copy here, just fee levels. */
cstate = *peer->us.staging_cstate;
if (!force_fee(&cstate, fee)) {
log_unusual(peer->log,
"peer_create_close_tx: can't afford fee %"PRIu64,
fee);
return NULL;
}
log_debug(peer->log,
"creating close-tx with fee %"PRIu64": to %02x%02x%02x%02x/%02x%02x%02x%02x, amounts %u/%u",
fee,
peer->us.finalkey.der[0], peer->us.finalkey.der[1],
peer->us.finalkey.der[2], peer->us.finalkey.der[3],
peer->them.finalkey.der[0], peer->them.finalkey.der[1],
peer->them.finalkey.der[2], peer->them.finalkey.der[3],
cstate.a.pay_msat / 1000,
cstate.b.pay_msat / 1000);
return create_close_tx(peer->dstate->secpctx, peer,
&peer->us.finalkey,
&peer->them.finalkey,
&peer->anchor.txid,
peer->anchor.index,
peer->anchor.satoshis,
cstate.a.pay_msat / 1000,
cstate.b.pay_msat / 1000);
}
void peer_calculate_close_fee(struct peer *peer)
{
/* Use actual worst-case length of close tx: based on BOLT#02's
* commitment tx numbers, but only 1 byte for output count */
const uint64_t txsize = 41 + 221 + 10 + 32 + 32;
uint64_t maxfee;
/* FIXME: Dynamic fee */
peer->closing.our_fee
= fee_by_feerate(txsize, peer->dstate->config.closing_fee_rate);
/* BOLT #2:
* The sender MUST set `close_fee` lower than or equal to the
* fee of the final commitment transaction and MUST set
* `close_fee` to an even number of satoshis.
*/
maxfee = commit_tx_fee(peer->us.commit->tx, peer->anchor.satoshis);
if (peer->closing.our_fee > maxfee) {
/* This shouldn't happen: we never accept a commit fee
* less than the min_rate, which is greater than the
* closing_fee_rate. Also, our txsize estimate for
* the closing tx is 2 bytes smaller than the commitment tx. */
log_unusual(peer->log,
"Closing fee %"PRIu64" exceeded commit fee %"PRIu64", reducing.",
peer->closing.our_fee, maxfee);
peer->closing.our_fee = maxfee;
/* This can happen if actual commit txfee is odd. */
if (peer->closing.our_fee & 1)
peer->closing.our_fee--;
}
assert(!(peer->closing.our_fee & 1));
}
bool peer_has_close_sig(const struct peer *peer)
{
return peer->closing.their_sig;
}
static void send_close_timeout(struct peer *peer)
{
/* FIXME: Remove any close_tx watches! */
state_event(peer, INPUT_CLOSE_COMPLETE_TIMEOUT, NULL);
}
void peer_watch_close(struct peer *peer,
enum state_input done, enum state_input timedout)
{
/* We save some work by assuming these. */
assert(done == BITCOIN_CLOSE_DONE);
/* FIXME: We can't send CLOSE, so timeout immediately */
if (!peer->conn) {
assert(timedout == INPUT_CLOSE_COMPLETE_TIMEOUT);
oneshot_timeout(peer->dstate, peer, 0,
send_close_timeout, peer);
return;
}
/* Give them a reasonable time to respond. */
/* FIXME: config? */
if (timedout != INPUT_NONE) {
assert(timedout == INPUT_CLOSE_COMPLETE_TIMEOUT);
peer->close_watch_timeout
= oneshot_timeout(peer->dstate, peer, 120,
send_close_timeout, peer);
}
/* anchor_spent will get called, we match against close_tx there. */
}
void peer_unwatch_close_timeout(struct peer *peer, enum state_input timedout)
{