From 83e2811903fd0cc0f26e24c4dcefcd3842741ef0 Mon Sep 17 00:00:00 2001 From: Olaoluwa Osuntokun Date: Sat, 30 Aug 2025 14:49:45 +0100 Subject: [PATCH] brontide: use a static buffer for the packet length In this commit, we eliminate the final allocation that takes place when we write out messages. Once again this was escaping to the heap, so we make it an attribute on the Machine struct, which allows pure static allocation. ``` goos: darwin goarch: arm64 pkg: github.com/lightningnetwork/lnd/brontide cpu: Apple M4 Max BenchmarkWriteMessage-16 25840 46376 ns/op 2 B/op 0 allocs/op BenchmarkWriteMessage-16 25646 46672 ns/op 2 B/op 0 allocs/op BenchmarkWriteMessage-16 25874 46391 ns/op 2 B/op 0 allocs/op BenchmarkWriteMessage-16 25512 46427 ns/op 2 B/op 0 allocs/op BenchmarkWriteMessage-16 25760 46309 ns/op 2 B/op 0 allocs/op BenchmarkWriteMessage-16 25789 46520 ns/op 2 B/op 0 allocs/op BenchmarkWriteMessage-16 25602 46619 ns/op 2 B/op 0 allocs/op BenchmarkWriteMessage-16 25766 46464 ns/op 2 B/op 0 allocs/op BenchmarkWriteMessage-16 25820 46487 ns/op 2 B/op 0 allocs/op BenchmarkWriteMessage-16 25634 46553 ns/op 2 B/op 0 allocs/op PASS ok github.com/lightningnetwork/lnd/brontide 16.907s ``` --- brontide/noise.go | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/brontide/noise.go b/brontide/noise.go index 56c4c340b..bdd922841 100644 --- a/brontide/noise.go +++ b/brontide/noise.go @@ -385,6 +385,9 @@ type Machine struct { // (of the next ciphertext), followed by a 16 byte MAC. nextCipherHeader [encHeaderSize]byte + // pktLenBuffer is a reusable buffer for encoding the packet length. + pktLenBuffer [lengthHeaderSize]byte + // nextHeaderSend holds a reference to the remaining header bytes to // write out for a pending message. This allows us to tolerate timeout // errors that cause partial writes. @@ -751,11 +754,10 @@ func (b *Machine) WriteMessage(p []byte) error { // NOT include the MAC. fullLength := uint16(len(p)) - var pktLen [2]byte - binary.BigEndian.PutUint16(pktLen[:], fullLength) + binary.BigEndian.PutUint16(b.pktLenBuffer[:], fullLength) // First, generate the encrypted+MAC'd length prefix for the packet. - b.nextHeaderSend = b.sendCipher.Encrypt(nil, nil, pktLen[:]) + b.nextHeaderSend = b.sendCipher.Encrypt(nil, nil, b.pktLenBuffer[:]) // Finally, generate the encrypted packet itself. b.nextBodySend = b.sendCipher.Encrypt(nil, nil, p)