From 6cabea563e17d3cac984fde4453c630421d05222 Mon Sep 17 00:00:00 2001 From: Conner Fromknecht Date: Fri, 22 Nov 2019 02:24:44 -0800 Subject: [PATCH] channeldb/invoices: optimize deserializeHtlcs Instead of allocating a byte slice to read in each htlc's raw TLV stream, use a LimitReader to truncate the stream to the proper length. --- channeldb/invoices.go | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/channeldb/invoices.go b/channeldb/invoices.go index 1f17d5f3b..eaedd1781 100644 --- a/channeldb/invoices.go +++ b/channeldb/invoices.go @@ -1132,7 +1132,7 @@ func deserializeHtlcs(r io.Reader) (map[CircuitKey]*InvoiceHTLC, error) { for { // Read the length of the tlv stream for this htlc. - var streamLen uint64 + var streamLen int64 if err := binary.Read(r, byteOrder, &streamLen); err != nil { if err == io.EOF { break @@ -1141,11 +1141,9 @@ func deserializeHtlcs(r io.Reader) (map[CircuitKey]*InvoiceHTLC, error) { return nil, err } - streamBytes := make([]byte, streamLen) - if _, err := r.Read(streamBytes); err != nil { - return nil, err - } - streamReader := bytes.NewReader(streamBytes) + // Limit the reader so that it stops at the end of this htlc's + // stream. + htlcReader := io.LimitReader(r, streamLen) // Decode the contents into the htlc fields. var ( @@ -1172,7 +1170,7 @@ func deserializeHtlcs(r io.Reader) (map[CircuitKey]*InvoiceHTLC, error) { return nil, err } - if err := tlvStream.Decode(streamReader); err != nil { + if err := tlvStream.Decode(htlcReader); err != nil { return nil, err }