From 7999d56959d8fedc12e7599bfbda4b6ac374a6bc Mon Sep 17 00:00:00 2001 From: mykola2312 <49044616+mykola2312@users.noreply.github.com> Date: Sat, 18 Jan 2025 16:06:45 +0200 Subject: [PATCH] implement sync deserialization --- node/lux_node_sync.go | 68 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) diff --git a/node/lux_node_sync.go b/node/lux_node_sync.go index 95c7a37..5fe85ad 100644 --- a/node/lux_node_sync.go +++ b/node/lux_node_sync.go @@ -1,7 +1,9 @@ package node import ( + "fmt" "lux/proto" + "net/netip" ipnet "net" ) @@ -11,3 +13,69 @@ type LuxNodeSync struct { Neighbors map[proto.LuxID]*ipnet.UDPAddr SyncState LuxNodeState } + +func NewLuxNodeSync() LuxNodeSync { + return LuxNodeSync{ + Synced: make(map[proto.LuxID]struct{}), + Neighbors: make(map[proto.LuxID]*ipnet.UDPAddr), + SyncState: LuxNodeState{}, + } +} + +func (sync *LuxNodeSync) Read(rd *proto.LuxBuffer) error { + // read synced list + syncNum, err := rd.ReadUint16() + if err != nil { + return err + } + for i := 0; i < int(syncNum); i++ { + id := proto.LuxID{} + if err := id.Read(rd); err != nil { + return err + } + + sync.Synced[id] = struct{}{} + } + + // read neighbors + neighborNum, err := rd.ReadUint16() + if err != nil { + return err + } + for i := 0; i < int(neighborNum); i++ { + id := proto.LuxID{} + if err := id.Read(rd); err != nil { + return err + } + + ipOctets, err := rd.ReadVarBlock() + 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) + } + + // read sync state + err = sync.SyncState.Read(rd) + if err != nil { + return err + } + + return nil +}