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
```
This commit is contained in:
Olaoluwa Osuntokun committed 2025-09-24 11:52:01 -07:00
1 parent 1fe156f2f4
commit 83e2811903
1 file changed
+5 -3
+5 -3
View File
@@ -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)