lnsocket

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

commit c24430254fafb0881c6ad8071bc731bdf9c65394
parent 9e4962b3367becb598a6baaea34ef909de149aab
Author: William Casarin <jb55@jb55.com>
Date:   Mon, 21 Mar 2022 08:57:26 -0700

lnsocket/js: fix read_all

it was doing bad things

Signed-off-by: William Casarin <jb55@jb55.com>

Diffstat:
Mlnsocket.c | 11+++++------
Mlnsocket_lib.js | 27+++++++++++++--------------
2 files changed, 18 insertions(+), 20 deletions(-)

diff --git a/lnsocket.c b/lnsocket.c @@ -229,12 +229,11 @@ int EXPORT lnsocket_decrypt(struct lnsocket *ln, unsigned char *packet, int size // this is used in js int EXPORT lnsocket_decrypt_header(struct lnsocket *ln, unsigned char *hdr) { - u16 size; - if (!cryptomsg_decrypt_header(&ln->crypto_state, hdr, &size)) - return note_error(&ln->errs, - "Failed hdr decrypt with rn=%"PRIu64, - ln->crypto_state.rn-1); - + u16 size = 0; + if (!cryptomsg_decrypt_header(&ln->crypto_state, hdr, &size)) + return note_error(&ln->errs, + "Failed hdr decrypt with rn=%"PRIu64, + ln->crypto_state.rn-1); return size; } diff --git a/lnsocket_lib.js b/lnsocket_lib.js @@ -14,7 +14,8 @@ async function lnsocket_init() { const ws = new WebSocket(host) ws.ondata = function(fn) { ws.onmessage = (v) => { - fn(v.data.arrayBuffer()) + const data = v.data.arrayBuffer() + fn(data) } } return ws @@ -182,23 +183,21 @@ async function lnsocket_init() { if (!this.connected) throw new Error("read_all: not connected") while (true) { - const res = await this.queue_recv() - count += res.byteLength - if (count > n) { - //console.log("adding %d to count %d > n %d, queue: %d", res.byteLength, count, n, this.queue.length) - chunks.push(res.slice(0, n)) - const sliced = res.slice(n) - //console.log("unshifting %d bytes back to queue", sliced.byteLength) - this.queue.unshift(sliced) + let res = await this.queue_recv() + + const remaining = n - count + + if (res.byteLength > remaining) { + chunks.push(res.slice(0, remaining)) + this.queue.unshift(res.slice(remaining)) break - } else if (count === n) { - //console.log("count %d === n %d, queue: %d", count, n, this.queue.length) + } else if (res.byteLength === remaining) { chunks.push(res) break - } else { - //console.log("count %d < n %d, queue: %d", count, n, this.queue.length) - chunks.push(res) } + + chunks.push(res) + count += res.byteLength } return concat_u8_arrays(chunks)