From 66ebf7c91ea383f115f06b5f9728906f6da2f9bb Mon Sep 17 00:00:00 2001 From: Kleissner Date: Wed, 7 Jul 2021 02:50:12 +0200 Subject: [PATCH] New DHT function IsNodeContact to check if node is in local routing table --- Kademlia.go | 12 ++++++++++++ dht/DHT Lite.go | 5 +++++ dht/Hash Table.go | 16 ++++++++++------ 3 files changed, 27 insertions(+), 6 deletions(-) diff --git a/Kademlia.go b/Kademlia.go index 1e34970..c92a4e7 100644 --- a/Kademlia.go +++ b/Kademlia.go @@ -163,3 +163,15 @@ func StoreDataDHT(data []byte) error { } return nodesDHT.Store(key, uint64(len(data))) } + +// ---- NODE FUNCTIONS ---- + +// IsNodeContact checks if the node is a contact in the local DHT routing table +func IsNodeContact(nodeID []byte) (node *dht.Node, peer *PeerInfo) { + node = nodesDHT.IsNodeContact(nodeID) + if node == nil { + return nil, nil + } + + return node, node.Info.(*PeerInfo) +} diff --git a/dht/DHT Lite.go b/dht/DHT Lite.go index 20804fb..f0dd134 100644 --- a/dht/DHT Lite.go +++ b/dht/DHT Lite.go @@ -96,6 +96,11 @@ func (dht *DHT) IsNodeCloser(node1, node2 []byte) bool { return iDist.Cmp(jDist) == -1 } +// IsNodeContact checks if the given node is in the local routing table +func (dht *DHT) IsNodeContact(ID []byte) (node *Node) { + return dht.ht.doesNodeExist(ID) +} + // ---- Synchronous network query functions below ---- // Store informs the network about data stored locally. diff --git a/dht/Hash Table.go b/dht/Hash Table.go index c3ea3b2..ae022fa 100644 --- a/dht/Hash Table.go +++ b/dht/Hash Table.go @@ -74,15 +74,19 @@ func (ht *hashTable) markNodeAsSeen(index int, ID []byte) { ht.RoutingTable[index] = bucket } -func (ht *hashTable) doesNodeExistInBucket(bucket int, node []byte) bool { +func (ht *hashTable) doesNodeExistInBucket(bucket int, ID []byte) (node *Node) { ht.mutex.RLock() defer ht.mutex.RUnlock() - for _, v := range ht.RoutingTable[bucket] { - if bytes.Compare(v.ID, node) == 0 { - return true + for _, node = range ht.RoutingTable[bucket] { + if bytes.Compare(node.ID, ID) == 0 { + return node } } - return false + return nil +} + +func (ht *hashTable) doesNodeExist(ID []byte) (node *Node) { + return ht.doesNodeExistInBucket(ht.getBucketIndexFromDifferingBit(ID), ID) } // getClosestContacts returns the closest nodes to the target. filterFunc is optional and allows the caller to filter the nodes. @@ -140,7 +144,7 @@ func (ht *hashTable) insertNode(node *Node, shouldEvict func(nodeOld *Node, node index := ht.getBucketIndexFromDifferingBit(node.ID) // If the node already exist, mark it as seen - if ht.doesNodeExistInBucket(index, node.ID) { + if ht.doesNodeExistInBucket(index, node.ID) != nil { ht.markNodeAsSeen(index, node.ID) return }