lnsocket

A minimal C library for connecting to the lightning network
git clone git://jb55.com/lnsocket
Log | Files | Refs | Submodules | README | LICENSE

commit b221c4ba76229494036ba4d633a3c90769b94e9e
parent 4f5d44b93f70e0c6c457c6277d77c56d3834107d
Author: William Casarin <jb55@jb55.com>
Date:   Sat, 22 Jan 2022 13:54:06 -0800

lnrpc: support timeouts

so that it doesn't hang if it doesn't have commando

Diffstat:
Mlnsocket.c | 6++++++
Mlnsocket.h | 1+
Mrpc.c | 29+++++++++++++++++++++++++++++
3 files changed, 36 insertions(+), 0 deletions(-)

diff --git a/lnsocket.c b/lnsocket.c @@ -474,6 +474,12 @@ int lnsocket_connect(struct lnsocket *ln, const char *node_id, const char *host) return act_one_initiator(ln, &h); } +int lnsocket_fd(struct lnsocket *ln, int *fd) +{ + *fd = ln->socket; + return 1; +} + void lnsocket_genkey(struct lnsocket *ln) { ln->key = generate_key(ln->secp); diff --git a/lnsocket.h b/lnsocket.h @@ -70,6 +70,7 @@ int lnsocket_perform_init(struct lnsocket *ln); int lnsocket_connect(struct lnsocket *, const char *node_id, const char *host); +int lnsocket_fd(struct lnsocket *, int *fd); int lnsocket_write(struct lnsocket *, const unsigned char *msg, unsigned short msg_len); int lnsocket_read(struct lnsocket *, unsigned char **buf, unsigned short *len); diff --git a/rpc.c b/rpc.c @@ -21,11 +21,23 @@ int main(int argc, const char *argv[]) static u8 msgbuf[4096]; u8 *buf; struct lnsocket *ln; + fd_set set; + struct timeval timeout; + + char *timeout_str; u16 len, msgtype; int ok = 1; + int socket, rv; int verbose = getenv("VERBOSE") != 0; //int verbose = 1; + timeout_str = getenv("LNRPC_TIMEOUT"); + int timeout_ms = timeout_str ? atoi(timeout_str) : 5000; + + timeout.tv_usec = 1000 * timeout_ms; + + FD_ZERO(&set); /* clear the set */ + if (argc < 5) return usage(); @@ -43,6 +55,11 @@ int main(int argc, const char *argv[]) if (!(ok = lnsocket_connect(ln, nodeid, host))) goto done; + if (!(ok = lnsocket_fd(ln, &socket))) + goto done; + + FD_SET(socket, &set); /* add our file descriptor to the set */ + if (!(ok = lnsocket_perform_init(ln))) goto done; @@ -59,6 +76,18 @@ int main(int argc, const char *argv[]) fprintf(stderr, "waiting for response...\n"); while (1) { + rv = select(socket + 1, &set, NULL, NULL, &timeout); + + if (rv == -1) { + perror("select"); + ok = 0; + goto done; + } else if (rv == 0) { + fprintf(stderr, "error: rpc request timeout\n"); + ok = 0; + goto done; + } + if (!(ok = lnsocket_recv(ln, &msgtype, &buf, &len))) goto done;