lnwire: let DNSAddress implement RecordProducer

In preparation for using this type as a TLV record, we let it implement
the RecordProducer interface.
This commit is contained in:
Elle Mouton committed 2025-10-01 13:49:15 +02:00
1 parent e9a4f22dd6
commit e24dd2f9e0
3 files changed
+204

No files matched your search

+71
View File
@@ -1,10 +1,14 @@
package lnwire
import (
"bytes"
"errors"
"fmt"
"io"
"net"
"strconv"
"github.com/lightningnetwork/lnd/tlv"
)
var (
@@ -86,3 +90,70 @@ func ValidateDNSAddr(hostname string, port uint16) error {
return nil
}
// Record returns a TLV record that can be used to encode/decode the DNSAddress.
//
// NOTE: this is part of the tlv.RecordProducer interface.
func (d *DNSAddress) Record() tlv.Record {
sizeFunc := func() uint64 {
// Hostname length + 2 bytes for port.
return uint64(len(d.Hostname) + 2)
}
return tlv.MakeDynamicRecord(
0, d, sizeFunc, dnsAddressEncoder, dnsAddressDecoder,
)
}
// dnsAddressEncoder is a TLV encoder for DNSAddress.
func dnsAddressEncoder(w io.Writer, val any, _ *[8]byte) error {
if v, ok := val.(*DNSAddress); ok {
var buf bytes.Buffer
// Write the hostname as raw bytes (no length prefix for TLV).
if _, err := buf.WriteString(v.Hostname); err != nil {
return err
}
// Write the port as 2 bytes.
err := WriteUint16(&buf, v.Port)
if err != nil {
return err
}
_, err = w.Write(buf.Bytes())
return err
}
return tlv.NewTypeForEncodingErr(val, "DNSAddress")
}
// dnsAddressDecoder is a TLV decoder for DNSAddress.
func dnsAddressDecoder(r io.Reader, val any, _ *[8]byte,
l uint64) error {
if v, ok := val.(*DNSAddress); ok {
if l < 2 {
return fmt.Errorf("DNS address must be at least 2 " +
"bytes")
}
// Read hostname (all bytes except last 2).
hostnameLen := l - 2
hostnameBytes := make([]byte, hostnameLen)
if _, err := io.ReadFull(r, hostnameBytes); err != nil {
return err
}
v.Hostname = string(hostnameBytes)
// Read port (last 2 bytes).
if err := ReadElement(r, &v.Port); err != nil {
return err
}
return ValidateDNSAddr(v.Hostname, v.Port)
}
return tlv.NewTypeForDecodingErr(val, "DNSAddress", l, 0)
}