diff --git a/node/lux_node_sync.go b/node/lux_node_sync.go index 5fe85ad..feb4325 100644 --- a/node/lux_node_sync.go +++ b/node/lux_node_sync.go @@ -1,9 +1,7 @@ package node import ( - "fmt" "lux/proto" - "net/netip" ipnet "net" ) @@ -48,25 +46,10 @@ func (sync *LuxNodeSync) Read(rd *proto.LuxBuffer) error { return err } - ipOctets, err := rd.ReadVarBlock() + addrPort, err := rd.ReadIPPort() if err != nil { return err } - portNum, err := rd.ReadUint16() - if err != nil { - return err - } - - // TODO: move this to proto - var addrPort netip.AddrPort - switch len(ipOctets) { - case ipnet.IPv4len: - addrPort = netip.AddrPortFrom(netip.AddrFrom4([4]byte(ipOctets)), portNum) - case ipnet.IPv6len: - addrPort = netip.AddrPortFrom(netip.AddrFrom16([16]byte(ipOctets)), portNum) - default: - return fmt.Errorf("received wrong sized neighbor ip len %d", len(ipOctets)) - } sync.Neighbors[id] = ipnet.UDPAddrFromAddrPort(addrPort) } diff --git a/proto/lux_buffer.go b/proto/lux_buffer.go index edd33ed..f9e708e 100644 --- a/proto/lux_buffer.go +++ b/proto/lux_buffer.go @@ -3,6 +3,8 @@ package proto import ( "encoding/binary" "fmt" + "net" + "net/netip" ) var NO = binary.BigEndian @@ -191,3 +193,56 @@ func (buf *LuxBuffer) ReadString() (string, error) { func (buf *LuxBuffer) WriteString(val string) { buf.WriteVarBlock([]byte(val)) } + +func (buf *LuxBuffer) ReadIP() (netip.Addr, error) { + var addr netip.Addr + + ipOctets, err := buf.ReadVarBlock() + if err != nil { + return addr, err + } + + switch len(ipOctets) { + case net.IPv4len: + addr = netip.AddrFrom4([4]byte(ipOctets)) + case net.IPv6len: + addr = netip.AddrFrom16([16]byte(ipOctets)) + default: + return addr, fmt.Errorf("wrong ip size %d", len(ipOctets)) + } + + return addr, nil +} + +func (buf *LuxBuffer) WriteIP(addr netip.Addr) { + if addr.Is4() { + octets := addr.As4() + buf.WriteVarBlock(octets[:]) + } else if addr.Is6() { + octets := addr.As16() + buf.WriteVarBlock(octets[:]) + } else { + panic("WriteIP addr is neither IPv4 nor IPv6") + } +} + +func (buf *LuxBuffer) ReadIPPort() (netip.AddrPort, error) { + var addrPort netip.AddrPort + + addr, err := buf.ReadIP() + if err != nil { + return addrPort, err + } + + portNum, err := buf.ReadUint16() + if err != nil { + return addrPort, err + } + + return netip.AddrPortFrom(addr, portNum), nil +} + +func (buf *LuxBuffer) WriteIPPort(addrPort netip.AddrPort) { + buf.WriteIP(addrPort.Addr()) + buf.WriteUint16(addrPort.Port()) +}