commit c161f4d25ea5e484bc06b7f2381da7203e7945c3
parent 3ce5ac8682fc4bb84bf59317dab05ebb4efd1d41
Author: William Casarin <jb55@jb55.com>
Date: Sun, 16 Jan 2022 12:55:39 -0800
write message
Diffstat:
5 files changed, 43 insertions(+), 1 deletion(-)
diff --git a/crypto.c b/crypto.c
@@ -150,8 +150,12 @@ u8 *cryptomsg_encrypt_msg(struct crypto_state *cs, const u8 *msg, unsigned long
be16 l;
int ret;
- if (outcap < sizeof(l) + 16 + mlen + 16)
+ *outlen = sizeof(l) + 16 + mlen + 16;
+
+ if (outcap < *outlen) {
+ *outlen = 0;
return NULL;
+ }
/* BOLT #8:
*
diff --git a/crypto.h b/crypto.h
@@ -43,4 +43,6 @@ void hkdf_two_keys(struct secret *out1, struct secret *out2,
const struct secret *in1,
const struct secret *in2);
+unsigned char *cryptomsg_encrypt_msg(struct crypto_state *cs, const u8 *msg, unsigned long long mlen, u8 *out, size_t *outlen, size_t outcap);
+
#endif /* LNSOCKET_CRYPTO_H */
diff --git a/lnsocket.c b/lnsocket.c
@@ -74,6 +74,32 @@ static int pubkey_from_node_id(secp256k1_context *secp, struct pubkey *key,
sizeof(id->k));
}
+int lnsocket_write(struct lnsocket *ln, const u8 *msg, int msglen)
+{
+ // this is just temporary so we don't need to move the memory cursor
+ u8 *out = ln->mem.p;
+ ssize_t outcap = ln->mem.end - ln->mem.p;
+ ssize_t writelen;
+ size_t outlen;
+
+ if (!ln->socket)
+ return note_error(&ln->errs, "not connected");
+
+ if (outcap <= 0)
+ return note_error(&ln->errs, "out of memory");
+
+ if (!cryptomsg_encrypt_msg(&ln->crypto_state, msg, msglen, out, &outlen, (size_t)outcap))
+ return note_error(&ln->errs, "encrypt message failed, out of memory");
+
+ if ((writelen = write(ln->socket, out, outlen)) != outlen)
+ return note_error(&ln->errs,
+ "write failed. wrote %ld bytes, expected %ld %s",
+ writelen, outlen,
+ writelen < 0 ? strerror(errno) : "");
+
+ return 1;
+}
+
struct lnsocket *lnsocket_create_with(int memory)
{
struct cursor mem;
diff --git a/lnsocket.h b/lnsocket.h
@@ -4,6 +4,7 @@
struct lnsocket;
int lnsocket_connect(struct lnsocket *, const char *node_id, const char *host);
+int lnsocket_write(struct lnsocket *, const unsigned char *msg, int msg_len);
void lnsocket_genkey(struct lnsocket *);
struct lnsocket *lnsocket_create();
void lnsocket_destroy(struct lnsocket *);
diff --git a/test.c b/test.c
@@ -16,6 +16,15 @@ int main(int argc, const char *argv[])
}
printf("connected!\n");
+
+ const unsigned char msg[] = {'h', 'i'};
+
+ if (!lnsocket_write(ln, msg, sizeof(msg))) {
+ lnsocket_print_errors(ln);
+ goto done;
+ }
+
+ printf("wrote message.\n");
done:
lnsocket_destroy(ln);
return !ok;